在 ASP.NET WebForms NOT MVC 中使用带有令牌的 OAuth 进行 Azure 身份验证
Azure Authentication using OAuth with token in ASP.NET WebForms NOT MVC
我想使用 OAuth 为我的 WebForms 实施 Azure 身份验证(它对我有用)。身份验证后,我需要令牌在服务器端进行验证,它将在每个客户端代码中进行验证。但是我在认证后没有得到令牌
我创建了一个启动程序 class 并使用 owin 配置它,它正确地进行了身份验证,但在身份验证后无法获取令牌。
启动class
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
令牌不会包含在 claimsIdentity 中。使用 OpenIdConnect 协议获取 asp.net 中的访问令牌。您需要覆盖 AuthorizationCodeReceived
方法来获取访问令牌。
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供大家参考。
您的 Page_Load 使用了不正确的逻辑。将注释下的所有代码(// 下面的代码...)移动到 'if !Request.IsAuthenticated' 的 'else' 子句中。 if 语句会将用户重定向到 AAD 进行身份验证。验证后,再次执行该方法时,您将陷入 'else' 子句。此外,当您在 'else' 子句中时,id_token 已经过验证并转换为 ClaimsPrincipal。 id_token 中的所有声明都被转换成其声明包中的单独项目 - 只需遍历该包以查看那里有什么(最好还是使用这个 sample)。您可以在 Fiddler 中看到线路上发生的一切。
由于您只进行身份验证(scope = OpenIdProfile 和 responsetype=idToken),您将不会获得任何刷新或访问令牌。后者仅在您的应用需要调用另一个 API 时才需要。刷新是由 AAD 保留会话 cookie 完成的。您还应该创建一个用户身份验证 cookie,它与 id_token 的有效期相同,并在其过期时重新进行身份验证。此 sample 特定于 WebForms。
我想使用 OAuth 为我的 WebForms 实施 Azure 身份验证(它对我有用)。身份验证后,我需要令牌在服务器端进行验证,它将在每个客户端代码中进行验证。但是我在认证后没有得到令牌
我创建了一个启动程序 class 并使用 owin 配置它,它正确地进行了身份验证,但在身份验证后无法获取令牌。
启动class
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
令牌不会包含在 claimsIdentity 中。使用 OpenIdConnect 协议获取 asp.net 中的访问令牌。您需要覆盖 AuthorizationCodeReceived
方法来获取访问令牌。
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供大家参考。
您的 Page_Load 使用了不正确的逻辑。将注释下的所有代码(// 下面的代码...)移动到 'if !Request.IsAuthenticated' 的 'else' 子句中。 if 语句会将用户重定向到 AAD 进行身份验证。验证后,再次执行该方法时,您将陷入 'else' 子句。此外,当您在 'else' 子句中时,id_token 已经过验证并转换为 ClaimsPrincipal。 id_token 中的所有声明都被转换成其声明包中的单独项目 - 只需遍历该包以查看那里有什么(最好还是使用这个 sample)。您可以在 Fiddler 中看到线路上发生的一切。
由于您只进行身份验证(scope = OpenIdProfile 和 responsetype=idToken),您将不会获得任何刷新或访问令牌。后者仅在您的应用需要调用另一个 API 时才需要。刷新是由 AAD 保留会话 cookie 完成的。您还应该创建一个用户身份验证 cookie,它与 id_token 的有效期相同,并在其过期时重新进行身份验证。此 sample 特定于 WebForms。