You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 8 Web API授权失效及角色授权配置疑问

ASP.NET Core 8 Web API 授权问题排查与解答

问题描述

1. Swagger测试授权接口返回404错误

使用Swagger测试带有[Authorize]属性的接口时,出现以下错误:

404
Undocumented
Error: response status is 404
https://localhost:7071/Identity/Account/Login?ReturnUrl=%2Fapi%2FUserRole%2Fcreate-custom-role Not Found

移除[Authorize]属性后,接口可正常调用。

2. 角色授权疑问

能否直接使用[Authorize(Roles="Admin")]?是否需要额外配置?


提供的代码

Program.cs

using EmployeeManagement.Database;
using EmployeeManagement.Entities;
using EmployeeManagement.Shared.Configrations;
using EmployeeManagement.Shared.Services.Employee;
using EmployeeManagement.Shared.Services.UserRole;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();

builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection") ?? 
    throw new InvalidOperationException( "Connection string Not found")));

builder.Services.AddAuthorization();

builder.Services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>()
    .AddApiEndpoints();

builder.Services.AddAuthentication()
    .AddJwtBearer(IdentityConstants.BearerScheme);

builder.Services.AddAuthorizationBuilder().AddPolicy(
        "api",
        p =>
        {
            p.RequireAuthenticatedUser();
            p.AddAuthenticationSchemes(IdentityConstants.BearerScheme);
        }
    );

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("RequireAdministratorRole",
         policy => policy.RequireRole("Admin"));
});

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });
    options.OperationFilter<SecurityRequirementsOperationFilter>();
});

builder.Services.AddAutoMapper(
    typeof(EmployeeMapperConfig),
    typeof(UserRoleReMapperConfig)
 );
builder.Services.AddScoped<IEmployeeService, EmployeeService>();
builder.Services.AddScoped<IUserRole, UserRoleService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.MapGroup("api/auth").MapIdentityApi<ApplicationUser>();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

UserRoleController.cs

[Authorize]
[Route("api/[controller]")]
[ApiController]
public class UserRoleController : ControllerBase
{
    private readonly IUserRole _userRoleService;

    public UserRoleController(IUserRole userRoleService)
    {
        _userRoleService = userRoleService;
    }

    [HttpPost("create-custom-role")]
    public async Task<ActionResult<UserRoleResponseDto>> CreateCustomRole(createRoleRequestDto requestDto)
    {
        try
        {
            var result = await _userRoleService.CreateCustomRole(requestDto);
            return Ok(result);
        }
        catch (Exception ex)
        {
            return StatusCode(500, ex.Message);
        }
    }
}

问题解答

1. 404错误的解决方法

这个错误的核心原因有两个:

  • 缺少认证中间件:代码中未添加app.UseAuthentication(),导致授权逻辑无法识别JWT Token,直接触发默认重定向行为。
  • 未关闭登录重定向:ASP.NET Core Identity默认会将未认证请求重定向到MVC登录页,但API项目没有该页面,因此返回404。

修复步骤:

  1. 在中间件管道中添加UseAuthentication(),必须放在UseAuthorization()之前:
app.UseHttpsRedirection();

// 新增这行,确保认证在授权之前执行
app.UseAuthentication();

app.UseAuthorization();
  1. 修改JWT Bearer配置,禁止重定向,直接返回401:
builder.Services.AddAuthentication()
    .AddJwtBearer(IdentityConstants.BearerScheme, options =>
    {
        options.Events = new JwtBearerEvents
        {
            OnChallenge = context =>
            {
                // 阻止默认的重定向行为
                context.HandleResponse();
                context.Response.StatusCode = StatusCodes.Status401Unauthorized;
                context.Response.ContentType = "application/json";
                return context.Response.WriteAsJsonAsync(new { Message = "未授权访问,请提供有效的Token" });
            }
        };
    });

2. [Authorize(Roles="Admin")]的使用说明

可以直接使用,但需要满足以下条件:

  • 代码中已经通过.AddRoles<IdentityRole>()启用了角色支持,这部分配置没问题。
  • 确保目标用户已经被分配了Admin角色(可通过Identity API或数据库直接添加)。
  • 使用Identity API生成的JWT Token会自动包含用户的角色声明,Swagger测试时需要在Authorization头中携带Bearer {Token}。

另外,你已经定义了RequireAdministratorRole策略,也可以用[Authorize(Policy = "RequireAdministratorRole")],两种方式功能等价,选择哪种取决于代码规范。


内容的提问来源于stack exchange,提问作者Sarah Aldosari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 04:21:00