Добавление неаутентифицированных страниц в сервис приложений с включенным AAD - PullRequest
0 голосов
/ 12 ноября 2019

У меня включен AAD Oauth, используя инструкции из этого URl. это работает как задумано и объяснено здесь. https://docs.microsoft.com/en-us/azure/app-service/configure-authentication-provider-aad, используя Configure with express settings

Однако я хотел бы добавить несколько URL-адресов на мой сайт, которые не требуют аутентификации, или я хотел бы, чтобы только определенные страницы проходили аутентификацию. Эта настройка делает каждую страницу аутентифицированной, а некоторые нет. Как добавить правила, чтобы избежать аутентификации AAD для определенных страниц?

Ответы [ 2 ]

0 голосов
/ 14 ноября 2019

Вы можете установить Action to take when request is not authenticated на allow anonymous. Затем в корневой папке включите файл authorization.json или authorization.yaml

. В этом файле вы можете определить правила для исключения / включения URL-адресов, требующих аутентификации / авторизации.

См. https://azure.github.io/AppService/2016/11/17/URL-Authorization-Rules.html для примеров

0 голосов
/ 12 ноября 2019

Насколько я знаю, если мы используем сервис приложений easy auth, мы не можем гарантировать, какие страницы требуют аутентификации. Поэтому нам нужно реализовать это с помощью нашего собственного кода. Подробные шаги приведены ниже.

  1. Регистрация приложения Azure AD Когда откроется страница «Регистрация приложения», введите регистрационную информацию приложения:

    a. В разделе Name введите значимое имя приложения, которое будет отображаться для пользователей приложения, например ASPNET-Quickstart.

    b. Добавьте <your web app url> в URI перенаправления и нажмите Регистрация.

    c. На левой панели навигации в разделе «Управление» выберите «* 1014». В подразделе «Неявное предоставление» выберите ID-токены. И затем выберите Сохранить.

  2. Обновить проект a. Установить пакет

    Install-Package Microsoft.Owin.Security.OpenIdConnect
    Install-Package Microsoft.Owin.Security.Cookies
    Install-Package Microsoft.Owin.Host.SystemWeb
    

    b. Добавить OWIN Startup 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

Для получения более подробной информации, пожалуйста, обратитесь к документу

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...