2

我正在使用IdentityServer3發出令牌並試圖使用Thinktecture.IdentityModel.Owin.ResourceAuthorization.WebApi來授權對web api的資源訪問。ResourceAuthorize(「Read」,「UsersList」)不起作用,ResourceAuthorizationManager

我使用以下代碼來授權的控制器的動作。

[ResourceAuthorize("Read","UsersList")] 

ResourceAuthorizationManager如下所示。

public class MyAuthorizationManager : ResourceAuthorizationManager 
{ 
    /// <summary> 
    /// Verify Access Rights 
    /// </summary> 
    /// <param name="context"></param> 
    /// <returns></returns> 
    public override Task<bool> CheckAccessAsync(ResourceAuthorizationContext context) 
    { 
     switch (context.Resource.First().Value) 
     { 
      case "UsersList": 
       return AuthorizeUsersList(context); 
      default: 
       return Nok(); 
     } 
    } 

    private Task<bool> AuthorizeUsersList(ResourceAuthorizationContext context) 
    { 
     switch (context.Action.First().Value) 
     { 
      case "Read": 
       return Eval(context.Principal.HasClaim("role", "User")); 
      case "Write": 
       return Eval(context.Principal.HasClaim("role", "Owner")); 
      default: 
       return Nok(); 
     } 
    } 
} 

然而,當控制來AuhtorizeUsersList,該context.Principal沒有作用索賠。我在註冊用戶時不存儲用戶聲明。如何在旅途中爲經過身份驗證的用戶添加聲明?

+0

我的代碼看起來像你的,但即使我已經把'ResourceAuthorize'屬性永遠不會被執行的CheckAccessAsync方法通過控制器操作,並且我還配置了'app.UseResourceAuthorization(MyAuthorizationManager)'授權。你知道我還需要做其他事情嗎? –

+0

我想,這應該是'app.UseResourceAuthorization(新MyAuthorizationManager())' – dudedev

+0

在旅途中增加的權利要求,覆蓋類AbstractIdentityUserService(Axoom.Core.IdentityServer.Services)的GetClaimsForUserAsync方法,並添加索賠那裏。 – dudedev

回答

1

也許這將是對他人有幫助的。

基本上,我缺少內部範圍-權利要求映射「角色」如權利要求而限定所述API爲範圍。您只需列出您希望作爲範圍一部分的所有聲明,IdentityServer將處理其餘部分。

在身份服務器端:

new Scope 
{ 
    Enabled = true, 
    Name = "ScopeName", 
    Type = ScopeType.Identity, 
Claims = new List<ScopeClaim> 
    { 
     new ScopeClaim("role") 
    } 
}