.net core API 项目token验证(JWT方法)

实现生成token、验证token

1、安装包JwtBearer

 我用的框架是.NET Core 3.1 ,JWT包没安装最新的

配置文件 appsetting.json:

 "JWT": {
    "SecretKey": "密钥自定义",
    "Issuer": "自定义",
    "Expires": 24,     //token过期时间
    "Audience": "自定义"
  }

2、ConfigureServices里添加

 // token验证
            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = true,
                    ValidIssuer = Configuration["JWT:Issuer"],
                    ValidateAudience = true,
                    ValidAudience = Configuration["JWT:Audience"],
                    ValidateLifetime = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:SecretKey"]))
                }
           );

 Configure里添加(认证和授权的先后顺序不能改)

//开启认证
app.UseAuthentication();
//开启授权
app.UseAuthorization();

3、生成token方法

        /// <summary>
        /// 生成token
        /// </summary>
        /// <param name="uid">用户的id</param>
        /// <returns>自己创建的类</returns>
        private LoginDTO CreateToken(string uid)
        {
            // 1. 定义需要使用到的Claims
            var claims = new[]
            {
                //把用户的id加密进去,使用的时候可以从token里解密拿出来
                new Claim("uid", uid),
                //也可以多传几个参数
                //new Claim("name", "Admin")
            };

            // 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. 从 appsettings.json 中读取Expires
            var expires = Convert.ToDouble(_configuration["JWT:Expires"]);

            // 6. 根据以上,生成token
            var token = new JwtSecurityToken(
                _configuration["JWT:Issuer"],     //Issuer
                _configuration["JWT:Audience"],   //Audience
                claims,                          //Claims,
                DateTime.Now,                    //notBefore
                DateTime.Now.AddHours(expires),  //expires token过期时间,这里我设置了24小时
                signingCredentials               //Credentials
            );

            // 7. 将token变为string
            var jwtToken = new JwtSecurityTokenHandler().WriteToken(token);

            return new LoginDTO
            {
                UID = uid,
                //LoginDTO是自定义的类,Expires我定义为unix时间戳类型,可以改成其他类型
                Expires = TimeHelper.DatetimeToUnix(DateTime.Now.AddHours(expires)), 
                Token = jwtToken
            };
        }

用户调用登陆接口,验证完毕后用这个方法可以生成token

4、给需要验证的接口所在的controller里加上Authorize标签

 5、从token里取出用户信息

        protected ValueTask<string> GetUserIdAsync()
        {
            //在Claim中填入的uid取出来
            var userId = HttpContext.User.Claims.FirstOrDefault(t => t.Type == "uid")?.Value ?? string.Empty;
            if (!string.IsNullOrWhiteSpace(userId))
            {
                return new ValueTask<string>(userId);
            }
            return new ValueTask<string>("-1");
        }

调用:

string userId= await GetUserIdAsync();

token验证方式:Bearer

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答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的用户可以访问受保护的资源。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值