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 ...
随机推荐
- Node.js的模块系统
编写稍大一点的程序时一般都会将代码模块化.Node.js提供了一个简单的模块系统.模块既可能是一个文件,也可能是包含一个或多个文件的目录. 模块的创建 如果模块是个文件,一般将代码合理拆分到不同的J ...
- SHA1算法原理【转】
转自:https://www.cnblogs.com/scu-cjx/p/6878853.html 一.SHA1与MD5差异 SHA1对任意长度明文的预处理和MD5的过程是一样的,即预处理完后的明文长 ...
- 不允许lseek文件 | nonseekable_open()【转】
转自:https://blog.csdn.net/gongmin856/article/details/8273545 使用数据区时,可以使用 lseek 来往上往下地定位数据.但像串口或键盘一类设备 ...
- $Django 聚合函数、分组查询、F,Q查询、orm字段以及参数
一.聚合函数 from django.db.models import Avg,Sum,Max,Min,Count,F,Q #导入 # .查询图书的总价,平均价,最大价,最小价 ...
- <转载>关系规范化之求最小函数依赖集(最小覆盖)
原文链接http://blog.csdn.net/icurious/article/details/51240114 最小函数依赖集 一.等价和覆盖 定义:关系模式R<U,F>上的两个依赖 ...
- mysql优化——show processlist命令详解
SHOW PROCESSLIST显示哪些线程正在运行 不在mysql提示符下使用时用mysql -uroot -e 'Show processlist' 或者 mysqladmin pro ...
- 【进阶4-2期】Object.assign 原理及其实现 (转)
这是我在公众号(高级前端进阶)看到的文章,现在做笔记 https://github.com/yygmind/blog/issues/26 浅拷贝 Object.assign 上篇文章介绍了其定义和使 ...
- js——字符串处理
字符串不能修改,所以修改后的结果都是以一个新的字符串返回,原串不改变 1. 创建字符串和typeof - 空字符串 var str = ""; - " ...
- ADO.NET连接字符串大全---各种数据库的连接字符串
ADO.NET连接字符串大全 ADO.NET连接字符串 名称 ADO.NET连接字符串 说明 ADO.NET连接字符串:SQL Server,SQL Server 2005,ACCESS,Oracle ...
- 3、SourceTree通过PUTTY连接GitLab
一.生成公钥和私钥 使用命令行生成(两种生成方式选择一种即可) 1.安装SourceTree打开SourceTree,点击“命令行模式”. 2.输入如下命令生成key“example@example. ...