Home  >  Article  >  Backend Development  >  IdentityServer4 authorization configuration AllowedScopes instance

IdentityServer4 authorization configuration AllowedScopes instance

零下一度
零下一度Original
2017-06-24 10:48:343415browse

1. Business scenario

AllowedScopes in the IdentityServer4 authorization configurationClient sets the specific API site name, which is the ## set by the user. #ApiName, sample code:

//授权中心配置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});
The above two

api_name1 configurations must be consistent. The problem arises because the scope## of the authorization center #The configuration is the entire API service. If we have multiple Client configurations, such as a frontend and a backend, and then both need to access api_name1, some problems will occur. For example, an interface service configuration code in the

api_name1

service:

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

Authorize()

configuration, description api/valuesThe interface needs to be accessed after authorization. If the authorization center is configured with two Client (frontend and backend), and scope both contain api_name1 , now there will be two situations:

    front desk
  1. Client

    and backend Client, both require authorization to access api/valuesInterface: No problem.

  2. Front desk
  3. Client

    does not require authorization for access, backgroundClient requires authorization for access: There is a problem, front deskClient There is no way to access it because the api/values interface is set with Authorize().

  4. Actually, to explain more clearly, how to let the API service specify
Client

to authorize access? For example: [Authorize(ClientId = 'client_id_1')]. 2. Solution

There is no

[Authorize(ClientId = 'client_id_1')]

this solution, 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<Claim>() { new Claim("role", "admin") }; //根据 user 对象,设置不同的 rolecontext.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<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 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 should be noted that although the
api/values

interface does not Set specific Roles, but each Role is accessible.

The above is the detailed content of IdentityServer4 authorization configuration AllowedScopes instance. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn