Microsoft.AspNetCore.Authorization为Http PUT引发401未经授权的错误.它适用于



我正在使用带有ASP.Net Core API(netcoreapp3.1(的IdentityServer4客户端位于Angular。

在API中调用Http Put方法时,Microsoft.AspNetCore.Authorization引发401未授权错误。

这适用于HTTP Get。

错误

代码如下:身份代码:

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

}    

角度代码:

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核心API代码:

控制器:


[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 }));
}
}

启动.cs

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");
});
}


得到了答案:

PUT的角度代码不同——它在发送授权标头时遗漏了。


const headers = { 'Authorization': token,  'Content-Type':  'application/json' };
const body = { };
this.http.put<any>(this.configService.resourceApiURI + '/Groups', body, { headers })
.subscribe(data => alert());

最新更新