.net core 学习小结之 JWT 认证授权
- 新增配置文件
{
"Logging": {
"IncludeScopes": false,
"Debug": {
"LogLevel": {
"Default": "Warning"
}
},
"Console": {
"LogLevel": {
"Default": "Warning"
}
}
},
"JwtSettings": {
"Issuer": "http://locahost:5000",
"Audience": "http://locahost:5000",
"SecretKey": "hello world this is my key for cyao"
}
}namespace JwtAuth
{
public class JwtSettings
{
///使用者
public string Issuer { get; set; }
///颁发者
public string Audience { get; set; }
///秘钥必须大于16个字符
public string SecretKey { get; set; }
}
} - 将配置文件读取映射到实体类,并且将jwt授权加入到管道中
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options; namespace JwtAuth
{
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.IdentityModel.Tokens;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
//将配置文件读取到settings
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
JwtSettings settings = new JwtSettings();
Configuration.Bind("JwtSettings", settings);
//添加授权信息
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; })
.AddJwtBearer(c => c.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters//添加jwt 授权信息
{
ValidIssuer = settings.Issuer,
ValidAudience = settings.Audience,
IssuerSigningKey = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey))
});
services.AddMvc();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
//向builder中添加授权的管道
app.UseAuthentication();
app.UseMvc();
}
}
} - 判断当前用户是否合法并且返回授权后的token信息
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; namespace JwtAuth.Controllers
{
using System.Security.Claims;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using Microsoft.AspNetCore.Authentication.JwtBearer;
//添加dll的引用 Nuget Microsoft.AspNetCore.Authentication.JwtBearer;
using System.IdentityModel.Tokens.Jwt;
[Route("Auth/[controller]")]
public class AuthController : Controller
{
public JwtSettings settings;
public AuthController(IOptions<JwtSettings> jwtsettings)
{
settings = jwtsettings.Value;
}
public IActionResult Token([FromBody]LoginInfo model)
{
if (ModelState.IsValid)
{
if (model.username == "cyao" && model.password == "")
{
//用户合法情况
//添加授权信息
var claims = new Claim[] { new Claim(ClaimTypes.Name, "cyao"), new Claim(ClaimTypes.Role, "admin") };
var key = new SymmetricSecurityKey(System.Text.Encoding.UTF8.GetBytes(settings.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(
settings.Issuer,
settings.Audience,
claims,
DateTime.Now,
DateTime.Now.AddMinutes(),//过期时间
creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
}
}
return BadRequest();
}
}
public class LoginInfo
{
[Required]
public string username { get; set; }
[Required]
public string password { get; set; }
}
}
.net core 学习小结之 JWT 认证授权的更多相关文章
- 【ASP.NET Core学习】使用JWT认证授权
概述 认证授权是很多系统的基本功能 , 在以前PC的时代 , 通常是基于cookies-session这样的方式实现认证授权 , 在那个时候通常系统的用户量都不会很大, 所以这种方式也一直很好运行, ...
- .net core 学习小结之 Cookie-based认证
在startup中添加授权相关的管道 using System; using System.Collections.Generic; using System.Linq; using System.T ...
- Dotnet core使用JWT认证授权最佳实践(二)
最近,团队的小伙伴们在做项目时,需要用到JWT认证.遂根据自己的经验,整理成了这篇文章,用来帮助理清JWT认证的原理和代码编写操作. 第一部分:Dotnet core使用JWT认证授权最佳实践(一) ...
- 任务35:JWT 认证授权介绍
任务35:JWT 认证授权介绍 应用场景主要是移动端或者PC端前后分离的场景 直接对客户端API的请求 例如访问admin/Index 没有权限返回403. 需要客户端手动的再发动请求,这是一个拿to ...
- .net core gRPC与IdentityServer4集成认证授权
前言 随着.net core3.0的正式发布,gRPC服务被集成到了VS2019.本文主要演示如何对gRPC的服务进行认证授权. 分析 目前.net core使用最广的认证授权组件是基于OAuth2. ...
- Dotnet core使用JWT认证授权最佳实践(一)
最近,团队的小伙伴们在做项目时,需要用到JWT认证.遂根据自己的经验,整理成了这篇文章,用来帮助理清JWT认证的原理和代码编写操作. 一.JWT JSON Web Token (JWT)是一个开放标准 ...
- 二手商城集成jwt认证授权
------------恢复内容开始------------ 使用jwt进行认证授权的主要流程 参考博客(https://www.cnblogs.com/RayWang/p/9536524.html) ...
- .net core 学习小结之 自定义JWT授权
自定义token的验证类 using System; using System.Collections.Generic; using System.IO; using System.Linq; usi ...
- ASP.NET Core 3.1使用JWT认证Token授权 以及刷新Token
传统Session所暴露的问题 Session: 用户每次在计算机身份认证之后,在服务器内存中会存放一个session,在客户端会保存一个cookie,以便在下次用户请求时进行身份核验.但是这样就暴露 ...
随机推荐
- 深入理解JAVA虚拟机 自动内存管理机制
运行时数据区域 其中右侧三个一起的部分是每个线程一份,左侧两个是所有线程共享的. 程序计数器(Program Counter Register) 英文名称叫Program Counter Regist ...
- Java 接口和内部类
接口的方法默认死public,接口的属性默认为public static final. 为什么要接口,而不是使用抽象类.一个对象只能继承一个类,却可以实现多个接口. clone: Object的浅拷贝 ...
- MyBatis:Parameter Maps collection does not contain value for 的问题解决
Result Maps collection does not contain value for frontpreviewprofitManage.cdata 出现上述错误 主要是因为你的sel ...
- oracle 创建表的规则
1.表明首字母 应该为字母 2.表名的最大长度为30个字符 3.不能使用oracle保留字和关键字来作表名 4.同一用户下的不同表不能具有相同的名称 5.可以使用下划线.数字和字母,但不能使用空格与单 ...
- 5G技术被夸大?专家来测试一下
像大多数新技术一样,5G也带来了大量媒体宣传.这种炒作中有些伴随着事实的严重扭曲和5G技术实际功能的放大.但是,有一个普遍共识的说法是5G将实现“极速”,换句话说,与前几代产品相比,带宽要高得多. 这 ...
- Vue路由参数设置可有可无
参数后面使用 ? id 后面加个 ‘ ? ’ ,将 id 设置为可选参数 { name: "index", path: '/p/:id?', component: resolve ...
- excel解决日常问题记录
=MOD(ROW(),2)和=TEXT(B2487-B2486,"[h]:mm:ss"),我利用excel分析出了延迟的数据 比较2个字符串是否一样:=EXACT(A2,F2) 公 ...
- JAVA批量文件下载
1,看看我们封装的方法 方法中有三个参数:视频url,文件夹路径,视频名称. 调用方法进行下载. 2,看看结果 打印结果 文件夹下的视频下载成功 详细的参数配置可以参考我写的这篇文章:http://b ...
- 将Emacs Org mode用于GTD任务管理
在上一篇日志中,我简要介绍了如何围绕Emacs Org mode构建个人任务管理系统的基本思路与方法.因为Org mode体系庞大.功能繁杂,本文仅以提纲契领的方式介绍不同环节在Org mode中的操 ...
- [Usaco2010 Dec]Treasure Chest 藏宝箱
题目链接:点这里 Solution: 刚开始以为是博弈论,然而不是... 首先考虑n方dp,设f(l,r)为只有\(l\)到\(r\)区间的钱的先手最大获利 那么我们可以得到式子f(l,r)=sum( ...