gpt4 book ai didi

asp.net-mvc - IdentityServer4基于角色的授权

转载 作者:行者123 更新时间:2023-12-03 11:42:22 25 4
gpt4 key购买 nike

我正在尝试使用IdentityServer4实现“基于角色的授权”,以便基于用户角色来访问我的API。

例如,我想为用户扮演两个角色,即FreeUser和PaidUser,并希望使用[Authorize(Roles =“FreeUser”)))通过Authorize属性提供对API的访问权限,请帮助我如何实现此目标。

我有以下解决方案结构:

  • IdentityServer的
  • WebApi
  • Javascript客户端

  • 我已经注册了我的Javascript客户端,如下所示:
     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 Controller
    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请求。
    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();
    }

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

    enter image description here

    当我通过单击按钮(调用Api)向API发出请求时,会出现以下错误。
    enter image description here

    最佳答案

    鉴于您尚未为javascript客户端提供配置对象,我假设您已按以下方式配置了作用域。

    scope:"openid profile api1 role"

    我认为造成您问题的主要原因是您的访问 token 中未包含角色声明。

    如下将角色声明添加到api1范围,以将其包括在访问 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)
    }
    }

    您可以在此处阅读我的答案,以帮助调试问题。
    implementing roles in identity server 4 with asp.net identity

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

    关于asp.net-mvc - IdentityServer4基于角色的授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40844310/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com