首页 > 编程语言 >Asp.net core使用Authentication使用jwt简单登录认证

Asp.net core使用Authentication使用jwt简单登录认证

时间:2024-03-16 16:44:06浏览次数:31  
标签:core Asp Jwt app jwt using var new configuration

研究了两天,简单使用就这些,如果需要token续期或者刷新或者自定义校验处理需要重写比较麻烦。

在controller中单独获取请求头可使用 

HttpContext.Request.Headers["Authorization"]

使用流程是:先认证登录 -> 再校验权限

Authentication -> Authorization

 

  1. 安装依赖,.net8版本为例
    1. Microsoft.AspNetCore.Authentication.JwtBearer
    2. Newtonsoft.Json
  1. 配置jwt所需配置,再appsettings.json文件
"Jwt": {
  "SecretKey": "U2FsdGVkX1/52fw3vL3OY4F1H7BV12pjPPb1mUhZyEPVRk72S5X2z/A8V9lTvK6T",
  "Issuer": "WebAppIssuer",
  "Audience": "WebAppAudience",
  "Expire": 30000
}
  1. jwt生成或解析帮助类 JwtHelper
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using Microsoft.IdentityModel.Tokens;

namespace jwt_api.Helper;

public class JwtHelper
{

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

    public string CreateToken(string Name, int id)
    {
        // 1. 定义需要使用到的Claims
        var claims = new[]
        {
            new Claim(ClaimTypes.Name, "u_admin"), //HttpContext.User.Identity.Name       
            new Claim("Id", id.ToString()),
            new Claim("Name", Name)
        };

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

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

        // 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.AddSeconds(Convert.ToInt32(_configuration["Jwt:Expire"])),    //expires
            signingCredentials               //Credentials
        );

        // 6. 将token变为string
        var token = new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);

        return token;
    }

}
  1. 主程序编写 Program.cs
using System.Text;
using jwt_api.Helper;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Newtonsoft.Json;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddControllers();

#region 配置登录认证

var configuration = builder.Configuration;
// 配置登录认证
builder.Services.AddAuthentication(options =>
                                   {
                                       options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; 
                                   }).AddJwtBearer(options =>
                {
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuer = true, //是否验证Issuer
                        ValidIssuer = configuration["Jwt:Issuer"], //发行人Issuer
                        ValidateAudience = true, //是否验证Audience
                        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,
                    };
                    // 当token验证通过后(执行完 JwtBearerEvents.TokenValidated 后),
                    // 是否将token存储在 Microsoft.AspNetCore.Authentication.AuthenticationProperties 中
                    // 默认 true
                    options.SaveToken = true;
                    options.Events = new JwtBearerEvents
                    {
                        //此处为权限验证失败后触发的事件
                        OnChallenge = context =>
                        {
                            //此处代码为终止.Net Core默认的返回类型和数据结果,这个很重要哦,必须
                            context.HandleResponse();

                            //自定义自己想要返回的数据结果,我这里要返回的是Json对象,通过引用Newtonsoft.Json库进行转换
                            var payload = JsonConvert.SerializeObject(new { Code = "401", Message = "很抱歉,您无权访问该接口;请登录!" });
                            //自定义返回的数据类型
                            context.Response.ContentType = "application/json";
                            //自定义返回状态码,默认为401 我这里改成 200
                            context.Response.StatusCode = StatusCodes.Status200OK;
                            //输出Json数据结果
                            context.Response.WriteAsync(payload);
                            return Task.FromResult(0);
                        }
                    };
                });
// 添加一个生成jwt和解析帮助类
builder.Services.AddSingleton<JwtHelper>();

#endregion

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

#region 启用认证

app.UseAuthentication();
app.UseAuthorization();

#endregion

app.MapControllers();

/*app.MapGet("/secret", (ClaimsPrincipal user) => $"Hello {user.Identity?.Name}. My secret")
    .RequireAuthorization();*/

app.Run();
  1. 编写测试请求

  1. 测试结果
    1. 使用1接口获取token,再测试2接口成功结果

    1. 失败结果如下

 

标签:core,Asp,Jwt,app,jwt,using,var,new,configuration
From: https://www.cnblogs.com/Zeng02/p/18077250

相关文章

  • jwt
    [jsonwebtoken挖坑]token令牌,注册时生成,登陆验证通过后下发//installnpminstalljsonwebtoken//生成consttoken='Bearer'+jwt.sign({userid:1},secret)//secret生成令牌加密用到的字符串,尽可能复杂一点//解析constdecode=jwt.ver......
  • [引].NET 和 .NET Core 支持策略
    .NET5和.NetCore官方支持策略(microsoft.com) NET和.NETCore版本生命周期支持的版本下表跟踪.NET和.NETCore版本的发布和终止支持日期。版本原始发布日期最新补丁版本补丁发布日期发布类型支持阶段终止支持.NET82023年11月14日8.0.32024年3月12日......
  • .Net Core 你必须知道的source-generators
    源生成器是C#9中引入的一项功能,允许在编译过程中动态生成代码。它们直接与C#编译器集成(Roslyn)并在编译时运行,分析源代码并根据分析结果生成附加代码。源生成器提供了一种简化的自动化代码生成方法,无需外部工具或单独的预编译步骤。通过无缝集成到编译过程中,源生成器可......
  • AspNetCore8.0实战
    前言想变优秀的第N天。学习张老师的Blog.Core。1.创建Asp.NetCoreAPI1.1创建项目启用OpenAPI:sawgger不适用顶级语句:使用main函数使用控制器:controller1.2配置说明iisSettings:iis配置。http:kestrl启动配置。IISExpress:iis启动配置。2.仓储+服务创建以下公共类......
  • 使用JWT进行授权认证
    .Net6WebAPI中1、安装组件(Nuget)Microsoft.AspNetCore.Authentication.JwtBearer2、Program.cs配置//授权认证(使用JWT)builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(o=>{//私钥varsecretByte=Encoding.UTF8.GetBytes......
  • .NetCore Web Api 项目Docker部署
    .NetCoreWebApi项目Docker部署.Net5之后版本编写的项目代码编译后均可以分别部署在Windows、Linux系统下。只需要安装对应的SDK或者运行时。这篇文章主要介绍.Net项目编译之后通过docker镜像部署WebApi项目了解dotnet命令dotnet命令详细说明链接。不得不说微软的文档......
  • .NET Aspire Preview 4 发布!
    .NETAspirePreview4isnowavailable!Here'sasummaryofwhat'snewinthispreviewrelease:.NETAspirePreview4现已推出!以下是此预览版中新增内容的摘要:Podman  Supportforrunningappswith podman支持使用 podman 运行应用程序Dashboard  仪表板......
  • 使用 u-boot 和 rootfs/Initramfs 启动 Raspberry Pi 4
    使用u-boot和rootfs/initramfs启动RaspberryPi4B0.概述这篇文章的目的是了解嵌入式Linux的四个组成部分——工具链、引导加载程序、内核、根文件系统——通过使用最少的代码从头开始启动RaspberryPi4的命令。1.硬件要求用于编译源代码的Linux桌面计算机。......
  • 反编译aspose-words
    publicstaticvoidmain(String[]args)throwsException{ClassPool.getDefault().insertClassPath("F:/lib/aspose-words-21.6-jdk16.jar");//获取javassist默认类池ClassPoolpool=ClassPool.getDefault();//获取domain.Hello......
  • Raspberry:Wiringpi的安装及使用
    +++title="Raspberry:Wiringpi的安装及使用"description="Wiringpi的安装及使用"date=2022-05-04T14:01:09+08:00author="chao"draft=falseimage=""math=truecategories=["os"]tags=["raspberry"]+......