因为害怕token泄露出现问题,所以从未在项目中使用jwt。但这玩意现在真的很火,趁有空还是研究了一下。

在aspnetcore中实现jwt很简单,感觉微软把很多工作都做了,虽然开发效率上去了,但是使得c#的程序员变得很傻,很多事情都是知其然而不知其所以然,只能绑死在微软这条大船上越行越远,唉~~

jwt一般在webapi的项目使用比较多,但我下面的代码都是在MVC环境上测试的,用法上应该没什么区别。

一、添加和配置JWT

1、引入nuget包

VS中点击 工具 > 管理解决方案 NuGet 程序包,搜索 IdentityModel,安装到项目

2、添加JWT配置项

打开  appsettings.json ,添加节点

"Authentication": {
"JwtBearer": {
"IsEnabled": "true",
"SecurityKey": "JWTStudyWebsite_DI20DXU3",
"Issuer": "JWTStudy",
"Audience": "JWTStudyWebsite"
}
}

3、新建  JWTConfiguration.cs 文件,内容如下:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Text; namespace JWTStudent.Website.Extensions
{
public static class JwtConfiguration
{
public static void AddJwtConfiguration(this IServiceCollection services, IConfiguration configuration)
{
if (bool.Parse(configuration["Authentication:JwtBearer:IsEnabled"]))
{
services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = "JwtBearer";
options.DefaultChallengeScheme = "JwtBearer";
}).AddJwtBearer("JwtBearer", options =>
{
options.Audience = configuration["Authentication:JwtBearer:Audience"]; options.TokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.ASCII.GetBytes(configuration["Authentication:JwtBearer:SecurityKey"])), // Validate the JWT Issuer (iss) claim
ValidateIssuer = true,
ValidIssuer = configuration["Authentication:JwtBearer:Issuer"], // Validate the JWT Audience (aud) claim
ValidateAudience = true,
ValidAudience = configuration["Authentication:JwtBearer:Audience"], // Validate the token expiry
ValidateLifetime = true, // If you want to allow a certain amount of clock drift, set that here
ClockSkew = TimeSpan.Zero
};
});
}
}
}
}

4、在StartUp.cs的ConfigurationServices方法内,添加如下代码:

services.AddJwtConfiguration(Configuration);

二、创建AccessTokenController,用于申请和发放JWT

public IActionResult Post([FromBody]LoginModel model)
{
var user = TempData.Users.FirstOrDefault(m => m.Account == model.Account && m.Pw == model.Pw); if (user != null)
{
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Account),
new Claim(ClaimTypes.Role, user.Role)
}; var key = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes(_configuration["Authentication:JwtBearer:SecurityKey"]));
var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(
_configuration["Authentication:JwtBearer:Issuer"],
_configuration["Authentication:JwtBearer:Audience"],
claims,
expires: DateTime.Now.AddMinutes(),
signingCredentials: credentials
); return Ok(new AccessTokenResult {Token = new JwtSecurityTokenHandler().WriteToken(token), Code = });
} return Ok(new AccessTokenResult {Code = , Token = ""});
}

LoginModel是自定义的登录模型,很简单,仅包含用户名和密码两个字段。AccessTokenResult是自定义的返回结果,int类型的Code,登录成功则返回200,失败为0,Token是生成的JWT

三、测试

1、创建TestController,并为其添加  Authorization  描述

2、运行程序,打开Postman,访问 http://localhost:5000/test

不出所料,访问被拒绝,提示没有授权。

3、获取JWT

访问 http://localhost:5000/api/accesstoken

4、使用Token重新访问受限的Action

拷贝token的值,重新请求 http://localhost:5000/test,在Headers上添加一项,KEY 为 Authorization,VALUE 为 Bear+空格+token值

【aspnetcore】配置使用jwt验证的更多相关文章

  1. Jwt验证登录

    练习模板:https://gitee.com/zh1446802857/swagger-multi-version-api.git Jwt在我的 认知里,是一套门锁.别人(用户)需要用到你的接口 的时 ...

  2. 踩坑之路---JWT验证

    使用JWT验证客户的携带的token 客户端在请求接口时,需要在request的head中携带一个token令牌 服务器拿到这个token解析获取用户资源,这里的资源是非重要的用户信息 目前我的理解, ...

  3. webapi中使用token验证(JWT验证)

    本文介绍如何在webapi中使用JWT验证 准备 安装JWT安装包 System.IdentityModel.Tokens.Jwt 你的前端api登录请求的方法,参考 axios.get(" ...

  4. Nginx实现JWT验证-基于OpenResty实现

    介绍 权限认证是接口开发中不可避免的问题,权限认证包括两个方面 接口需要知道调用的用户是谁 接口需要知道该用户是否有权限调用 第1个问题偏向于架构,第2个问题更偏向于业务,因此考虑在架构层解决第1个问 ...

  5. nginx配置ssl双向验证 nginx https ssl证书配置

    1.安装nginx 参考<nginx安装>:http://www.ttlsa.com/nginx/nginx-install-on-linux/ 如果你想在单IP/服务器上配置多个http ...

  6. nginx配置https双向验证(ca机构证书+自签证书)

    nginx配置https双向验证 服务端验证(ca机构证书) 客户端验证(服务器自签证书) 本文用的阿里云签发的免费证书实验,下载nginx安装ssl,文件夹有两个文件 这两个文件用于做服务器http ...

  7. 如何为ASP.NET Core的强类型配置对象添加验证

    原文: Adding validation to strongly typed configuration objects in ASP.NET Core 作者: Andrew Lock 译文: La ...

  8. centos6.5中部署Zeppelin并配置账号密码验证

    centos6.5中部署Zeppelin并配置账号密码验证1.安装JavaZeppelin支持的操作系统如下图所示.在安装Zeppelin之前,你需要在部署的服务器上安装Oracle JDK 1.7或 ...

  9. golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息

    golang学习笔记10 beego api 用jwt验证auth2 token 获取解码信息 Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放 ...

随机推荐

  1. 对存在JavaScript隐式类型转换的四种情况的总结

    一般存在四种情况,JavaScript会对变量的数据类型进行转换. 目录 * if中的条件会被自动转为Boolean类型 * 会被转为false的数据 * 会被转为true的数据 * 参与+运算都会被 ...

  2. 洛谷【P1104】生日(选择排序版)

    题目传送门:https://www.luogu.org/problemnew/show/P1104 题目很简单,不过我是来讲选择排序的. 选择排序\((Selection sort)\)是一种简单直观 ...

  3. bzoj 2125 最短路——仙人掌两点间最短路

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=2125 因为看了TJ又抄了标程,现在感觉还是轻飘飘的……必须再做一遍. 两点间的情况: 1.直 ...

  4. 使用ceph命令提示handle_connect_reply connect got BADAUTHORIZER

    输入命令提示如下错误: [root@node1 ~]# rados -p testpool ls 2017-10-21 06:13:25.743045 7f8f89b6d700 0 -- 192.16 ...

  5. PHP7三元运算符 ?? 和 ?: 的区别

    1. (expr1) ?? (expr2)  是 PHP7才有的功能,等同于: isset(expr1) ? expr1 : expr2 ; 2.(expr1) ?: (expr2) 是PHP5.3才 ...

  6. Project Online JS 添加Ribbon按钮

    var Projects = Projects || {}; (function () { Projects.ribbonButtonClick = function (name) { var pro ...

  7. 12.Redis Select 命令 - 切换到指定的数据库

    转自:http://www.runoob.com/redis/redis-tutorial.html Redis Select 命令用于切换到指定的数据库,数据库索引号 index 用数字值指定,以 ...

  8. redis持久化  发布消息与订阅

    vi /usr/local/redis/etc/redis.conf  快照方式:     save 900 1     save 300 10     save 60 10000 aof方式: ap ...

  9. Antiprime数-数论

    题目描述 Description 如果一个自然数n满足:所有小于它的自然数的约数个数都小于n的约数个数,则称n是一个Antiprime数.譬如:1.2.4.5.12.24都是Antiprime数.   ...

  10. 9、perldoc文档阅读器

    转载:http://www.cnblogs.com/nkwy2012/p/6016320.html 一般来说,将文档的名称作为参数传递给perldoc命令,即可查阅该文档.比如下面,给定文档名称per ...