.net6 webapi 添加认证token

Authentication(认证) 和 Authorization(授权)傻傻分不清楚

1.注册中配置认证,添加JWThelper 认证 .添加授权验证

2.swagger 添加token 配置

1.添加JWT 认证 

(注意你的包的版本信息 需要选择6.*)
前提需要安装unget 包Microsoft.AspNetCore.Authentication.JwtBearer
在你的appsetting.json 添加如下配置(注意你的Secretkey,需要一定的长度才能获取到256位)

"Jwt": {
    "SecretKey": "****************************",
    "Issuer": "WebAppIssuer",
    "Audience": "WebAppAudience"
}

然后在你的注册器里添加如下代码

var configuration = builder.Configuration;
builder.Services.AddAuthentication(option =>
{
    option.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters()
    {
        ValidateIssuer = true,
        ValidIssuer= configuration["Jwt:Issuer"],
        ValidateAudience        = true,
        ValidAudience = configuration["Jwt:Audience"], //订阅人Audience
        ValidateIssuerSigningKey = true, //是否验证SecurityKey
        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration["Jwt:SecretKey"])), //SecurityKey
        ValidateLifetime = true, //是否验证失效时间
        ClockSkew = TimeSpan.FromSeconds(30), //过期时间容错值,解决服务器端时间不同步问题(秒)
        RequireExpirationTime = true,
    };
});

builder.Services.AddSingleton(new JwtHelper(configuration));

这里就需要的 jwthelper 去处理的认证  根据自己的需求 定义角色 用户信息。如下简单,过期时间为一个小时。token 里添加头 注意是Bearer

using Microsoft.IdentityModel.Tokens;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;

namespace **************
{
    public class JwtHelper
    {
        private readonly IConfiguration _configuration;

        public JwtHelper(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public string CreateToken()
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
            new Claim(ClaimTypes.Name, "u_admin"), //HttpContext.User.Identity.Name
            new Claim(ClaimTypes.Role, "r_admin"), //HttpContext.User.IsInRole("r_admin")
            new Claim(JwtRegisteredClaimNames.Jti, "admin"),
            new Claim("Username", "Admin"),
            new Claim("Name", "超级管理员")
        };

            // 2. 从 appsettings.json 中读取SecretKey
            var secretKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Jwt:SecretKey"]));

            // 3. 选择加密算法
            var algorithm = SecurityAlgorithms.HmacSha256;

            // 4. 生成Credentials
            var signingCredentials = new SigningCredentials(secretKey, algorithm);

            // 5. 根据以上,生成token
            var jwtSecurityToken = new JwtSecurityToken(
                _configuration["Jwt:Issuer"],     //Issuer
                _configuration["Jwt:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddHours(1),    //expires
                signingCredentials               //Credentials
            );

            // 6. 将token变为string
            var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
            token = "Bearer " + token;
            return token;
        }
    }
}

接着 根据自身要求 生成一个认证token,验证token及授权[Authorize] 过滤器

[HttpGet]
public ActionResult<string> GetToken()
{
    return _jwtHelper.CreateToken();
}

[Authorize]
[HttpGet]
public ActionResult<string> GetTest()
{
    return "Test Authorize";
}

可以通过 postman 验证 为了方便操作 在swagger添加 授权就可以在浏览器里调试测试

2.swagger 添加token 配置

VS 2022 自带的注册器不带 如下配置
builder.Services.AddSwaggerGen(); 替换如下代码
配置Swagger,添加一个安全定义并应用到每个路由。

builder.Services.AddSwaggerGen(options =>
    {
        // 添加安全定义
        options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
        {
            Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
            Name = "Authorization",
            In = ParameterLocation.Header,
            Type = SecuritySchemeType.ApiKey,
            Scheme = "Bearer" // 注意 "Bearer" 必须使用大写 "B"
        });
 
        // 添加全局的安全要求
        options.AddSecurityRequirement(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = "Bearer"
                    }
                },
                new string[] {}
            }
        });
    });

 app.UseSwagger();
 app.UseSwaggerUI(); 这个代码里是不带配置授权,这样页面里就没有地方让你输入token。
我们需要在使用swaggerUI时添加一些配置 如下

app.UseSwaggerUI(
options =>{
// 指定Swagger JSON端点
options.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
// 如果你想要在Swagger UI上隐藏这个选项,可以不添加下面这行代码
options.OAuthClientId(value: "swagger"); //default clientId
options.OAuthAppName("My API");
});

这样你的调试页面里将有输入token的地方。

参考如下文档

https://www.cnblogs.com/clis/p/16151872.html

  • 9
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
### 回答1: 在 .NET Core Web API 中进行 Token 验证通常涉及以下步骤: 1. 安装 Microsoft.AspNetCore.Authentication.JwtBearer 包。 2. 在 Startup.cs 文件的 ConfigureServices() 方法中添加身份验证服务,包括 JWTBearerOptions 配置。 3. 在 Startup.cs 文件的 Configure() 方法中启用身份验证中间件。 以下是一个基本的示例: ```csharp using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens; using System.Text; public void ConfigureServices(IServiceCollection services) { // 配置身份验证服务 services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, ValidateAudience = true, ValidateLifetime = true, ValidateIssuerSigningKey = true, ValidIssuer = Configuration["Jwt:Issuer"], ValidAudience = Configuration["Jwt:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:SecretKey"])) }; }); // 其他服务注册... } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { // 启用身份验证中间件 app.UseAuthentication(); // 其他中间件注册... } ``` 上述代码中,我们使用了 `AddAuthentication()` 方法来配置身份验证服务,并指定了 JWTBearerDefaults.AuthenticationScheme 作为默认身份验证方案。 接着,我们使用 `AddJwtBearer()` 方法来配置 JWTBearerOptions,其中 `TokenValidationParameters` 属性用于指定 Token 验证参数,例如验证发行者、受众、过期时间、签名密钥等。 最后,在 Configure() 方法中,我们调用 `UseAuthentication()` 方法来启用身份验证中间件,以确保每个请求都进行身份验证。 ### 回答2: 在.NET Core Web API中配置Token验证,可以按照以下步骤进行操作: 1. 添加NuGet包:在项目中添加Microsoft.AspNetCore.Authentication和Microsoft.AspNetCore.Authentication.JwtBearer两个NuGet包。 2. 配置认证服务:在Startup.cs文件的ConfigureServices方法中添加以下代码,以启用Bearer令牌验证: ``` services.AddAuthentication(options => { options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(options => { options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, // 验证发行人 ValidateAudience = true, // 验证受众 ValidateLifetime = true, // 验证生命周期 ValidateIssuerSigningKey = true, // 验证颁发的签名密钥 ValidIssuer = "your_issuer", // 设置发行人 ValidAudience = "your_audience", // 设置受众 IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) // 设置签名密钥 }; }); ``` 3. 配置授权:在Startup.cs文件的Configure方法中添加以下代码,以启用授权中间件: ``` app.UseAuthentication(); app.UseAuthorization(); ``` 4. 添加[Authorize]特性:在需要验证Token的Controller或Action上添加[Authorize]特性。 现在,当客户端请求受保护的Controller或Action时,将自动检查请求中的Token是否有效。如果Token验证失败,将返回401 Unauthorized状态码。如果验证成功,则可以继续处理请求。 ### 回答3: 在.NET Core WebAPI中配置Token验证主要涉及以下几个步骤: 1. 导入所需的包:首先,需要在`Startup.cs`文件中的`ConfigureServices`方法中导入所需的包。使用`Microsoft.AspNetCore.Authentication.JwtBearer`包来配置JWT验证。 2. 配置认证服务:在`ConfigureServices`方法中使用`services.AddAuthentication`来添加认证服务,并指定默认的身份验证方案。例如: ```csharp services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; // 是否要求HTTPS options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = true, // 验证发行者 ValidateAudience = true, // 验证接收者 ValidateLifetime = true, // 验证令牌有效期 ValidateIssuerSigningKey = true, // 验证签名 ValidIssuer = "your_issuer", ValidAudience = "your_audience", IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your_secret_key")) }; }); ``` 在上述代码中,可以根据自己的需求调整参数值,如验证发行者、接收者、令牌有效期、签名等。 3. 应用认证中间件:在`Configure`方法中,使用`app.UseAuthentication()`来应用认证中间件。确保此代码位于路由中间件之前。例如: ```csharp app.UseAuthentication(); app.UseRouting(); app.UseAuthorization(); ``` 4. 使用`Authorize`特性:在需要进行Token验证的Controller或Action上,可以使用`Authorize`特性来标记,以进行访问控制。例如: ```csharp [Authorize] public class MyController : ControllerBase { // ... } ``` 5. 在请求中包含Token:最后,在发送请求时,需要在请求头中包含Bearer Token,以进行验证。例如: ``` Authorization: Bearer your_token ``` 通过以上配置,就可以在.NET Core WebAPI中实现Token验证。这样,当请求到达API时,API验证Token的有效性,并对请求进行授权控制,确保只有拥有有效Token的用户可以访问受保护的资源。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值