IdentityServer4基于角色的授权 [英] Role based authorization with IdentityServer4

查看:776
本文介绍了IdentityServer4基于角色的授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用IdentityServer4实施基于角色的授权",以根据用户角色提供对我的API的访问权限.

I am trying to implement "Role Based Authorization" using IdentityServer4 to give access to my API based on the user roles.

例如,我想为用户提供两个角色,即FreeUser和PaidUser,并希望使用[Authorize(Roles ="FreeUser"))]通过Authorize属性提供对API的访问权限,请帮助我我实现了.

For example , I want to have two roles for the user i.e. FreeUser and PaidUser and want to give access to the API through the Authorize Attribute using [Authorize(Roles = "FreeUser"))], Kindly help me that How can I achieve this.

我具有以下解决方案结构:

I have the following solution structure :

  1. IdentityServer
  2. WebApi
  3. JavaScript客户端

我已经按照以下方式注册了我的Javascript客户端:

I have registered my Javascript client as follows:

 new Client
            {
                ClientId = "js",
                ClientName = "javascript client",
                AllowedGrantTypes = GrantTypes.Implicit,
                AllowAccessTokensViaBrowser= true,
                RedirectUris = {"http://localhost:5004/callback.html"},
                PostLogoutRedirectUris = {"http://localhost:5004/index.html"},
                AllowedCorsOrigins = {"http://localhost:5004"},

                AllowedScopes =
                {
                    StandardScopes.OpenId.Name,
                    StandardScopes.Profile.Name,
                    "api1",
                    "role",
                    StandardScopes.AllClaims.Name
                }
            }

范围

 return new List<Scope>
        {
            StandardScopes.OpenId,
            StandardScopes.Profile,

            new Scope
            {
                Name = "api1",
                Description = "My API"
            },
           new Scope
           {
               Enabled = true,
               Name  = "role",
               DisplayName = "Role(s)",
               Description = "roles of user",
               Type = ScopeType.Identity,
               Claims = new List<ScopeClaim>
               {
                   new ScopeClaim("role",false)
               }
           },
           StandardScopes.AllClaims
        };

用户

 return new List<InMemoryUser>
        {
            new InMemoryUser
            {
                Subject = "1",
                Username = "alice",
                Password = "password",

                Claims = new List<Claim>
                {
                    new Claim("name", "Alice"),
                    new Claim("website", "https://alice.com"),
                    new Claim("role","FreeUser")
                }
            },
            new InMemoryUser
            {
                Subject = "2",
                Username = "bob",
                Password = "password",

                Claims = new List<Claim>
                {
                    new Claim("name", "Bob"),
                    new Claim("website", "https://bob.com"),
                    new Claim("role","PaidUser")
                }
            }
        };

WebApi Startup.cs

  public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole(Configuration.GetSection("Logging"));
        loggerFactory.AddDebug();


        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        app.UseCors("default");
        app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
        {
            Authority = "http://localhost:5000",
            ScopeName = "api1",
            //  AdditionalScopes = new List<string> { "openid","profile", "role" },
            RequireHttpsMetadata = false
        });

        app.UseMvc();
    }

Web Api控制器

namespace Api.Controllers
{
 [Route("[controller]")]

public class IdentityController : ControllerBase
{
    [HttpGet]
    [Authorize(Roles = "PaidUser")]
    public IActionResult Get()
    {
        return new JsonResult(from c in User.Claims select new { c.Type,    c.Value });
    }

    [Authorize(Roles = "FreeUser")]
    [HttpGet]
    [Route("getfree")]
    public IActionResult GetFreeUser()
    {
        return new JsonResult(from c in User.Claims select new { c.Type, c.Value });
    }
}
}

JavaScript客户端app.js 在这里,我试图通过IdentityServer登录用户并发出API请求.

Javascript Client app.js Here I am trying to login the user through IdentityServer and make an API Request.

var mgr = new Oidc.UserManager(config);
mgr.getUser().then(function (user) {
if (user) {
    log("User logged in", user.profile);
} else {
    log("User is not logged in.");
}
});

function login() {
  mgr.signinRedirect();
 }

function api() {
mgr.getUser().then(function (user) {
    var url = "http://localhost:5001/identity/getfree";

    var xhr = new XMLHttpRequest();
    xhr.open("GET", url);
    xhr.onload = function () {
        log(xhr.status, JSON.parse(xhr.responseText));
    };

    xhr.setRequestHeader("Authorization", "Bearer " + user.access_token);
    xhr.send();
  });
 }

 function logout() {
   mgr.signoutRedirect();
 }

登录"流程工作正常,我可以成功登录,并且可以在访问令牌中收到角色.

The Login flow works fine and I can login successfully, and I can receive the role in the access token.

当我通过单击按钮(调用Api)向API发出请求时,出现以下错误.

When I make a request to the API by clicking the button (Call Api) then I get the following error..

推荐答案

鉴于您尚未为javascript客户端提供配置对象,我假设您具有如下范围的配置.

Given that you have not provided config object for javascript client, I assume you have scope configured as follows.

scope:"openid profile api1 role"

我相信造成您问题的主要原因是您的访问令牌中未包含角色声明.

I believe that the main reason for your issue is that role claim is not included in your access token.

如下所示将角色声明添加到api1范围中,以将其包括在访问令牌中.

Add role claim to api1 scope as follows to include it in the access token.

             new Scope
                {
                    Name = "api1",
                    DisplayName = "API1 access",
                    Description = "My API",
                    Type = ScopeType.Resource,
                    IncludeAllClaimsForUser = true,
                    Claims = new List<ScopeClaim>
                    {
                        new ScopeClaim(ClaimTypes.Name),
                        new ScopeClaim(ClaimTypes.Role)
                    }
                }

您可以在此处阅读我的答案,以帮助调试问题. 在具有ASP的身份服务器4中实现角色.net身份

You can read my answer here for help debug the issue. implementing roles in identity server 4 with asp.net identity

完整的工作解决方案在这里. https://github.com/weliwita/IdentityServer4.Samples/tree/40844310

The complete working solution is here. https://github.com/weliwita/IdentityServer4.Samples/tree/40844310

这篇关于IdentityServer4基于角色的授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆