Accessing protected API on IdentityServer4 with Bearer Token
There is an example co-hosting a protected API inside IdentityServer: IdentityServerAndApi
I quick comparison between their startup and yours is that they are calling AddJwtBearer
instead of AddIdentityServerAuthentication
:
services.AddAuthentication()
.AddJwtBearer(jwt => {
jwt.Authority = "http://localhost:5000";
jwt.RequireHttpsMetadata = false;
jwt.Audience = "api1";
});
TheAuthorize
attribute also sets the authentication scheme:
[Authorize(AuthenticationSchemes = "Bearer")]
If you want to set a default authentication scheme to be one level above the policies (it is most relevant when you have multiple policies or no policies at all):
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(o =>
{
o.Authority = "http://localhost:5000";
o.RequireHttpsMetadata = false;
o.Audience = "api1";
});
Then you can simple use the [Authorize]
tag attribute above the controller's method without polluting each authorization attribute with the sceme:
[Authorize]
public IActionResult GetFoo()
{
}