gpt4 book ai didi

c# - 在 ASP.NET WebForms NOT MVC 中使用带有 token 的 OAuth 进行 Azure 身份验证

转载 作者:行者123 更新时间:2023-12-02 07:24:40 25 4
gpt4 key购买 nike

我想使用 OAuth 为我的 WebForms 实现 Azure 身份验证(它对我有用)。身份验证后,我需要 token 在服务器端进行验证,它将在每个客户端代码中进行验证。但身份验证后我没有获得 token

我创建了一个启动类并使用 owin 配置它,它可以正确进行身份验证,但在身份验证后无法获取 token 。

启动类

using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
using System;
using System.Threading.Tasks;

[assembly: OwinStartup(typeof(Manager.Startup))]

namespace Manager
{
public class Startup
{
// The Client ID is used by the application to uniquely identify itself to Azure AD.
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];

// RedirectUri is the URL where the user will be redirected to after they sign in.
string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];

// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];

// Authority is the URL for authority, composed by Azure Active Directory v2 endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);

/// <summary>
/// Configure OWIN to use OpenIdConnect
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Sets the ClientId, authority, RedirectUri as obtained from web.config
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
// PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
PostLogoutRedirectUri = redirectUri,
Scope = OpenIdConnectScope.OpenIdProfile,
// ResponseType is set to request the id_token - which contains basic information about the signed-in user
ResponseType = OpenIdConnectResponseType.IdToken,
// ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
// To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
// To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
// OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed
}
}
);
}

/// <summary>
/// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("/?errormessage=" + context.Exception.Message);
return Task.FromResult(0);
}
}
}

页面加载

 protected void Page_Load(object sender, EventArgs e)
{
if (!Request.IsAuthenticated)
{
Context.GetOwinContext().Authentication.Challenge(new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);

// below codes are tested but all are giving null or empty string

var claimsIdentity = User.Identity as ClaimsIdentity;
string str = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Name)?.Value;
string accessToken = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == "access_token")?.Value;
string idToken = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == "id_token")?.Value;
string refreshToken = claimsIdentity?.Claims.FirstOrDefault(c => c.Type == "refresh_token")?.Value;
str = User.Identity.Name;
GetTokenForApplication().Wait(); ;
}

}

认证后预期结果为Token实际结果是认证后没有拿到token

最佳答案

token 不会包含在claimsIdentity中。通过OpenIdConnect协议(protocol)获取asp.net中的访问 token 。您需要重写 AuthorizationCodeReceived 方法来获取访问 token 。

using System;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
using System.IdentityModel.Claims;
using ToDoGraphDemo.TokenStorage;
using System.Web;
using Microsoft.Identity.Client;

[assembly: OwinStartup(typeof(ToDoGraphDemo.Startup))]

namespace ToDoGraphDemo
{
public class Startup
{
// The Client ID is used by the application to uniquely identify itself to Azure AD.
string clientId = ConfigurationManager.AppSettings["ClientId"];
// RedirectUri is the URL where the user will be redirected to after they sign in.
string redirectUri = ConfigurationManager.AppSettings["RedirectUri"];
// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = ConfigurationManager.AppSettings["Tenant"];
// Authority is the URL for authority, composed by Azure Active Directory v2 endpoint
// and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com/v2.0)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture,
ConfigurationManager.AppSettings["Authority"], tenant);
// Scopes are the specific permissions we are requesting for the application.
string scopes = ConfigurationManager.AppSettings["Scopes"];
// ClientSecret is a password associated with the application in the authority.
// It is used to obtain an access token for the user on server-side apps.
string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];

/// <summary>
/// Configure OWIN to use OpenIdConnect
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUri,
PostLogoutRedirectUri = redirectUri,
Scope = "openid email profile offline_access " + scopes,

// TokenValidationParameters allows you to control the users who are allowed to sign in
// to your application. In this demo we only allow users associated with the specified tenant.
// If ValidateIssuer is set to false, anybody with a personal or work Microsoft account can
// sign in.
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
{
ValidateIssuer = true,
ValidIssuer = tenant
},

// OpenIdConnect event handlers/callbacks.
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthorizationCodeReceived = OnAuthorizationCodeReceived,
AuthenticationFailed = OnAuthenticationFailed
}
});
}

/// <summary>
/// Handle authorization codes by creating a token cache then requesting and storing an access token
/// for the user.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedNotification context)
{
string userId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
TokenCache userTokenCache = new SessionTokenCache(
userId, context.OwinContext.Environment["System.Web.HttpContextBase"] as HttpContextBase).GetMsalCacheInstance();
// A ConfidentialClientApplication is a server-side client application that can securely store a client secret,
// which is not accessible by the user.
ConfidentialClientApplication cca = new ConfidentialClientApplication(
clientId, redirectUri, new ClientCredential(clientSecret), userTokenCache, null);
string[] scopes = this.scopes.Split(new char[] { ' ' });

AuthenticationResult result = await cca.AcquireTokenByAuthorizationCodeAsync(context.Code, scopes);
var accessToken = result.AccessToken;
}

/// <summary>
/// Handle failed authentication requests by redirecting the user to the home page with an error in the query string.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("/?errormessage=" + context.Exception.Message);
return Task.FromResult(0);
}
}
}

这是一个sample供您引用。

关于c# - 在 ASP.NET WebForms NOT MVC 中使用带有 token 的 OAuth 进行 Azure 身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57519054/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com