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 ...
随机推荐
- Apollo 启动脚本解析
Apollo 启动脚本解析 sudo service docker start -- 是在ubuntu14.04中打开 在dev_start.sh脚本中会调用restart_map_volume.sh ...
- mysql查询sending data占用大量时间的问题处理
问题描述:某条sql语句在测试环境执行只需要1秒不到,到了生产环境执行需要8秒以上 在phpmyadmin里面执行性能分析,发现sending data占用了差不多90%以上的时间 查询一下“Send ...
- h5 右下角浮动按钮, 纯css实现
2017年11月22日19:00:22 效果: 代码: /** 右下角跳转按钮 跳转到列表 */ #list_note_icon { position: fixed; ...
- PHP程序守护进程化
一般Server程序都是运行在系统后台,这与普通的交互式命令行程序有很大的区别.glibc里有一个函数daemon.调用此函数,就可使当前进程脱离终端变成一个守护进程,具体内容参见man daemon ...
- HDU 1250
简单大数 (要压位,不然会超内存) #include<iostream> #include<cstdio> #include<cstring> #include&l ...
- 【原创】大数据基础之Flume(2)应用之kafka-kudu
应用一:kafka数据同步到kudu 1 准备kafka topic # bin/kafka-topics.sh --zookeeper $zk:2181/kafka -create --topic ...
- 【原创】大数据基础之Marathon(2)marathon-lb
marathon-lb 官方:https://github.com/mesosphere/marathon-lb 一 简介 Marathon load balancer (Marathon-LB) i ...
- 远程连接阿里云的mysql数据库
第一步 由于mysql版本问题 先尝试打开 sudo vim /etc/mysql/my.cnf 如空,再尝试打开 sudo vim /etc/mysql/mysql.conf.d/mysqld.cn ...
- url分发(二级分发)
from django.shortcuts import HttpResponsedef test(request): return HttpResponse('test') from django. ...
- Go语言中的byte和rune区别、对比
Go语言中byte和rune实质上就是uint8和int32类型.byte用来强调数据是raw data,而不是数字:而rune用来表示Unicode的code point.参考规范: uint8 t ...