0

我成功地在身份服務器上對用戶進行身份驗證,並獲取聲明(以及聲明中的角色)。一切都很好,當我不考慮角色。我想限制用戶,除非他具有特定角色並將他重定向到特定創建的「未授權」或「拒絕訪問」頁面。以下代碼不會引發未經授權的異常。OWIN Katana中間件:如果返回的聲明沒有特定的角色,如何阻止用戶?

var canAccessPortal = id.HasClaim(c => c.Type == "role" && c.Value == "XP"); 
if (!canAccessPortal) 
{ 
    throw new UnauthorizedAccessException(); 
} 

完全app.UseOpenIdConnectAuthentication代碼如下:在web.config文件

app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions 
{ 
    ClientId = ClientId, 
    Authority = IdServBaseUri, 
    RedirectUri = ClientUri, 
    PostLogoutRedirectUri = ClientUri, 
    ResponseType = "code id_token token", 
    Scope = "openid profile roles clef", 
    TokenValidationParameters = new TokenValidationParameters 
    { 
     NameClaimType = "name", 
     RoleClaimType = "role" 
    }, 
    SignInAsAuthenticationType = "Cookies", 

    Notifications = new OpenIdConnectAuthenticationNotifications 
    { 
     AuthorizationCodeReceived = async n => 
     { 
      // use the code to get the access and refresh token 
      var tokenClient = new TokenClient(
       TokenEndpoint, 
       ClientId, 
       ClientSecret); 

      var tokenResponse = await tokenClient.RequestAuthorizationCodeAsync(n.Code, n.RedirectUri); 

      if (tokenResponse.IsError) 
      { 
       throw new Exception(tokenResponse.Error); 
      } 

      // use the access token to retrieve claims from userinfo 
      var userInfoClient = new UserInfoClient(UserInfoEndpoint); 

      var userInfoResponse = await userInfoClient.GetAsync(tokenResponse.AccessToken); 

      // create new identity 
      var id = new ClaimsIdentity(n.AuthenticationTicket.Identity.AuthenticationType); 
      id.AddClaims(userInfoResponse.Claims); 
      id.AddClaim(new Claim("access_token", tokenResponse.AccessToken)); 
      id.AddClaim(new Claim("expires_at", DateTime.Now.AddSeconds(tokenResponse.ExpiresIn).ToLocalTime().ToString())); 
      id.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken)); 
      id.AddClaim(new Claim("sid", n.AuthenticationTicket.Identity.FindFirst("sid").Value)); 

      var canAccessPortal = id.HasClaim(c => c.Type == "role" && c.Value == "XP"); 
      if (!canAccessPortal) 
      { 
       throw new UnauthorizedAccessException(); 
      } 

      n.AuthenticationTicket = new AuthenticationTicket(
       new ClaimsIdentity(id.Claims, n.AuthenticationTicket.Identity.AuthenticationType, "name", "role"), 
       n.AuthenticationTicket.Properties); 
     }, 

     RedirectToIdentityProvider = n => 
     { 
      // if signing out, add the id_token_hint 
      if (n.ProtocolMessage.RequestType == OpenIdConnectRequestType.LogoutRequest) 
      { 
       var idTokenHint = n.OwinContext.Authentication.User.FindFirst("id_token"); 

       if (idTokenHint != null) 
       { 
        n.ProtocolMessage.IdTokenHint = idTokenHint.Value; 
       } 
      } 

      return Task.FromResult(0); 
     } 
    } 
}); 

自定義錯誤節點:

<customErrors mode="On" defaultRedirect="~/account/error"> 
    <error statusCode="401" redirect="~/account/unauthorized" /> 
</customErrors> 

回答

0

實現授權在MVC管道是最好的地方實施AuthorizationAttribute。在這裏你可以完全控制請求上下文。確保您是否正在授權MVC,您應該實現System.Web.MVC .AuthorizeAttribute並實現覆蓋AuthorizeCore。

protected override bool AuthorizeCore(HttpContextBase httpContext) { 

     if (!base.AuthorizeCore(httpContext)) { 
      return false; 
     } 
     //Check roles from DB service 
     return roleservice.UserInRole && UserClaims.Count > 0; 
    } 

    /// <summary> 
    /// Processes HTTP requests that fail authorization. 
    /// </summary> 
    /// <param name="filterContext">Encapsulates the information for using <see cref="T:System.Web.Mvc.AuthorizeAttribute" />. The <paramref name="filterContext" /> object contains the controller, HTTP context, request context, action result, and route data.</param> 
    protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { 
     filterContext.Result = new RedirectResult("~/main/unauthorized"); 
    } 
相關問題