jwt实现登录 和 接口实现动态权限
[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实现登录 和 接口实现动态权限的更多相关文章
- SpringBoot 整合Shiro实现动态权限加载更新+Session共享+单点登录
作者:Sans_ juejin.im/post/5d087d605188256de9779e64 一.说明 Shiro是一个安全框架,项目中主要用它做认证,授权,加密,以及用户的会话管理,虽然Shir ...
- 开源干货!!!.NET Core + JWT令牌认证 + Vue.js(iview-admin) 通用动态权限(RBAC)管理系统框架[DncZeus]开源啦!!!
DncZeus 前言 关于 DncZeus DncZeus = Dnc + Zeus "Dnc"--.Net Core 的缩写: "Zeus"--中文译为宙斯, ...
- SpringBootSecurity学习(11)网页版登录之URL动态权限
动态权限 前面讨论用户登录认证的时候,根据用户名查询用户会将用户拥有的角色一起查询出来,自动实现判断当前登录用户拥有哪些角色.可以说用户与角色之间的动态配置和判断security做的非常不错.不过在配 ...
- JWT之登录、登出、验证码接口
6.2 验证码接口 验证码接口用于登录页面展示时,获取验证码图片地址及验证码标识 安装验证码功能组件(如果是官网下载的完整版框架,无需安装) composer require topthink/thi ...
- 常用功能系列---【JWT生成Token实现接口登录认证方案思路】
JWT生成Token实现接口登录认证方案思路 方案一(双token实现无感刷新) 在token中,refreshToken的作用主要是避免token过期时,前端用户突然退出登录,跳转至登录页面. 但是 ...
- 厉害!我带的实习生仅用四步就整合好SpringSecurity+JWT实现登录认证!
小二是新来的实习生,作为技术 leader,我还是很负责任的,有什么锅都想甩给他,啊,不,一不小心怎么把心里话全说出来了呢?重来! 小二是新来的实习生,作为技术 leader,我还是很负责任的,有什么 ...
- SpringBoot整合SpringSecurityOauth2实现鉴权-动态权限
写在前面 思考:为什么需要鉴权呢? 系统开发好上线后,API接口会暴露在互联网上会存在一定的安全风险,例如:爬虫.恶意访问等.因此,我们需要对非开放API接口进行用户鉴权,鉴权通过之后再允许调用. 准 ...
- .net core 2.1 基于Jwt的登录认证
1.新建一个.net core2.1 基于 api 的工程,引用Microsoft.AspNetCore.Authentication.JwtBearer 包 2.新建一个Token的实体类,一个Jw ...
- vue-element-admin登录逻辑,以及动态添加路由,显示侧边栏
这段时间在研究element-admin,感觉这个库有许多值得学习的地方,我学习这个库的方法是,先看它的路由,顺着路由,摸清它的逻辑,有点像顺藤摸瓜. 这个库分的模块非常清晰,适合多人合作开发项目,但 ...
- .net core3.1 abp动态菜单和动态权限(思路) (二)
ps:本文需要先把abp的源码下载一份来下,跟着一起找实现,更容易懂 在abp中,对于权限和菜单使用静态来管理,菜单的加载是在登陆页面的地方(具体是怎么知道的,浏览器按F12,然后去sources中去 ...
随机推荐
- Jmeter函数助手27-urlencode
urlencode函数用于将字符串进行application/x-www-form-urlencoded编码格式化. String to encode in URL encoded chars:填入字 ...
- 常回家看看之fastbin_attack
常回家看看之fastbin_attack 原理分析 fastbin属于小堆块的管理,这里说的fastbin_attack大多指glibc2.26之前的手法,因为自glibc2.26以后,glibc迎来 ...
- 《Python数据可视化之matplotlib实践》 源码 第三篇 演练 第九章
图 9.1 import matplotlib.pyplot as plt import numpy as np fig=plt.figure() ax=fig.add_subplot(111) f ...
- 读论文《Reinforced Attention for Few-Shot Learning and Beyond》
2022年4月22日,实验室开组会,我讲了论文<Reinforced Attention for Few-Shot Learning and Beyond>,最近整理资料又再读了一遍,这里 ...
- Golang在整洁架构基础上实现事务
前言 大家好,这里是白泽,这篇文章在 go-kratos 官方的 layout 项目的整洁架构基础上,实现优雅的数据库事务操作. 视频讲解 :B站:白泽talk,公众号[白泽talk] 本期涉及的学习 ...
- conda 安装pytorch
配置:win 10 ,python=3.6 安装pytorch-1.1.0,cudatoolkit-9.0,torchvision-0.3.0. 出现的问题:import torch 的时候,出现了O ...
- spring创建 JavaWeb
- [NOIP2010 提高组] 关押罪犯 - 洛谷
P1525 [NOIP2010 提高组] 关押罪犯 - 洛谷 | 计算机科学教育新生态 (luogu.com.cn) 种类并查集 #include <bits/stdc++.h> #def ...
- 【CMake系列】10-cmake测试 ctest
cmake作为一个强大的构建系统指导工具,同时也提供了测试功能,可用于项目的单元测试等,也可以与其他测试框架协作,如googletest,共同完成项目开发中的测试工作,本节我们就来学习 如何借助cma ...
- containerd在线部署
containerd的作用以及跟docker的区别 Containerd是一个用于管理容器生命周期的开源项目.它最初是从Docker项目中分离出来的,现在已经成为了一个独立的项目.它可以用作容器镜像管 ...