Authorization in ASP.NET Core. Always 401 Unauthorized for [Authorize] attribute

前端 未结 7 1157
陌清茗
陌清茗 2021-01-07 18:22

For the first time I\'m creating Authorization in ASP.NET Core. I used tutorial from here TUTORIAL

The problem is when I sending request from postman:



        
7条回答
  •  不知归路
    2021-01-07 19:24

    My ConfigureServices and Configure methods (Asp.Net Core 3.1.0) in the Startup class:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowsAll", builder =>
            {
                builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader();
            });
        });
    
        services.AddAuthentication(options =>
        {
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            ...
        });
    
        services.AddControllers();
    }
    
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
    
        app.UseHttpsRedirection();
        app.UseStaticFiles();
    
        app.UseAuthentication();
        app.UseRouting();
        app.UseAuthorization();
    
        app.UseCors(options => options.AllowAnyOrigin());
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
    

    My controller:

    [Authorize]
    [EnableCors("AllowsAll")]
    [Route("[controller]")]
    public class MyController : MyController
    {
        ...
    }
    

提交回复
热议问题