日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

IdentityServer4 指定角色授权(Authorize(Roles=amp;quot;adminamp;quot;))

發布時間:2023/12/4 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IdentityServer4 指定角色授权(Authorize(Roles=amp;quot;adminamp;quot;)) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 業務場景

IdentityServer4 授權配置Client中的AllowedScopes,設置的是具體的 API 站點名字,也就是使用方設置的ApiName,示例代碼:


//授權中心配置
new Client
{
? ?ClientId = "client_id_1",
? ?AllowedGrantTypes = GrantTypes.ResourceOwnerPassword,
? ?AllowOfflineAccess = true,
? ?AccessTokenLifetime = 3600 * 6, //6小時
? ?SlidingRefreshTokenLifetime = 1296000, //15天
? ?ClientSecrets =
? ?{
? ? ? ?new Secret("secret".Sha256())
? ?},
? ?AllowedScopes =
? ?{
? ? ? ?"api_name1"
? ?},
}

//API 服務配置
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
? ?Authority = $"http://localhost:5000",
? ?ApiName = "api_name1",
? ?RequireHttpsMetadata = false
});


上面兩個api_name1配置要一致,問題來了,因為授權中心的scope配置是整個 API 服務,如果我們存在多個Client配置,比如一個前臺和后臺,然后都需要訪問api_name1,就會出現一些問題。

比如,api_name1服務中的一個接口服務配置代碼:

[Authorize()] [Route("api/values")] [HttpGet]public IActionResult Get(){ ?
?return Ok(); }

Authorize()的配置,說明api/values接口需要授權后訪問,如果授權中心配置了兩個Client(前臺和后臺),并且scope都包含了api_name1,現在就會出現兩種情況:

  • 前臺Client和后臺Client,都需要授權后訪問api/values接口:沒有問題。

  • 前臺Client不需要授權后訪問,后臺Client需要授權后訪問:有問題,前臺Client沒辦法訪問了,因為api/values接口設置了Authorize()。

  • 其實,說明白些,就是該如何讓 API 服務指定Client授權訪問?比如:[Authorize(ClientId = 'client_id_1')]。

    2. 解決方案

    沒有[Authorize(ClientId = 'client_id_1')]這種解決方式,不過可以使用[Authorize(Roles = 'admin')]。

    授權中心的ResourceOwnerPasswordValidator代碼,修改如下:


    public class ResourceOwnerPasswordValidator : IResourceOwnerPasswordValidator
    {
    ? ?private readonly IUserService _userService;

    ? ?public ResourceOwnerPasswordValidator(IUserService userService)
    ? ?
    {
    ? ? ? ?_userService = userService;
    ? ?}

    ? ?public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
    ? ?
    {
    ? ? ? ?var user = await _userService.Login(context.UserName, context.Password);
    ? ? ? ?if (user != null)
    ? ? ? ?{
    ? ? ? ? ? ?var claims = new List<Claim>() { new Claim("role", "admin") }; //根據 user 對象,設置不同的 role
    ? ? ? ? ? ?context.Result = new GrantValidationResult(user.UserId.ToString(), OidcConstants.AuthenticationMethods.Password, claims);
    ? ? ? ?}
    ? ?}
    }


    授權中心的startup配置,修改如下


    var builder = services.AddIdentityServer();
    builder.AddTemporarySigningCredential()
    ? ? ? ?//.AddInMemoryIdentityResources(Config.GetIdentityResources())
    ? ? ? ?.AddInMemoryApiResources(new List<ApiResource>
    ? ? ? ?{
    ? ? ? ? ? ?new ApiResource("api_name1", "api1"){ UserClaims = new List<string> {"role"}}, //增加 role claim
    ? ? ? ? ? ?new ApiResource("api_name2", "api2"){ UserClaims = new List<string> {"role"}}
    ? ? ? ?})
    ? ? ? ?.AddInMemoryClients(Config.GetClients());


    API 服務接口,只需要配置如下:


    [Authorize()]
    [Route("api/values")]
    [HttpGet]
    public IActionResult Get()
    {
    ? ?return Ok();
    }

    [Authorize(Roles = "admin")]
    [Route("api/values2")]
    [HttpGet]
    public IActionResult Get2()
    {
    ? ?return Ok();
    }

    [Authorize(Roles = "admin,normal")]
    [Route("api/values3")]
    [HttpGet]
    public IActionResult Get3()
    {
    ? ?return Ok();
    }


    需要注意的是,api/values接口雖然沒有設置具體的Roles,但每個Role都可以訪問。

    相關文章:

    • IdentityServer4(OAuth2.0服務)折騰筆記

    • IdentityServer4 實現 OpenID Connect 和 OAuth 2.0

    • IdentityServer4 使用OpenID Connect添加用戶身份驗證

    • IdentityServer4 ASP.NET Core的OpenID Connect OAuth 2.0框架學習保護API

    原文地址:http://www.cnblogs.com/xishuai/p/identityserver4-apiresource-userclaim-role-authorize.html


    .NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注

    總結

    以上是生活随笔為你收集整理的IdentityServer4 指定角色授权(Authorize(Roles=amp;quot;adminamp;quot;))的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。