Asp.Net Core认证-Jwt-基础篇

简介: Asp.Net Core认证-Jwt-基础篇


一、添加依赖

创建 Core 对应 WebApplication ,选择项目类型为 Web Api ,需要引入 Nuget 包 ,Microsoft.AspNetCore.Authentication.JwtBearer

二、添加认证服务

ConfigureServices 中添加 AddAuthentication 函数,配置如下:

public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    //设置secret
    byte[] secret = System.Text.Encoding.UTF8.GetBytes("1234567890123456");
    //添加认证服务
    services.AddAuthentication(config => {
        //设置默认架构
        config.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    //添加Jwt自定义配置
    .AddJwtBearer(config => {
        //设置Token验证参数项
        config.TokenValidationParameters = new TokenValidationParameters
        {
            //认证秘钥
            IssuerSigningKey = new SymmetricSecurityKey(secret),
            //是否调用对 securityToken 签名的
            //Microsoft.IdentityModel.Tokens.SecurityKey 的验证
            ValidateIssuerSigningKey = true,
            //颁发者
            ValidIssuer = "ggcy",
            //是否验证颁发者
            ValidateIssuer = true,
            //受众
            ValidAudience = "Audience",
            //是否验证受众
            ValidateAudience = true,
            //是否验证凭证有效时限
            ValidateLifetime = true,
            ClockSkew = TimeSpan.FromMinutes(5)
        };
    });
}

上述代码中 TokenValidationParameters 中的认证秘钥 IssuerSigningKey 、颁发者 ValidIssuer 、受众 ValidAudience 中,认证秘钥作为必须验证项,后者两项,理论上也需要进行校验,提高数据到安全性,需要设置对应配置为启用状态。

AddAuthentication 对应源码结构如下:

public static class AuthenticationServiceCollectionExtensions
{
    public static AuthenticationBuilder AddAuthentication(this IServiceCollection services)
    {
        //
    }
    public static AuthenticationBuilder AddAuthentication(this IServiceCollection services, Action<AuthenticationOptions> configureOptions)
    {
        //
    }
    public static AuthenticationBuilder AddAuthentication(this IServiceCollection services, string defaultScheme)
    {
        //
    }
}

三、启用认证中间件

服务中,在介于路由中间件 UseRouting 与节点中间件 UseEndpoints 之间添加认证中间件 UseAuthentication,结构如下:

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //忽略
    app.UseRouting();
    //启用认证管道中间件
    app.UseAuthentication();
    app.UseAuthorization();
    app.UseEndpoints(endpoints =>
    {
        //
    })

四、添加认证接口

创建简单的获取凭证的 Api,创建一个控制器 TokenController,添加内容如下:

[ApiController]
[Route("[controller]")]
public class TokenController : ControllerBase
{
    [HttpGet]
    public object Get()
    {
        //秘钥
        byte[] secret = System.Text.Encoding.UTF8.GetBytes("1234567890123456");
        //生成秘钥
        var key = new SymmetricSecurityKey(secret);
        //生成数字签名的签名密钥、签名密钥标识符和安全算法
        var credential = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
        //构建JwtSecurityToken类实例
        var token = new JwtSecurityToken(
            //添加颁发者
            issuer: "ggcy", 
            //添加受众
            audience: "Audience",
            //添加其他声明
            new List<Claim> { 
                new Claim(ClaimTypes.Name,"zhangsan"),
                new Claim(ClaimTypes.Role,"admin")
            },
            expires: DateTime.UtcNow.AddMinutes(5)
            ,signingCredentials:credential);
        //签发token
        return Ok(new
        {
            access_token = new JwtSecurityTokenHandler().WriteToken(token)
        });
    }
}

其中 JwtSecurityToken 函数的参数 issueraudience 服务配置时的对应内容 ValidIssuerValidIssuer 保持一致。

五、测试效果

运行项目,使用 Postman 请求链接 http://localhost:5000/token,获取结果如下:

将获取到的 access_token 本地保留,请求获取 http://localhost:5000/weatherforecast ,链接数据时,在Auth页签中,选择添加类型为 Bearer Token 类型的认证方式,填入对应 access_token ,内容如下:

1、请求结果

1)成功

请求成功时,能够获取到对应的 api 请求结果,返回如下结果:

2)错误

当带有的 token 无效或者验证不通过时,响应结果常常是 401Unauthorized,具体反馈错误内容,从实际请求响应结果中进行查看。具体常见内容如下:

token 过期

HTTP/1.1 401 Unauthorized
Date: Wed, 08 Sep 2021 15:16:10 GMT
Server: Kestrel
Content-Length: 0
WWW-Authenticate: Bearer error="invalid_token", error_description="The token expired at '09/08/2021 15:06:28'"

token 不合法

HTTP/1.1 401 Unauthorized
Date: Wed, 08 Sep 2021 14:59:02 GMT
Server: Kestrel
Content-Length: 0
WWW-Authenticate: Bearer error="invalid_token", error_description="The signature is invalid"

issueraduenice 内容与服务配置不匹配

HTTP/1.1 401 Unauthorized
Date: Wed, 08 Sep 2021 15:02:30 GMT
Server: Kestrel
Content-Length: 0
WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'xxx' is invalid"
HTTP/1.1 401 Unauthorized
Date: Wed, 08 Sep 2021 15:04:28 GMT
Server: Kestrel
Content-Length: 0
WWW-Authenticate: Bearer error="invalid_token", error_description="The audience 'xxx' is invalid"

以上为 Asp.Net Core 使用 Jwt 基本操作和常见细节问题。

六、参考链接

[1]

https://www.cnblogs.com/ittranslator/p/asp-net-core-5-rest-api-authentication-with-jwt-step-by-step.html

相关文章
|
5天前
|
SQL Java 测试技术
在Spring boot中 使用JWT和过滤器实现登录认证
在Spring boot中 使用JWT和过滤器实现登录认证
|
4天前
|
存储 开发框架 安全
ASP.NET WebApi 如何使用 OAuth2.0 认证
ASP.NET WebApi 如何使用 OAuth2.0 认证
|
4天前
|
存储 开发框架 算法
ASP.NET Core 标识(Identity)框架系列(四):闲聊 JWT 的缺点,和一些解决思路
ASP.NET Core 标识(Identity)框架系列(四):闲聊 JWT 的缺点,和一些解决思路
|
14天前
|
JSON 安全 数据安全/隐私保护
Python 安全性大揭秘:OAuth 与 JWT,不只是认证,更是信任的传递
【8月更文挑战第6天】在数字化时代,Python 通过 OAuth 和 JWT 筑牢应用安全防线。OAuth 是一种授权框架,允许第三方应用在用户授权下安全访问资源;JWT 则是一种自包含的声明传输格式,确保通信安全。两者结合使用,能有效进行身份验证及授权管理。然而,密钥管理和 JWT 有效期设置等仍是挑战,需谨慎处理以保障整体安全性。正确配置这些工具和技术,可为用户提供既安全又便捷的服务体验。
24 7
|
14天前
|
JSON 安全 数据安全/隐私保护
Python安全新篇章:OAuth与JWT携手,开启认证与授权的新时代
【8月更文挑战第6天】随着互联网应用的发展,安全认证与授权变得至关重要。本文介绍OAuth与JWT两种关键技术,并展示如何结合它们构建安全系统。OAuth允许用户授权第三方应用访问特定信息,无需分享登录凭证。JWT是一种自包含的信息传输格式,用于安全地传递信息。通过OAuth认证用户并获取JWT,可以验证用户身份并保护数据安全,为用户提供可靠的身份验证体验。
27 6
|
4天前
|
存储 前端开发 JavaScript
2022年超详细的SpringBoot+Vue+Jwt实现token的认证(重点部分讲解和完整的代码设计)
这篇文章详细介绍了使用SpringBoot、Vue.js和Jwt实现token认证的完整流程和代码设计,包括后端的jwt依赖引入、token生成和认证过滤器编写,以及前端的路由守卫、Vuex状态管理和token的存储与使用,确保用户登录状态的维护和验证。
|
4天前
|
存储 开发框架 JSON
ASP.NET Core 标识(Identity)框架系列(二):使用标识(Identity)框架生成 JWT Token
ASP.NET Core 标识(Identity)框架系列(二):使用标识(Identity)框架生成 JWT Token
|
5天前
|
JSON 人工智能 算法
Golang 搭建 WebSocket 应用(四) - jwt 认证
Golang 搭建 WebSocket 应用(四) - jwt 认证
12 0
|
4天前
|
开发框架 前端开发 .NET
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
ASP.NET MVC WebApi 接口返回 JOSN 日期格式化 date format
10 0
|
4天前
|
开发框架 前端开发 安全
ASP.NET MVC 如何使用 Form Authentication?
ASP.NET MVC 如何使用 Form Authentication?