Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to authorize IdentityServer4 specified roles

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article shows you how to carry out IdentityServer4 designated role authorization, the content is concise and easy to understand, it will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

1. Business scenario

The AllowedScopes in the IdentityServer4 authorization configuration Client sets the specific API site name, that is, the ApiName set by the user. Sample code:

/ / Authorization Center configuration

New Client

{

ClientId = "client_id_1"

AllowedGrantTypes = GrantTypes.ResourceOwnerPassword

AllowOfflineAccess = true

AccessTokenLifetime = 3600 * 6, / / 6 hours

SlidingRefreshTokenLifetime = 1296000, / / 15 days

ClientSecrets =

{

New Secret ("secret" .Sha256 ())

}

AllowedScopes =

{

"api_name1"

}

}

/ / API service configuration

App.UseIdentityServerAuthentication (new IdentityServerAuthenticationOptions

{

Authority = $"http://localhost:5000",

ApiName = "api_name1"

RequireHttpsMetadata = false

});

The above two api_name1 configurations should be consistent, and the problem arises, because the scope configuration of the authorization center is the entire API service. If we have multiple Client configurations, such as a foreground and background, and then all need to access the api_name1, there will be some problems.

For example, an interface service configuration code in an api_name1 service:

[Authorize ()] [Route ("api/values")] [HttpGet] public IActionResult Get () {

Return Ok ();}

The configuration of Authorize () indicates that the api/values interface needs to be accessed after authorization. If the authorization center is configured with two Client (foreground and background), and the scope contains api_name1, two situations will occur:

Both foreground Client and backend Client need to access the api/values interface after authorization: no problem.

Access after authorization is not required for the foreground Client, but for the backend Client: if there is a problem, the foreground Client cannot access it because the api/values API is set to Authorize ().

In fact, to be clear, how to get the API service to specify Client authorized access? For example: [Authorize (ClientId = 'client_id_1')].

two。 Solution

There is no such solution as [Authorize (ClientId = 'client_id_1')], but you can use [Authorize (Roles =' admin')].

The ResourceOwnerPasswordValidator code of the authorization center is modified as follows:

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 () {new Claim ("role", "admin")}; / / set different role based on the user object

Context.Result = new GrantValidationResult (user.UserId.ToString (), OidcConstants.AuthenticationMethods.Password, claims)

}

}

}

The startup configuration of the authorization center is modified as follows

Var builder = services.AddIdentityServer ()

Builder.AddTemporarySigningCredential ()

/ / .AddInMemoryIdentityResources (Config.GetIdentityResources ())

.AddInMemoryApiResources (new List

{

New ApiResource ("api_name1", "api1") {UserClaims = new List {"role"}}, / / add role claim

New ApiResource ("api_name2", "api2") {UserClaims = new List {"role"}}

})

.AddInMemoryClients (Config.GetClients ())

The API service interface only needs to be configured as follows:

[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 ()

}

It is important to note that although the api/values interface does not have a specific Roles set, each Role can be accessed.

The above content is how to authorize IdentityServer4 designated roles. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report