ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,187 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I am using IdentityServer4 with ASP .Net Core API (netcoreapp3.1) The client is in Angular.
The Microsoft.AspNetCore.Authorization throws a 401 un authorized error when calling Http Put Method in the API.
This works for HTTP Get.
Error
The code is as follows: Identity Code :
new ApiResource("resourceapi", "Resource API")
{
Scopes = {
new Scope
{
Name = "api1",
DisplayName = "API1 access",
Description = "My API",
UserClaims= new List<string>()
{
"Name",
"Role"
}
}
}
}
new Client {
RequireConsent = false,
ClientId = "angular_spa",
ClientName = "Angular SPA",
AllowedGrantTypes = GrantTypes.Implicit,
AllowedScopes = { "openid", "profile", "email", "api1" },
RedirectUris = {"https://localhost:4200/auth-callback"},
PostLogoutRedirectUris = {"https://localhost:4200/"},
AllowedCorsOrigins = {"https://localhost:4200"},
AllowAccessTokensViaBrowser = true,
AccessTokenLifetime = 3600
}
Angular Code :
`
authority: 'https://localhost:5000',
client_id: 'angular_spa',
redirect_uri: 'https://localhost:4200/auth-callback',
post_logout_redirect_uri: 'https://localhost:4200/',
response_type:"id_token token",
scope:"openid profile email api1",
filterProtocolClaims: true,
loadUserInfo: true,
automaticSilentRenew: true,
silent_redirect_uri: 'http://localhost:4200/silent-refresh.html'
`
.NET Core API Code :
Controller:
[Route("api/[controller]")]
[Authorize]
[ApiController]
public class GroupsController : ControllerBase
{
[HttpPut]
public ActionResult<IEnumerable<string>> put()
{
return new JsonResult(User.Claims.Select(c => new { c.Type, c.Value }));
}
}
`
`
public void ConfigureServices(IServiceCollection services)
{
// accepts any access token issued by identity server
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "https://localhost:5000";
options.TokenValidationParameters = new
TokenValidationParameters
{
ValidateAudience = false
};
});
// adds an authorization policy to make sure the token is for scope 'api1'
services.AddAuthorization(options =>
{
options.AddPolicy("ApiScope", policy =>
{
policy.RequireAuthenticatedUser();
policy.RequireClaim("scope", "api1");
});
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseCors(options => options.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin());
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers()
.RequireAuthorization("ApiScope");
});
}
`
@klabs Shortcut for testing, comment out your [Authorize] attribute.