.net core Jwt 添加
Jwt 已经成为跨平台身份验证通用方案,如不了解请关注:https://jwt.io/。
为了和微软其他验证模块有个比较好的衔接,项目中采用了微软开发的jwt组件: System.IdentityModel.Tokens.Jwt。首先安装:Install-Package System.IdentityModel.Tokens.Jwt。
在config方法中添加
if (!HostingEnvironment.IsEnvironment("test"))
{
app.UseJwtBearerAuthentication(Jwt.GetJwtOptions());
}
实现一个jwt工具类:
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNet.Hosting;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Extensions;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using NDaisy.Core.ServiceLocator;
using WebApiCore.Core.Utility.Extension;
using IHostingEnvironment = Microsoft.AspNetCore.Hosting.IHostingEnvironment; namespace WebApiCore.Utility
{
public class Jwt
{
private static SecurityKey _signKey;
private static IConfigurationSection _config;
private const string Issue = "webcore";
static Jwt()
{
_config= ServiceLocator.Current.GetInstance<IConfigurationRoot>().GetSection("Jwt");
var keyAsBytes = Encoding.ASCII.GetBytes(_config.GetValue<string>("Salt"));
_signKey = new SymmetricSecurityKey(keyAsBytes); } public static JwtBearerOptions GetJwtOptions()
{
return new JwtBearerOptions
{
TokenValidationParameters =
{
ValidIssuer = Issue,
IssuerSigningKey = _signKey,
ValidateLifetime = true,
ValidateIssuer = true,
ValidateAudience = false
},
Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{ return Task.Run(() =>
{
if (ServiceLocator.Current.GetInstance<IHostingEnvironment>().IsDevelopment())
{
c.Request.GetDisplayUrl().LogInfo();
c.Exception.LogError();
} } );
} }
};
} public static string SignToken(IList<Claim> claims)
{
var seconds= _config.GetValue<int>("SlideTime"); JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(issuer: Issue, claims: claims, expires: DateTime.UtcNow.AddSeconds(seconds), signingCredentials: new SigningCredentials(_signKey, SecurityAlgorithms.HmacSha256)); return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
} }
添加一个获取token的入口,实际项目中,放在登录授权里面:
app.Map("/auth/test", appbuilder =>
{
appbuilder.Run(d =>
{
var token= Jwt.SignToken(new List<Claim>() {new Claim("name", "ryan")});
return d.Response.WriteAsync(token);
});
});
.net core Jwt 添加的更多相关文章
- .net core jwt 入门记录
从百度里搜索里搜索了很多jwt的文章,跟着文章写了一个demo,这里记录下学习过程中碰上的问题.看文章多遍,不如手工实现一次. 模板已上传到github.com:dogvane/webapi_jwt_ ...
- [转]三分钟学会.NET Core Jwt 策略授权认证
[转]三分钟学会.NET Core Jwt 策略授权认证 一.前言# 大家好我又回来了,前几天讲过一个关于Jwt的身份验证最简单的案例,但是功能还是不够强大,不适用于真正的项目,是的,在真正面对复杂而 ...
- asp.net core MVC 添加静态文件
ASP.net Core 中添加插件需要 1.将文件放在wwwroot文件夹下(根目录文件夹,没有的话需要创建) 2.需要在project.json中的dependencies添加如下依赖 " ...
- CZGL.Auth: ASP.NET Core Jwt角色授权快速配置库
CZGL.Auth CZGL.Auth 是一个基于 Jwt 实现的快速角色授权库,ASP.Net Core 的 Identity 默认的授权是 Cookie.而 Jwt 授权只提供了基础实现和接口,需 ...
- dotnet core JWT Demo
JWT介绍 JSON Web Token(JWT)是目前最流行的跨域身份验证解决方案.JWT的官网地址:https://jwt.io/. 通俗地来讲,JWT是能代表用户身份的令牌,可以使用JWT令牌在 ...
- .Net Core JWT Bearer 的认证
关于JWT原理在这不多说,主要由三部分组成:Header.Payload.Signature,有兴趣自己上网了解. 1.首先创建.Net Core 一个Api项目 2.添加 JWT 配置 2.1 修改 ...
- 三分钟学会.NET Core Jwt 策略授权认证
一.前言 大家好我又回来了,前几天讲过一个关于Jwt的身份验证最简单的案例,但是功能还是不够强大,不适用于真正的项目,是的,在真正面对复杂而又苛刻的客户中,我们会不知所措,就现在需要将认证授权这一块也 ...
- .Net Core JWT 动态设置接口与权限
通过上一篇.Net Core官方的 JWT 授权验证学习到了JWT的授权.可以发现一个问题,就是如果每个接口可以使用的角色都是写死的,这样如果有所修改会非常麻烦,虽然用policy可以一定程度上缓解, ...
- ASP.NET Core - JWT认证实现
一.JWT结构 JWT介绍就太多了,这里主要关注下Jwt的结构. Jwt中包含三个部分:Header(头部).Payload(负载).Signature(签名) Header:描述 JWT 的元数据的 ...
随机推荐
- bodyParser中间件的研究
原文链接: bodyParser中间件 bodyParser中间件用来解析http请求体,是express默认使用的中间件之一. 使用express应用生成器生成一个网站,它默认已经使用了 bodyP ...
- linux文件对比命令——diff
diff用于比较文件或目录内容,特别是比较两个版本不同的文件以找到改动的地方. 如果指定比较的是文件,则只有当输入为文本文件时才有效,以逐行的方式,比较文本文件的异同处. 如果指定比较的是目录的的时候 ...
- 编写高质量代码:改善Java程序的建议
建议的采用顺序是List<T>.List<?>.List<Object> List<T>.List<?>.List<Object> ...
- Ternary Expression Parser
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- iOS-最全的App上架教程
App上架教程 心情有没有好一点 在上架App之前想要 真机测试的同学 请查看iOS- 最全的真机测试教程 里面包含怎么让多台电脑同时 上架App和同时真机调试.P12文件的使用详解 因为最近更新了X ...
- 49. 3种方法实现复杂链表的复制[clone of complex linked list]
[本文链接] http://www.cnblogs.com/hellogiser/p/clone-of-complex-linked-list.html [题目] 有一个复杂链表,其结点除了有一个ne ...
- [PHP][REDIS]phpredis 'RedisException' with message 'read error on connection'
最近一个后台常驻job通过redis的brpop阻塞读取消息时,设置了永不超时 while( $re=$redis->brPop($queue_name,0) ){ } 但是在实际的使用中发现很 ...
- markdown博文测试
一级标题 二级标题 正文 三级标题 C代码: // code #include <stdio.h> int main() { printf("Hello, World!\n&qu ...
- Apple Pay 初探
Apple Pay 一.概述 1.支付方式:Touch ID/ Passcode 2.设备要求:iPhone6以上(iphone:线上/线下 ipad:线上 watch:线下) 3.系统要求:iOS8 ...
- 【python】with的实现方法
来源:http://www.ibm.com/developerworks/cn/opensource/os-cn-pythonwith/#icomments 重点: with方法适用于需要分配和清理资 ...