IdentityServer4 授權配置AllowedScopes執行個體

來源:互聯網
上載者:User

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,現在就會出現兩種情況:

  1. 前台Client和後台Client,都需要授權後訪問api/values介面:沒有問題。

  2. 前台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 對象,設定不同的 rolecontext.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 claimnew 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都可以訪問。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.