Microsoft.AspNetCore.Authorization 为 Http PUT 抛出 401 未经授权的错误。它适用于 Http Get

Microsoft.AspNetCore.Authorization throws 401 unauthorized error for Http PUT . It works for Http Get

我将 IdentityServer4 与 ASP .Net Core API (netcoreapp3.1) 一起使用 客户在 Angular.

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

这适用于 HTTP Get。

Error

代码如下: 身份证号码:

  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代码:

   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 代码:

控制器:

  

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

        }

    }

Startup.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 的 angular 代码不同,它在发送授权时错过了 header。


const headers = { 'Authorization': token,  'Content-Type':  'application/json' };

const body = { };

this.http.put<any>(this.configService.resourceApiURI + '/Groups', body, { headers })
    .subscribe(data => alert());