将未经身份验证的页面添加到启用了 AAD 的 AppService
Add Unauthenticated Pages to a AppService with AAD enabled
我使用此 URl 中的说明启用了 AAD Oauth。它按此处设计和解释的方式工作。
https://docs.microsoft.com/en-us/azure/app-service/configure-authentication-provider-aad 使用快速设置配置
但是我想向我的站点添加一些不需要身份验证的 URL,或者我只想对某些页面进行身份验证。此设置使每个页面都经过身份验证,而有些则没有。如何添加规则以避免某些页面的 AAD 身份验证?
据我所知,如果我们使用app service easy auth,我们无法确定哪些页面需要认证。所以我们需要用自己的代码来实现它。详细步骤如下。
注册 Azure AD 应用程序
当注册应用程序页面出现时,输入您的应用程序的注册信息:
一个。在 Name
部分,输入一个有意义的应用程序名称,该名称将显示给应用程序的用户,例如 ASPNET-Quickstart
.
b。在重定向 URI 中添加 <your web app url>
,然后单击注册。
c。在“管理”部分下的左侧导航窗格中,select Authentication
在隐式授予子部分下,select ID 令牌。
然后select保存。
更新项目
一种。安装包
Install-Package Microsoft.Owin.Security.OpenIdConnect
Install-Package Microsoft.Owin.Security.Cookies
Install-Package Microsoft.Owin.Host.SystemWeb
b。添加 OWIN 启动 Class
using System;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Notifications;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
[assembly: OwinStartup(typeof(WebappAD.Startup))]
namespace WebappAD
{
public class Startup
{
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
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 // This is a simplification
},
// 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);
}
}
}
c。更新web.config
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientId" value="Enter_the_Application_Id_here" />
<add key="redirectUri" value="Enter_the_Redirect_URL_here" />
<add key="Tenant" value="common" />
<add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />
</appSettings>
d.在您的控制器中添加登录方法
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
e。使用它
[Authorize] // add it on the method you need to authenticate
详情请参考document
您可以将 Action to take when request is not authenticated
设置为 allow anonymous
。然后在您的根文件夹中包含文件 authorization.json
或 authorization.yaml
在该文件中,您可以为 exclude/include 需要 authentication/authorisation.
的网址定义规则
有关示例,请参阅 https://azure.github.io/AppService/2016/11/17/URL-Authorization-Rules.html
我使用此 URl 中的说明启用了 AAD Oauth。它按此处设计和解释的方式工作。 https://docs.microsoft.com/en-us/azure/app-service/configure-authentication-provider-aad 使用快速设置配置
但是我想向我的站点添加一些不需要身份验证的 URL,或者我只想对某些页面进行身份验证。此设置使每个页面都经过身份验证,而有些则没有。如何添加规则以避免某些页面的 AAD 身份验证?
据我所知,如果我们使用app service easy auth,我们无法确定哪些页面需要认证。所以我们需要用自己的代码来实现它。详细步骤如下。
注册 Azure AD 应用程序 当注册应用程序页面出现时,输入您的应用程序的注册信息:
一个。在
Name
部分,输入一个有意义的应用程序名称,该名称将显示给应用程序的用户,例如ASPNET-Quickstart
.b。在重定向 URI 中添加
<your web app url>
,然后单击注册。c。在“管理”部分下的左侧导航窗格中,select
Authentication
在隐式授予子部分下,select ID 令牌。 然后select保存。更新项目 一种。安装包
Install-Package Microsoft.Owin.Security.OpenIdConnect Install-Package Microsoft.Owin.Security.Cookies Install-Package Microsoft.Owin.Host.SystemWeb
b。添加 OWIN 启动 Class
using System;
using System.Threading.Tasks;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Notifications;
using Microsoft.Owin.Security.OpenIdConnect;
using Owin;
[assembly: OwinStartup(typeof(WebappAD.Startup))]
namespace WebappAD
{
public class Startup
{
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
string redirectUri = System.Configuration.ConfigurationManager.AppSettings["RedirectUri"];
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
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 // This is a simplification
},
// 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);
}
}
}
c。更新web.config
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientId" value="Enter_the_Application_Id_here" />
<add key="redirectUri" value="Enter_the_Redirect_URL_here" />
<add key="Tenant" value="common" />
<add key="Authority" value="https://login.microsoftonline.com/{0}/v2.0" />
</appSettings>
d.在您的控制器中添加登录方法
public void SignIn()
{
if (!Request.IsAuthenticated)
{
HttpContext.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
}
e。使用它
[Authorize] // add it on the method you need to authenticate
详情请参考document
您可以将 Action to take when request is not authenticated
设置为 allow anonymous
。然后在您的根文件夹中包含文件 authorization.json
或 authorization.yaml
在该文件中,您可以为 exclude/include 需要 authentication/authorisation.
的网址定义规则有关示例,请参阅 https://azure.github.io/AppService/2016/11/17/URL-Authorization-Rules.html