ASP.NET Core JWT认证授权介绍


using JWTWebApi.Models;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System.Text; namespace JWTWebApi
{
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)
{
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
var jwtsettings = new JwtSettings();
Configuration.Bind("JwtSettings", jwtsettings);
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = jwtsettings.Audience,
ValidIssuer = jwtsettings.Issuer,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtsettings.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();
} app.UseAuthentication();
app.UseMvc();
}
}
}
using JWTWebApi.Models;
using JWTWebApi.ViewModel;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text; namespace JWTWebApi.Controllers
{
[Route("api/[controller]")]
public class AuthrozeController : Controller
{
private readonly JwtSettings _jwtSetting; public AuthrozeController(IOptions<JwtSettings> jwtSetting)
{
_jwtSetting = jwtSetting.Value;
} [HttpGet]
public IActionResult Token()
{
LoginViewModel viewModel = new LoginViewModel(){ User= "wolf",PassWord = "" };
if (ModelState.IsValid)
{
if (viewModel.User == "wolf" && viewModel.PassWord == "")
{
var claims = new Claim[]
{
new Claim(ClaimTypes.Name,"wolf"),
new Claim(ClaimTypes.Role,"admin"),
}; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSetting.SecretKey));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
var token = new JwtSecurityToken(_jwtSetting.Issuer, _jwtSetting.Audience, claims, DateTime.Now,
DateTime.Now.AddHours(), creds);
return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });
} return BadRequest();
} return BadRequest();
}
}
}
{
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
},
"JwtSettings": {
"Issuer": "http://localhost:50443/",
"Audience": "http://localhost:50443/",
"SecretKey": "wolf123456789123456789"
}
}


ASP.NET Core JWT认证授权介绍的更多相关文章
- 任务35:JWT 认证授权介绍
任务35:JWT 认证授权介绍 应用场景主要是移动端或者PC端前后分离的场景 直接对客户端API的请求 例如访问admin/Index 没有权限返回403. 需要客户端手动的再发动请求,这是一个拿to ...
- ASP.NET Core - JWT认证实现
一.JWT结构 JWT介绍就太多了,这里主要关注下Jwt的结构. Jwt中包含三个部分:Header(头部).Payload(负载).Signature(签名) Header:描述 JWT 的元数据的 ...
- CZGL.Auth: ASP.NET Core Jwt角色授权快速配置库
CZGL.Auth CZGL.Auth 是一个基于 Jwt 实现的快速角色授权库,ASP.Net Core 的 Identity 默认的授权是 Cookie.而 Jwt 授权只提供了基础实现和接口,需 ...
- asp.net core-14.JWT认证授权 生成 JWT Token
源码下载 语言组织能力不好 ,看这个 视频 用visual studio code打开文件,运行dotnet watch run 之后在postman里面去访问 拿到Token后
- Dotnet core使用JWT认证授权最佳实践(二)
最近,团队的小伙伴们在做项目时,需要用到JWT认证.遂根据自己的经验,整理成了这篇文章,用来帮助理清JWT认证的原理和代码编写操作. 第一部分:Dotnet core使用JWT认证授权最佳实践(一) ...
- [转]三分钟学会.NET Core Jwt 策略授权认证
[转]三分钟学会.NET Core Jwt 策略授权认证 一.前言# 大家好我又回来了,前几天讲过一个关于Jwt的身份验证最简单的案例,但是功能还是不够强大,不适用于真正的项目,是的,在真正面对复杂而 ...
- asp.net core 自定义认证方式--请求头认证
asp.net core 自定义认证方式--请求头认证 Intro 最近开始真正的实践了一些网关的东西,最近写几篇文章分享一下我的实践以及遇到的问题. 本文主要介绍网关后面的服务如何进行认证. 解决思 ...
- Asp.Net Core 中IdentityServer4 授权中心之自定义授权模式
一.前言 上一篇我分享了一篇关于 Asp.Net Core 中IdentityServer4 授权中心之应用实战 的文章,其中有不少博友给我提了问题,其中有一个博友问我的一个场景,我给他解答的还不够完 ...
- ASP.NET Core Token认证
翻译:Token Authentication in ASP.NET Core 令牌认证(Token Authentication)已经成为单页应用(SPA)和移动应用事实上的标准.即使是传统的B/S ...
随机推荐
- 武汉倍特威视系统有限公司 --- 安全帽识别|烟火识别|智慧工地|BVS智能视频分析
武汉倍特威视系统有限公司 --- 安全帽识别|烟火识别|智慧工地|BVS智能视频分析 http://www.betvsys.com/
- Datasnap 服务端 (Server)Session 管理 --- 解决 全示例慢(Google)
Datasnap 服务端 (Server)Session 管理: http://docwiki.embarcadero.com/RADStudio/Tokyo/en/Server_Side_Ses ...
- vue生命周期学习(watch跟computed)
1.watch钩子函数监听数据的变化 watch 的一个特点是,最初绑定的时候是不会执行的,要等到 firstName 改变时才执行监听计算. <div> <p>FullNam ...
- VB获取CAD属性值
Dim myAcadApp As AutoCAD.AcadApplication, activeDoc As AutoCAD.AcadDocument, acMS As AutoCAD.AcadMod ...
- PCM EQ DRC 音频处理
PCM Pulse-code modulation的缩写,中文译名是脉冲编码调制.(I2S仅仅是PCM的一个分支,接口定义都是一样的, I2S的采样频率一般为44.1KHZ和48KHZ做,PCM采样频 ...
- LabVIEW 波形图表显示多条曲线
如何在波形图表中显示多条曲线呢? 首先看看波形图表的说明,请查看labVIEW 帮助 图 1 波形图表控件的即时帮助信息 关键就在绑定多个点. 图 2 利用捆绑函数将多个信号捆绑成簇 图 3 ...
- C#如何使用SqlCacheDependency
1.数据库依赖类SqlCacheDependency 数据库缓存依赖主要解决的是当数据库的内容发生改变时,如何及时通知缓存,并更新缓存中的数据的问题. 语法定义: SqlCacheDependency ...
- CodeVs 1009
题意: 给出一个整数 n(n<10^30) 和 k 个变换规则(k<=15). 规则: 一位数可变换成另一个一位数: 规则的右部不能为零. 例如:n=234.有规则(k=2): 2-> ...
- python---控制台输出带颜色的文字方法
控制台的展示效果有限,并不能像前端一样炫酷,只能做一些简单的设置,不过站在可读性的角度来看,已经好很多了. 书写格式: ##格式: 设置颜色开始:\033[显示方式;前景色;背景色m ##说明: 前景 ...
- git的简单使用(windows)
使用参考文档 git简易指南:http://www.bootcss.com/p/git-guide/ git官方文档:https://git-scm.com/book/zh/v1/%E8%B5%B7% ...