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

相关文章
|
2月前
|
开发框架 .NET C#
ASP.NET Core Blazor 路由配置和导航
大家好,我是码农刚子。本文系统介绍Blazor单页应用的路由机制,涵盖基础配置、路由参数、编程式导航及高级功能。通过@page指令定义路由,支持参数约束、可选参数与通配符捕获,结合NavigationManager实现页面跳转与参数传递,并演示用户管理、产品展示等典型场景,全面掌握Blazor路由从入门到实战的完整方案。
270 6
|
开发框架 .NET 开发者
简化 ASP.NET Core 依赖注入(DI)注册-Scrutor
Scrutor 是一个简化 ASP.NET Core 应用程序中依赖注入(DI)注册过程的开源库,支持自动扫描和注册服务。通过简单的配置,开发者可以轻松地从指定程序集中筛选、注册服务,并设置其生命周期,同时支持服务装饰等高级功能。适用于大型项目,提高代码的可维护性和简洁性。仓库地址:&lt;https://github.com/khellang/Scrutor&gt;
314 5
|
开发框架 .NET C#
在 ASP.NET Core 中创建 gRPC 客户端和服务器
本文介绍了如何使用 gRPC 框架搭建一个简单的“Hello World”示例。首先创建了一个名为 GrpcDemo 的解决方案,其中包含一个 gRPC 服务端项目 GrpcServer 和一个客户端项目 GrpcClient。服务端通过定义 `greeter.proto` 文件中的服务和消息类型,实现了一个简单的问候服务 `GreeterService`。客户端则通过 gRPC 客户端库连接到服务端并调用其 `SayHello` 方法,展示了 gRPC 在 C# 中的基本使用方法。
276 5
在 ASP.NET Core 中创建 gRPC 客户端和服务器
|
12月前
|
开发框架 算法 中间件
ASP.NET Core 中的速率限制中间件
在ASP.NET Core中,速率限制中间件用于控制客户端请求速率,防止服务器过载并提高安全性。通过`AddRateLimiter`注册服务,并配置不同策略如固定窗口、滑动窗口、令牌桶和并发限制。这些策略可在全局、控制器或动作级别应用,支持自定义响应处理。使用中间件`UseRateLimiter`启用限流功能,并可通过属性禁用特定控制器或动作的限流。这有助于有效保护API免受滥用和过载。 欢迎关注我的公众号:Net分享 (239字符)
288 1
|
开发框架 缓存 .NET
GraphQL 与 ASP.NET Core 集成:从入门到精通
本文详细介绍了如何在ASP.NET Core中集成GraphQL,包括安装必要的NuGet包、创建GraphQL Schema、配置GraphQL服务等步骤。同时,文章还探讨了常见问题及其解决方法,如处理复杂查询、错误处理、性能优化和实现认证授权等,旨在帮助开发者构建灵活且高效的API。
346 3
|
开发框架 .NET 中间件
ASP.NET Core 面试题(二)
ASP.NET Core 面试题(二)
437 0
|
开发框架 JSON .NET
ASP.NET Core 面试题(一)
ASP.NET Core 面试题(一)
1118 0
|
开发框架 前端开发 .NET
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
ASP.NET CORE 3.1 MVC“指定的网络名不再可用\企图在不存在的网络连接上进行操作”的问题解决过程
450 0
|
开发框架 前端开发 JavaScript
ASP.NET MVC 教程
ASP.NET 是一个使用 HTML、CSS、JavaScript 和服务器脚本创建网页和网站的开发框架。
237 7
|
存储 开发框架 前端开发
[回馈]ASP.NET Core MVC开发实战之商城系统(五)
经过一段时间的准备,新的一期【ASP.NET Core MVC开发实战之商城系统】已经开始,在之前的文章中,讲解了商城系统的整体功能设计,页面布局设计,环境搭建,系统配置,及首页【商品类型,banner条,友情链接,降价促销,新品爆款】,商品列表页面,商品详情等功能的开发,今天继续讲解购物车功能开发,仅供学习分享使用,如有不足之处,还请指正。
339 0