Identity Server 3隐式授权,基于角色的授权

时间:2015-10-14 17:05:12

标签: asp.net-web-api2 claims-based-identity identityserver3 role-base-authorization membershipreboot

我已将Identity Server 3与Membership reboot数据库设置为我的授权服务器,并且还开发了一个Web Api项目,该项目将由javascript Web应用程序访问。

使用隐式流,客户端可以登录并获取id_token和access_token。现在我有几个问题,我也很感激一些详细的答案:

  1. id_token的功能是什么?获得后,我能用它做什么?

  2. 用户的角色作为声明存储在数据库中(例如,&#34的关键值;#34;" admin")。此时如何执行基于角色的授权?似乎id_token包含那些声明,但access_token没有。在我的Api请求中将access_token作为Bearer发送时,api如何知道发送用户有哪些角色?

  3. 在网络API控制器中,我想使用以下方式访问用户的信息:

    var user = User as ClaimsPrincipal;

  4. 使用此代码,我无法获得有关用户的任何信息;用户名,ID等。当我在控制器中使用user.Claims时,我无法访问存储在数据库中的声明。如何有两组声明,一个在数据库中,一个在令牌中?!

    非常感谢任何额外的信息。

1 个答案:

答案 0 :(得分:1)

  1. 应在客户端中使用id_token。您可以使用它来访问客户端的声明。 AccessToken将在API中使用。

  2. 对于要包含在access_token中的声明,您需要创建具有相关声明的作用域并在请求中请求该作用域。 要创建范围(在self-host sample范围内添加Scopes.cs):

    new Scope 
    {
                Name = "myApiScope",
                DisplayName = "IdentityManager",
                Type = ScopeType.Resource,
                Emphasize = true,
                ShowInDiscoveryDocument = false,
    
                Claims = new List<ScopeClaim>
                {
                    new ScopeClaim(Constants.ClaimTypes.Name),
                    new ScopeClaim(Constants.ClaimTypes.Role)
                }
    }
    
  3. 在您的授权请求中询问范围(在Javascript implicit client - simple中按以下方式完成)

    function getToken() {
            var authorizationUrl = 'https://localhost:44333/core/connect/authorize';
            var client_id = 'implicitclient';
            var redirect_uri = 'http://localhost:37045/index.html';
            var response_type = "token";
            var scope = "myApiScope";
            var state = Date.now() + "" + Math.random();
    
            localStorage["state"] = state;
    
            var url =
                authorizationUrl + "?" +
                "client_id=" + encodeURI(client_id) + "&" +
                "redirect_uri=" + encodeURI(redirect_uri) + "&" +
                "response_type=" + encodeURI(response_type) + "&" +
                "scope=" + encodeURI(scope) + "&" +
                "state=" + encodeURI(state);
            window.location = url;
        }
    

    这将包括访问令牌中的名称和角色声明

    1. 在Web API启动时使用相关中间件配置您的API(在SampleAspNetWebApi示例中,按以下方式完成)

      app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions             {                 权限=“https://localhost:44333/core”,                 RequiredScopes = new [] {“myApiScope”}             });

    2. 然后您可以按如下方式访问声明

                  var principal = User as ClaimsPrincipal;
                  return from c in principal.Identities.First().Claims
                         select new 
                         {
                             c.Type,
                             c.Value
                         };
      
相关问题