2017-11-27 14 views
1

로그인 웹 페이지에서 데이터베이스에 계정을 만들 때 사용할 수있는 webform (Identity 2.0)이 있습니다. Azure Active Directory를 사용하여 회사 전자 메일을 인증 할 수 있습니다. (외부 인증)webform 인증을 사용할 때 openidconnect에서 [Authorize (Roles = "xxx")]를 확인하는 방법

[Authorize] 특성을 UserController의 Index() 동작을 꾸미기 위해 넣었습니다. 동일한 컨트롤러의 My List() 액션은 다음과 같이 장식되어 있습니다. [Authorize (Roles = "Admin")]

My webform 로그인으로 로그인하면/MyController/List /로 이동하면 Microsoft 계정 로그인 페이지로 리디렉션됩니다./MyController/Index로 갈 때 나는 방향이 바뀌지 않았다.

이 동작의 원인은 무엇입니까? 사용자가 webform으로 로그인했을 때 Azure를 확인하고 싶지 않습니다. 어떻게 이런 일이 일어나지 않도록 할 수 있습니까?

여기에 여기에 내가 쿠키 Authenticatoin (이메일/비밀번호)로 로그인하고있어 컨트롤러 코드

using System.Web.Mvc; 

namespace MyApp.Controllers 
{ 

    public class AccueilController : Controller 
    { 
     [Authorize] 
     public ActionResult Index() 
     { 
      return View(); 
     } 

     [Authorize(Roles = "Admin")] 
     public ActionResult List() 
     { 
      return View(); 
     } 
    } 
} 

의 내 Startup.Auth.cs

public partial class Startup 
{ 
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"]; 
    private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"]; 
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"]; 
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"]; 
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"]; 

    public static readonly string Authority = aadInstance + tenantId; 

    // This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API. 
    string graphResourceId = "https://graph.windows.net"; 


    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 
    public void ConfigureAuth(IAppBuilder app) 
    { 

     // Configure the db context, user manager and role manager to use a single instance per request 
     app.CreatePerOwinContext(ApplicationDbContext.Create); 
     app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); 
     app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 
     app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); 

     // Enable the application to use a cookie to store information for the signed in user 
     // and to use a cookie to temporarily store information about a user logging in with a third party login provider 
     // Configure the sign in cookie 
     app.UseCookieAuthentication(new CookieAuthenticationOptions 
     { 
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, 
      LoginPath = new PathString("/Account/Login"), 
      Provider = new CookieAuthenticationProvider 
      { 
       // Enables the application to validate the security stamp when the user logs in. 
       // This is a security feature which is used when you change a password or add an external login to your account. 
       OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
        validateInterval: TimeSpan.FromMinutes(30), 
        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) 
      } 
     }); 

     // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. 
     app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); 

     // Enables the application to remember the second login verification factor such as phone or email. 
     // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. 
     // This is similar to the RememberMe option when you log in. 
     app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); 

     // Pour Azure 
     app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions 
     { 
      ClientId = clientId, 
      Authority = Authority, 
      PostLogoutRedirectUri = postLogoutRedirectUri, 
      AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType, 

      Notifications = new OpenIdConnectAuthenticationNotifications() 
      { 
       // If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away. 
       AuthorizationCodeReceived = (context) => 
       { 
        var code = context.Code; 
        ClientCredential credential = new ClientCredential(clientId, appKey); 
        string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value; 
        AuthenticationContext authContext = new AuthenticationContext(Authority, new ADALTokenCache(signedInUserID)); 
        Task<AuthenticationResult> result = authContext.AcquireTokenByAuthorizationCodeAsync(
        code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId); 

        return Task.FromResult(0); 
       } 
      } 
     }); 
     app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); 


     // Uncomment the following lines to enable logging in with third party login providers 
     //app.UseMicrosoftAccountAuthentication(
     // clientId: "", 
     // clientSecret: ""); 

     //app.UseTwitterAuthentication(
     // consumerKey: "", 
     // consumerSecret: ""); 

     //app.UseFacebookAuthentication(
     // appId: "", 
     // appSecret: ""); 

     //app.UseGoogleAuthentication(
     // clientId: "", 
     // clientSecret: ""); 
    } 
} 

편집

입니다.

  1. 나는 색인 작업을했는데, 내 응용 프로그램 내에서 그 페이지의 내용을 참조하십시오.
  2. List() 액션을 누르면 OpenIdConnect 로그인 페이지로 리디렉션됩니다.
+0

'HttpContext.User.IsInRole ("Admin")을 사용하면 AAD로 리디렉션되지 않고 AAD 또는 Webforms로 기록 될 때 false를 반환합니다. '[Authorize (Roles = "MyRole")]'행동은 버그입니까? – Philippe

+0

다른 동작이있는 두 컨트롤러 동작 코드 (빼기 콘텐츠)를 게시 할 수 있습니까? – Cam

+0

@Philippe 사용자 로그인은'admin' 역할을하고 있습니까? –

답변

1

webforms 사용자에게는 관리자 역할이 없지만 AD 사용자에게는 관리자 역할이있는 것으로 보입니다. 신속하게 AspNetUserRoles 테이블을 쿼리하여이를 확인할 수 있습니다.

[Authorize(Roles="Admin")]으로 작업을 꾸미면 역할이있는 사용자 만 액세스 할 수 있습니다. 권한이없는 사용자의 기본 동작 (사용자의 인증 상태와 상관없이)을 로그인 페이지로 리디렉션하는 것입니다.

  1. 서브 클래스 AuthorizeAttribute과 기본 동작을 오버라이드 (override) :

    옵션은 다음.

  2. 사용자가 인증 된 경우 로그인 페이지에서 다른 위치 (올바른 상태 코드가 설정된 금지 된 페이지)로 사용자를 리디렉션하십시오.

알고있는 한, ASP.NET 코어에서와 같이 AuthorizeAttribute을 서브 클래 싱하지 않으면 기본 리디렉션 동작을 재정의 할 수 없습니다.

+0

.NET Core 동작 대 .NET 4의 차이점을 보여주는 링크가 있습니까? 그것은 내가 무슨 일이 일어나는지 이해하는 데 도움이 될 것입니다. 고맙습니다. – Philippe

+1

@Philippe 기본 동작은 .NET Core에서와 동일합니다.그러나 모든 인증 방법이 쿠키 인증을 사용하기 때문에 [응용 프로그램 쿠키 구성] (https://stackoverflow.com/a/42030138/1678053)을 수행 할 수 있습니다. – gldraphael