.net 默认新建Api项目不需要额外从Nuget添加Microsoft.AspNetCore.Authentication.JwtBearer

appsettings.json

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Authentication": {
//私钥必须16位
"SecretKey": "YpdCP1VHoWkNawmb",
//谁签发的(发布者)
"issuer": "issuer",
//签发给谁(持有者)
"audience": "audience"
}
}

AuthController,具体登录实现可参考我以前文章Identity用户管理入门五(登录、注销)

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text; namespace Shop.WebHost.Controllers
{
[Route("auth")]
[ApiController]
public class AuthController : ControllerBase
{
private readonly IConfiguration _configuration; public AuthController(IConfiguration configuration)
{
_configuration = configuration;
}
// GET: api/<AuthController>
[AllowAnonymous]
[HttpPost("Login")]
public ActionResult Login([FromForm] UserDto loginUser)
{
//模拟登陆用户提交数据
//以下假设登陆验证通过 // JWT主要由三部分组成:HEADER.PAYLOAD.SIGNATURE // HEADER,加密算法和签名的类型,加密算法是HmacSha256
const string signingAlgorithm = SecurityAlgorithms.HmacSha256; //Payload,如用户名,角色等信息,过期日期等,因为是未加密的,所以不建议存放敏感信息。
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub, "user_id"), //红色字体为登录后获取的实际用户ID
//用户角色
new Claim(ClaimTypes.Role,"Admin"), //红色字体为用户登录后获取的实际用户角色
};
            //Signiture从配置文件获取私钥
var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
//使用非对称算法对私钥进行加密
var signingKey = new SymmetricSecurityKey(secretByte);
//使用HmacSha256验证非对称加密后的私钥
var signingCredentials = new SigningCredentials(signingKey, signingAlgorithm); //创建Jwt Token
var token = new JwtSecurityToken(
//谁发布的token
issuer: _configuration["Authentication:issuer"],
//发布给谁
audience: _configuration["Authentication:audience"],
//Payload
claims,
//发布时间
notBefore: DateTime.UtcNow,
//有效期s
expires: DateTime.UtcNow.AddDays(1),
//数字签名
signingCredentials
);
return Ok(new JwtSecurityTokenHandler().WriteToken(token));
}
} public class UserDto
{
public string UserName { get; set; }
public string Password { get; set; }
}
}

Startup.cs

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using System.Text; namespace Shop.WebHost
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
} public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
//Jwt认证服务
//AddAuthentication注册认证服务
//JwtBearerDefaults.AuthenticationScheme身份认证类型
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
//Jwt身份认证
.AddJwtBearer(option =>
{
//从配置文件读取私钥
var secretByte= Encoding.UTF8.GetBytes(Configuration["Authentication:SecretKey"]);
//身份认证参数
option.TokenValidationParameters = new TokenValidationParameters()
{
//验证发布者
ValidateIssuer = true,
ValidIssuer = Configuration["Authentication:issuer"], //验证持有者
ValidateAudience = true,
ValidAudience = Configuration["Authentication:audience"], //验证是否过期
ValidateLifetime = true, //加密私钥
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Shop.WebHost", Version = "v1" });
});
} public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Shop.WebHost v1"));
} app.UseHttpsRedirection(); //你在哪
app.UseRouting();
//你是谁
app.UseAuthentication();
//你可以干什么
app.UseAuthorization(); app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

在控制器方法中增加【Authorize】即可未登录用户不能访问

控制用户组访问[Authorize(Roles = "Admin")]

// 由于我们没有将身份验证中间件配置为自动运行并创建身份,
// 因此在授权时必须选择要使用的中间件。
// 选择要授权的中间件的最简单方法是使用ActiveAuthenticationSchemes属性
[Authorize(AuthenticationSchemes = "Bearer")]

访问方式在header中增加(具体格式是Authorization:Bearer+空格+具体Token

Authorization:Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyX2lkIiwibmJmIjoxNjA3MzI1NzkxLCJleHAiOjE2MDc0MTIxOTEsImlzcyI6Imlzc3VlciIsImF1ZCI6ImF1ZGllbmNlIn0.ZEN3m7XP8u-u9CNkVf1tfeznqh1SuK7Y0wD1bq9rSfQ

获取当前登录用户ID

startup.cs增加HttpContextAccessor服务并注入HttpContext的访问器对象IHttpContextAccessor来获取当前的HttpContext

services.AddHttpContextAccessor();
private readonly IHttpContextAccessor _httpContextAccessor;

public AuthController(IHttpContextAccessor httpContextAccessor)
{
_httpContextAccessor = httpContextAccessor;
}

增加获取当前用户ID方法

[HttpGet(nameof(GetCurrUserIdAsync))]
public async Task<string> GetCurrUserIdAsync()
{
var auth = await _httpContextAccessor.HttpContext!.AuthenticateAsync();//获取登录用户的AuthenticateResult
if (!auth.Succeeded) return null;
var userCli = auth.Principal?.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier); //在声明集合中获取ClaimTypes.NameIdentifier 的值就是用户ID
if (userCli == null || string.IsNullOrEmpty(userCli.Value))
{
return null;
}
return userCli.Value;
}

或者使用

return _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

查询出当前用户ID就可以根据Identity用户管理入门二(显示用户列表)显示用户详情

Asp.net Core Jwt简单使用的更多相关文章

  1. ASP.NET Core CORS 简单使用

    CORS 全称"跨域资源共享"(Cross-origin resource sharing). 跨域就是不同域之间进行数据访问,比如 a.sample.com 访问 b.sampl ...

  2. ASP.NET Core 项目简单实现身份验证及鉴权

    ASP.NET Core 身份验证及鉴权 目录 项目准备 身份验证 定义基本类型和接口 编写验证处理器 实现用户身份验证 权限鉴定 思路 编写过滤器类及相关接口 实现属性注入 实现用户权限鉴定 测试 ...

  3. CZGL.Auth: ASP.NET Core Jwt角色授权快速配置库

    CZGL.Auth CZGL.Auth 是一个基于 Jwt 实现的快速角色授权库,ASP.Net Core 的 Identity 默认的授权是 Cookie.而 Jwt 授权只提供了基础实现和接口,需 ...

  4. ASP.NET Core - JWT认证实现

    一.JWT结构 JWT介绍就太多了,这里主要关注下Jwt的结构. Jwt中包含三个部分:Header(头部).Payload(负载).Signature(签名) Header:描述 JWT 的元数据的 ...

  5. 使用SignalR ASP.NET Core来简单实现一个后台实时推送数据给Echarts展示图表的功能

    什么是 SignalR ASP.NET Core ASP.NET Core SignalR 是一种开放源代码库,可简化将实时 web 功能添加到应用程序的功能. 实时 web 功能使服务器端代码可以立 ...

  6. Asp.Net Core中简单使用日志组件log4net

    本文将简单介绍在.NET 6中使用log4net的方法,具体见下文范例. 1.首先新建一个ASP.NET Core空项目 2.通过Nuget包管理器安装下面两个包 log4net Microsoft. ...

  7. C# ASP.NET MVC/WebApi 或者 ASP.NET CORE 最简单高效的跨域设置

    概述 前面写了一篇:<C# ASP.NET WebApi 跨域设置>的文章,主要针对 ASP.NET WebApi 项目. 今天遇到 ASP.NET MVC 项目也需要设置跨域,否则浏览器 ...

  8. 基于Asp.Net Core的简单社区项目源代码开源

    2019年3月27号 更新版本 本项目基于 ASP.NET CORE 3.0+EF CORE 3.0开发 使用vs2019 +sqlserver 2017(数据库脚本最低支持sql server 20 ...

  9. 部署ASP.NET Core最简单的办法,使用IIS部署ASP.NET Core应用

    本文迁移自Panda666原博客,原发布时间:2021年3月28日.写原文的时候.NET的最新版本是5.0,现在7的preview出来了,时间真快啊.抽空再写个在Windows Server Core ...

随机推荐

  1. Java中泛型的详细解析,深入分析泛型的使用方式

    泛型的基本概念 泛型: 参数化类型 参数: 定义方法时有形参 调用方法时传递实参 参数化类型: 将类型由原来的具体的类型参数化,类似方法中的变量参数 类型定义成参数形式, 可以称为类型形参 在使用或者 ...

  2. 正则表达式-固定XML格式提取内容

    (?<=(<(?<a>([A-Za-z]*?))>)).*?(?=(</\k<a>>))

  3. Mybatis源码解析1—— JDBC

    在之前的文章中,我为大家介绍了 Mybatis 的详细用法,算是基础教程. 详细链接:Mybatis 基础教程 言归正传,只懂基础可不行,接下来将给大家带来高阶的源码解析教程,从浅入深,通过源码解析, ...

  4. 【Unity3D】Android App Bundle(aab)打包上架Google Play介绍

    总体说来,Android App Bundle打包有3种方式,每种方式都有成功上架Google Play进行测试通过,因此实用程度还是挺高的.能够理解以下内容的前提是会打apk包,知道如何生成Asse ...

  5. Notes about multiboot usb creator

    U盘上的多系统启动工具,Windows上YUMI比较好,Ubuntu上MultiSystem用法复杂,unetbootin是另外一款,需要安装p7zip(apt-get install p7zip-f ...

  6. awk-05-数组

    数组 数组: 存储一系列相同类型的元素,键/值方式存储,通过下标(键)来访问值 awk 中数组称为关联数组,不仅可以使用数字作为下标,还可以使用字符串作为下标 数组元素的键和值存储在 awk 程序内部 ...

  7. Linux下的段错误(Segmentation fault)

    Linux下的段错误(Segmentation fault) 段错误是指:访问了系统分配给程序的内存空间之外起的内存空间,比如: 访问不存在的地址 访问受系统保护的地址 访问了只读内存地址 内存访问越 ...

  8. S3C2440—2.裸机开发步骤及工具使用

    文章目录 一.裸机开发步骤简介 1.在X86架构的Windows系统中 2.在X86架构的Ubuntu系统中 3.ARM裸机开发 二.soucre insight使用 1.sourec insight ...

  9. 内存吞金兽(Elasticsearch)的那些事儿 -- 常见问题痛点及解决方案

    1.大数据量的查询效率如何保证: 查询的流程:往 ES 里写的数据,实际上都写到磁盘文件里去了,查询的时候,操作系统会将磁盘文件里的数据自动缓存到 Filesystem Cache 里面去 最佳的情况 ...

  10. noip14

    T1 考试假贪心,20pts,能摧毁就摧毁,不管前边已经摧毁的水晶. 正解: 首先肯定要离散化,然后考虑dp,设 \(dp_{i,j}\) 表示当前处理到了i,摧毁掉的水晶的a最小为j,则转移方程: ...