We have an Identity Server 4 to authorize users and custom authorization in API project.
I want to set both of these authorizations together, but first check Identity Server 4 and then my custom authorization.
The problem is, this order does not work and my custom authorization executes first. How can I change this order?
Startup.cs
services.AddAuthorization(authorizationOptions =>
{
authorizationOptions.AddPolicy(
name: "UserAccess",
configurePolicy: policyBuilder =>
{
policyBuilder.RequireAuthenticatedUser();
policyBuilder.AddRequirements(new UserAccessRequirement());
});
}).AddAuthentication(defaultScheme: IdentityServerAuthenticationDefaults.AuthenticationScheme).AddIdentityServerAuthentication(options =>
{
options.Authority = "https://*******.land/";
options.ApiName = "****.Api";
options.RequireHttpsMetadata = false;
});
My custom authorization:
public class UserAccessHandler : AuthorizationHandler<UserAccessRequirement>
{
private readonly IHttpContextAccessor _accessor;
public UserAccessHandler(IHttpContextAccessor accessor)
{
_accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
}
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, UserAccessRequirement requirement)
{
var httpContext = _accessor.HttpContext;
/// Some Code
}
}
In API controllers:
[Route("api/[controller]")]
[ApiController]
[Authorize]
public class TestController : ControllerBase
{
[Authorize(policy: "UserAccess")]
[HttpGet("[action]")]
public IActionResult Get()
{
return Ok("Access");
}
}
Updated:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
I wouldn't use the AddIdentityServerAuthentication method for new development as it seems to be deprecated and not supported anymore
see https://github.com/IdentityServer/IdentityServer4.AccessTokenValidation
In your API that receives access tokens from your client you should use:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.Audience = "payment"; //api name
opt.Authority = "https://identityservice.local:6001"; //URL to your identityserver
});
AddIdentityServerAuthentication is not meant to be used in the API.
Updated:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.