[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. Jmeter函数助手30-groovy

    groovy函数用于脚本执行. 表达式评估:填入Apache Groovy脚本(不是文件名).本身包含逗号的参数值应根据需要进行转义'\,' 存储结果的变量名(可选) 1.引用变量进行截取字符处理 $ ...

  2. 【Kafka】03 Shell 操作

    查看Kafka主题列表 $KAFKA_HOME/bin/kafka-topics.sh \ --zookeeper centos7-02:2181,centos7-03:2181,centos7-04 ...

  3. 【IDEA】转大小写快速操作

    需求场景: 快速修改一些字符全部变成大写,或者小写 例如修改SQL语句,部分字段大写,部分字段小写,需要统一 快捷键: [Ctrl + Shift + U] 演示案例: SELECT ( (SELEC ...

  4. 【Spring Data JPA】05 方法名限定查询

    方法名限定查询 方法名限定查询是对JPQL的再封装 按照SpringData提供的方法名定义方法,不需要配置JPQL语句即可完成查询 在IDEA中都有相应的提示 他会按照方法字符判断 public C ...

  5. 【Windows】XP系统安装TIM/QQ 数字签名过期问题

    需要手动安装数字签名 右键安装包 -> 属性 但是我的TIM没有用,对QQ是有效的 参考自视频: https://www.bilibili.com/video/av413122971/

  6. Python报错:performance hint: av/logging.pyx:232:5: the GIL to be acquired

    参考: https://stackoverflow.com/questions/77410272/problems-installing-python-av-in-windows-11 https:/ ...

  7. 【转载】failed to open /dev/dri/renderd128 permission denied

    原文地址: https://juejin.cn/s/failed%20to%20open%20%2Fdev%2Fdri%2Frenderd128%20permission%20denied ===== ...

  8. Apache DolphinScheduler:深入了解大数据调度工具

    一.海豚调度介绍 Apache DolphinScheduler 是一个分布式易扩展的可视化DAG工作流任务调度开源系统.适用于企业级场景,提供了一个可视化操作任务.工作流和全生命周期数据处理过程的解 ...

  9. 重磅预告!Apache DolphinScheduler 3.2.0 新功能“剧透”

    近期,Apache DolphinScheduler 将迎来 3.2.0 版本的到来.本次发版为大版本发布,将会带来众多大家期待已久的新功能和新改进.为了让用户提前感知到新版本的变化,社区特意提前&q ...

  10. CH01_初识C++

    CH01_初识C++ 第一个C++程序 新建项目 新建文件 编写代码 #include <iostream> using namespace std; int main() { cout ...