[Authorize]   ====   using Microsoft.AspNetCore.Authorization;

登录的 DTO

namespace login;

public class WeatherForecast
{
public DateOnly Date { get; set; } public int TemperatureC { get; set; } public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); public string? Summary { get; set; }
}

program.cs 实现 jwt 注册

using Microsoft.IdentityModel.Tokens;
using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
var builder = WebApplication.CreateBuilder(args); // Add services to the container. builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
//取出私钥
var secretByte = Encoding.UTF8.GetBytes(builder.Configuration["Authentication:SecretKey"]);
options.TokenValidationParameters = new TokenValidationParameters()
{
//验证发布者
ValidateIssuer = true,
ValidIssuer = builder.Configuration["Authentication:Issuer"],
//验证接收者
ValidateAudience = true,
ValidAudience = builder.Configuration["Authentication:Audience"],
//验证是否过期
ValidateLifetime = true,
//验证私钥
IssuerSigningKey = new SymmetricSecurityKey(secretByte)
};
}); var app = builder.Build();
//添加jwt验证
app.UseAuthentication();
app.UseAuthorization(); // Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
} app.UseHttpsRedirection(); app.UseAuthorization(); app.MapControllers(); app.Run();

csproj 依赖管理

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup> <ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="7.0.17-preview.2.24128.4" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="7.0.10" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup> </Project>

appsetting.json

{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Authentication": {
"SecretKey": "nadjhfgkadshgoihfkajhkjdhsfaidkuahfhdksjaghidshyaukfhdjks",
"Issuer": "www.adsfsadfasdf",
"Audience": "www.adsfsadfasdf"
}
}

Controller 控制器:

using Microsoft.AspNetCore.Mvc;
using login.Dtos;
using Microsoft.IdentityModel.Tokens;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using System.IdentityModel.Tokens.Jwt;
using System.Text;
namespace login.Controllers; [ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
public readonly IConfiguration _configuration;
private readonly ILogger<WeatherForecastController> _logger; public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration)
{
_logger = logger;
_configuration = configuration;
}
[HttpPost("testLogin")]
public IActionResult Login([FromBody] LoginDto loginDto)
{
//1.验证用户账号密码是否正确,暂时忽略,因为我们是模拟登录
//2.生成JWT
//Header,选择签名算法
var signingAlogorithm = SecurityAlgorithms.HmacSha256;
System.Console.WriteLine("算法");
System.Console.WriteLine(signingAlogorithm);
var claims = new[]
{
new Claim(JwtRegisteredClaimNames.Sub,"user_id"),
new Claim(ClaimTypes.Role,"admin")
};
//取出私钥并以utf8编码字节输出
var secretByte = Encoding.UTF8.GetBytes(_configuration["Authentication:SecretKey"]);
//使用非对称算法对私钥进行加密
var signingKey = new SymmetricSecurityKey(secretByte);
//使用HmacSha256来验证加密后的私钥生成数字签名
var signingCredentials = new SigningCredentials(signingKey, signingAlogorithm);
//生成Token
var Token = new JwtSecurityToken(
issuer: _configuration["Authentication:Issuer"], //发布者
audience: _configuration["Authentication:Audience"], //接收者
claims: claims, //存放的用户信息
notBefore: DateTime.UtcNow, //发布时间
expires: DateTime.UtcNow.AddDays(1), //有效期设置为1天
signingCredentials //数字签名
);
//生成字符串 token
var TokenStr = new JwtSecurityTokenHandler().WriteToken(Token);
return Ok(TokenStr);
} /// <summary>
/// [Authorize(Roles = "admin")] 需要验证token 只允许 admin 角色使用
/// </summary>
/// <returns></returns>
[HttpGet(Name = "GetWeatherForecast")]
[Authorize(Roles = "admin")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}

实现基于jwt登录

jwt实现登录 和 接口实现动态权限的更多相关文章

  1. SpringBoot 整合Shiro实现动态权限加载更新+Session共享+单点登录

    作者:Sans_ juejin.im/post/5d087d605188256de9779e64 一.说明 Shiro是一个安全框架,项目中主要用它做认证,授权,加密,以及用户的会话管理,虽然Shir ...

  2. 开源干货!!!.NET Core + JWT令牌认证 + Vue.js(iview-admin) 通用动态权限(RBAC)管理系统框架[DncZeus]开源啦!!!

    DncZeus 前言 关于 DncZeus DncZeus = Dnc + Zeus "Dnc"--.Net Core 的缩写: "Zeus"--中文译为宙斯, ...

  3. SpringBootSecurity学习(11)网页版登录之URL动态权限

    动态权限 前面讨论用户登录认证的时候,根据用户名查询用户会将用户拥有的角色一起查询出来,自动实现判断当前登录用户拥有哪些角色.可以说用户与角色之间的动态配置和判断security做的非常不错.不过在配 ...

  4. JWT之登录、登出、验证码接口

    6.2 验证码接口 验证码接口用于登录页面展示时,获取验证码图片地址及验证码标识 安装验证码功能组件(如果是官网下载的完整版框架,无需安装) composer require topthink/thi ...

  5. 常用功能系列---【JWT生成Token实现接口登录认证方案思路】

    JWT生成Token实现接口登录认证方案思路 方案一(双token实现无感刷新) 在token中,refreshToken的作用主要是避免token过期时,前端用户突然退出登录,跳转至登录页面. 但是 ...

  6. 厉害!我带的实习生仅用四步就整合好SpringSecurity+JWT实现登录认证!

    小二是新来的实习生,作为技术 leader,我还是很负责任的,有什么锅都想甩给他,啊,不,一不小心怎么把心里话全说出来了呢?重来! 小二是新来的实习生,作为技术 leader,我还是很负责任的,有什么 ...

  7. SpringBoot整合SpringSecurityOauth2实现鉴权-动态权限

    写在前面 思考:为什么需要鉴权呢? 系统开发好上线后,API接口会暴露在互联网上会存在一定的安全风险,例如:爬虫.恶意访问等.因此,我们需要对非开放API接口进行用户鉴权,鉴权通过之后再允许调用. 准 ...

  8. .net core 2.1 基于Jwt的登录认证

    1.新建一个.net core2.1 基于 api 的工程,引用Microsoft.AspNetCore.Authentication.JwtBearer 包 2.新建一个Token的实体类,一个Jw ...

  9. vue-element-admin登录逻辑,以及动态添加路由,显示侧边栏

    这段时间在研究element-admin,感觉这个库有许多值得学习的地方,我学习这个库的方法是,先看它的路由,顺着路由,摸清它的逻辑,有点像顺藤摸瓜. 这个库分的模块非常清晰,适合多人合作开发项目,但 ...

  10. .net core3.1 abp动态菜单和动态权限(思路) (二)

    ps:本文需要先把abp的源码下载一份来下,跟着一起找实现,更容易懂 在abp中,对于权限和菜单使用静态来管理,菜单的加载是在登陆页面的地方(具体是怎么知道的,浏览器按F12,然后去sources中去 ...

随机推荐

  1. excel一次性粘贴2万行数据

    测试导入文件功能中,会出现需要验证导入大批量数据文件的情况,怎么样让文件快速从1行数据变成2万行数据呢,以下讲解方法: 1.如下原文件只有2行数据,第一行是标题第二行是数据 2. 选中需要复制的第二行 ...

  2. 大语言模型(LLM)运行报错:module ‘streamlit‘ has no attribute ‘chat_message‘

    参考: https://blog.csdn.net/weixin_45748921/article/details/134645308 问题在于版本不匹配,深究一下为什么各个版本软件不匹配,发现原因是 ...

  3. GPG公钥的删除与注销

    参考: 如何在 Gitee 上使用 GPG 我们通过在本地主机保存GPG私钥,然后在Gitee或Github上保存GPG公钥的方式来实现对git的commit和tag操作的签名. 当GPG公私秘钥对作 ...

  4. 【转载】 EdgeX Foundry试运行

    原文地址: https://www.cnblogs.com/charlieroro/p/14843335.html ========================================== ...

  5. 查看并添加python中库的搜索路径

    根据前文  pip install --user 使用方法和注意事项--python中安装module库到用户packages路径中 我们知道python中除了自身的全局module lib路径以外还 ...

  6. CUDA编译.cu文件报错unsupported GNU version! gcc versions later than 10 are not supported! The nvcc flag '-allow-unsupported-compiler' can be used to override this version check;

    最近使用cuda11.3编译.cu文件,报错: #error -- unsupported GNU version! gcc versions later than 10 are not suppor ...

  7. 说说中国高校理工科教育中的基础概念混乱问题——GPU是ASIC吗

    在YouTube上看到这样一个视频: https://www.youtube.com/watch?v=7EXDp6c9n-Q&lc=Ugydwl8gppB5FWE8Y5V4AaABAg.9fc ...

  8. 曝光!Apache SeaTunnel Catalog 功能设计为何能大大简化用户启用步骤?

    Catalog(目录)提供了关于数据库.表格和访问数据所需的信息的元数据,以及统一的 API 来管理元数据,验证连接,让元数据对 Sources(数据源).Sinks(数据汇)和 Web 可访问. C ...

  9. ρars/ey 题解

    给个链接:ρars/ey. 我们考虑一个树上背包. 设 \(f_{u,i}\) 表示在 \(u\) 号节点的子树内删除 \(i\) 个点的最小代价.显然有答案为 \(f_{1,siz_1-1}\). ...

  10. Avnet ZUBoard 1CG开发板上手—深度学习新选择

    Avnet ZUBoard 1CG 开发板上手-深度学习新选择 摘要 本文主要介绍了 Avnet ZUBoard 1CG 开发板的特性.架构.硬件单元等概念,并对如何使用以太网接口和串口连接开发板进行 ...