You need to enable JavaScript to run this app. ASP.NET Core 5中配置Bearer令牌实现Web API授权的简单方案咨询
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core 5中配置Bearer令牌实现Web API授权的简单方案咨询

ASP.NET Core 5 MVC 配置Bearer令牌最简方案

ASP.NET Core 5 不再内置传统的OAuth授权服务器中间件,最简对齐原有功能的方案是用JWT Bearer认证,步骤如下:

1. 安装依赖NuGet包

安装官方JWT认证组件:

Install-Package Microsoft.AspNetCore.Authentication.JwtBearer

2. 配置JWT参数

在appsettings.json中添加配置项:

"JwtSettings": {
  "SecretKey": "你自己设置的至少16位长度的加密密钥",
  "Issuer": "你的应用名称,比如MyApp",
  "Audience": "你的客户端名称,比如MyAppClient",
  "ExpireDays": 14
}

3. 注册认证授权服务

修改Startup.cs的ConfigureServices方法:

public void ConfigureServices(IServiceCollection services)
{
    // 读取JWT配置
    var jwtSettings = Configuration.GetSection("JwtSettings");
    var secretKey = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);

    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(options =>
        {
            options.RequireHttpsMetadata = false; // 对应原有AllowInsecureHttp=true,生产环境请设为true
            options.SaveToken = true;
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(secretKey),
                ValidateIssuer = true,
                ValidIssuer = jwtSettings["Issuer"],
                ValidateAudience = true,
                ValidAudience = jwtSettings["Audience"],
                ValidateLifetime = true,
                ClockSkew = TimeSpan.Zero
            };
        });

    services.AddControllersWithViews();
    // 你的其他服务注册...
}

4. 启用认证中间件

修改Startup.cs的Configure方法,注意中间件顺序不能错:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    // 你的其他中间件,比如异常处理、静态文件等...

    app.UseRouting();

    app.UseAuthentication(); // 注意要放在UseAuthorization之前
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
}

5. 实现令牌发放接口

对应原有/Token端点,新建API控制器实现登录发令牌逻辑:

[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
    private readonly IConfiguration _configuration;
    // 注入你的用户管理服务,替换成你自己的UserManager
    private readonly UserManager<ApplicationUser> _userManager;

    public AccountController(IConfiguration configuration, UserManager<ApplicationUser> userManager)
    {
        _configuration = configuration;
        _userManager = userManager;
    }

    [HttpPost("Token")]
    public async Task<IActionResult> GenerateToken([FromForm] string username, [FromForm] string password)
    {
        // 验证用户名密码,替换成你自己的验证逻辑
        var user = await _userManager.FindByNameAsync(username);
        if (user == null || !await _userManager.CheckPasswordAsync(user, password))
        {
            return Unauthorized("用户名或密码错误");
        }

        var jwtSettings = _configuration.GetSection("JwtSettings");
        var secretKey = Encoding.ASCII.GetBytes(jwtSettings["SecretKey"]);
        
        // 生成令牌凭据
        var tokenDescriptor = new SecurityTokenDescriptor
        {
            Subject = new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Name, user.UserName),
                new Claim(ClaimTypes.NameIdentifier, user.Id)
                // 可添加你需要的其他自定义声明
            }),
            Expires = DateTime.UtcNow.AddDays(double.Parse(jwtSettings["ExpireDays"])),
            Issuer = jwtSettings["Issuer"],
            Audience = jwtSettings["Audience"],
            SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(secretKey), SecurityAlgorithms.HmacSha256Signature)
        };

        var tokenHandler = new JwtSecurityTokenHandler();
        var securityToken = tokenHandler.CreateToken(tokenDescriptor);
        var token = tokenHandler.WriteToken(securityToken);

        return Ok(new { access_token = token, expires_in = 14 * 24 * 3600, token_type = "Bearer" });
    }
}

使用方式

  • 需要授权的接口添加[Authorize]特性即可
  • 请求接口时在请求头添加Authorization: Bearer <你获取到的令牌>即可正常访问

如果需要兼容原有外部登录逻辑,只需要在上述令牌生成逻辑中补充外部登录的用户验证逻辑即可,无需额外复杂配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 13:45:03