1.创建项目

使用visual studio创建一个名为JwtDemo的空项目,创建后如图

2.添加依赖项

  • 在nuget包管理器中搜索 Microsoft.AspNetCore.Authentication.JwtBearer、System.IdentityModel.Tokens.Jwt
  • 在nuget包管理控制台安装
Install-Package Microsoft.AspNetCore.Authentication.JwtBearer -Version 3.1.7
Install-Package System.IdentityModel.Tokens.Jwt -Version 6.7.1

3.编写代码

创建一个接口(IJwtAuthenticationHandler),声明一个用于创建token的方法(Authenticate)

namespace JwtDemo
{
public interface IJwtAuthenticationHandler
{
string Authenticate(string username, string password);
}
}

创建一个类,继承接口(IJwtAuthenticationHandler),并实现方法,这里简单起见就将用户硬编码在代码中

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text; using Microsoft.IdentityModel.Tokens; namespace JwtDemo
{
public class JwtAuthenticationHandler: IJwtAuthenticationHandler
{
private readonly IDictionary<string, string> users = new Dictionary<string, string>()
{
{"user1","password1"},
{"user2","password2"},
}; private readonly string _token; //声明一个加密的密钥,由外部传入 public JwtAuthenticationHandler(string token)
{
_token = token;
} public string Authenticate(string username, string password)
{
//如果用户名密码错误则返回null
if (!users.Any(t => t.Key == username && t.Value == password))
{
return null;
}
var tokenKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_token));
var tokenHandler = new JwtSecurityTokenHandler();
var tokenDescriptor = new SecurityTokenDescriptor()
{
SigningCredentials = new SigningCredentials(tokenKey, SecurityAlgorithms.HmacSha256),
Expires = DateTime.Now.AddMinutes(10),
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name,username),
})
}; var token = tokenHandler.CreateJwtSecurityToken(tokenDescriptor);
return tokenHandler.WriteToken(token);
}
}
}

修改Startup类

using System.Text;

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens; namespace JwtDemo
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
string tokenSecretKey = "this is a test token secret key"; //加密的密钥
services.AddAuthentication(config =>
{
//认证方案设置为Jwt
config.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
config.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(config=>
{
config.RequireHttpsMetadata = false;
config.SaveToken = true; //保存token
config.TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false,//不验证签发人
ValidateAudience = false, //不验证听众
ValidateIssuerSigningKey = true, //验证签发者密钥
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(tokenSecretKey)) //签发者密钥
};
});
//将生成token的类注册为单例
services.AddSingleton<IJwtAuthenticationHandler>(new JwtAuthenticationHandler(tokenSecretKey));
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
} app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

创建一个控制器(UserController),包含一个认证方法和一个获取用户列表(加了权限认证)的方法

using System.Collections.Generic;

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc; namespace JwtDemo.Controllers
{
[ApiController]
public class UserController: Controller
{
private readonly IJwtAuthenticationHandler _jwtAuthenticationHandler;
//构造函数注入生成token的类
public UserController(IJwtAuthenticationHandler jwtAuthenticationHandler)
{
_jwtAuthenticationHandler = jwtAuthenticationHandler;
} [AllowAnonymous] //表示可以匿名访问
[Route("user/authenticate")]
[HttpPost]
public IActionResult Authenticate([FromBody] LoginViewModel loginViewModel)
{
var token = _jwtAuthenticationHandler.Authenticate(loginViewModel.UserName,loginViewModel.Password);
if (token == null)
{
return Unauthorized();
}
return Ok(token);
} [Authorize] //表示需要认证授权访问
[Route("user/list")]
[HttpGet]
public List<object> List()
{
return new List<object>()
{
"user1","user2","user3","user..."
};
}
}
}

LoginViewModel类

namespace JwtDemo.Controllers
{
public class LoginViewModel
{
public string UserName { get; set; }
public string Password { get; set; }
}
}

完成后的项目结构

4.测试接口

运行项目,我们直接请求用户列表的接口,返回401,表示未授权

我们请求认证接口进行认证,输入正确的用户名和密码,会返回一个token

使用上面的token再次请求用户列表接口,将Header中加入Authorization:Bearer token,可以正常返回数据,表示已经成功

.net core3.1中实现简单的jwt认证的更多相关文章

  1. 记录一下在SpringBoot中实现简单的登录认证

    代码参考博客: https://blog.csdn.net/weixin_37891479/article/details/79527641 在做学校的课设的时候,发现了安全的问题,就不怀好意的用户有 ...

  2. drf JWT认证模块与自定制

    JWT模块 在djangorestframework中,有一款扩展模块可用于做JWT认证,使用如下命令进行安装: pip install djangorestframework-jwt 现在,就让我们 ...

  3. NetCore+Dapper WebApi架构搭建(六):添加JWT认证

    WebApi必须保证安全,现在来添加JWT认证 1.打开appsettings.json添加JWT认证的配置信息 2.在项目根目录下新建一个Models文件夹,添加一个JwtSettings.cs的实 ...

  4. drf认证组件(介绍)、权限组件(介绍)、jwt认证、签发、jwt框架使用

    目录 一.注册接口 urls.py views.py serializers.py 二.登录接口 三.用户中心接口(权限校验) urls.py views.py serializers.py 四.图书 ...

  5. 如何简单的在 ASP.NET Core 中集成 JWT 认证?

    前情提要:ASP.NET Core 使用 JWT 搭建分布式无状态身份验证系统 文章超长预警(1万字以上),不想看全部实现过程的同学可以直接跳转到末尾查看成果或者一键安装相关的 nuget 包 自上一 ...

  6. Jwt在Java项目中的简单实际应用

    1.什么是jwt 双方之间传递安全信息的简洁的.URL安全的表述性声明规范.JWT作为一个开放的标准(RFC 7519),定义了一种简洁的,自包含的方法用于通信双方之间以Json对象的形式安全的传递信 ...

  7. Laravel 中使用 JWT 认证的 Restful API

    Laravel 中使用 JWT 认证的 Restful API 5天前/  678 /  3 / 更新于 3天前     在此文章中,我们将学习如何使用 JWT 身份验证在 Laravel 中构建 r ...

  8. drf框架中jwt认证,以及自定义jwt认证

    0909自我总结 drf框架中jwt 一.模块的安装 官方:http://getblimp.github.io/django-rest-framework-jwt/ 他是个第三方的开源项目 安装:pi ...

  9. ASP.Net Core 3.0 中使用JWT认证

    JWT认证简单介绍     关于Jwt的介绍网上很多,此处不在赘述,我们主要看看jwt的结构.     JWT主要由三部分组成,如下: HEADER.PAYLOAD.SIGNATURE HEADER包 ...

随机推荐

  1. 畅购商城(八):微服务网关和JWT令牌

    好好学习,天天向上 本文已收录至我的Github仓库DayDayUP:github.com/RobodLee/DayDayUP,欢迎Star,更多文章请前往:目录导航 畅购商城(一):环境搭建 畅购商 ...

  2. Linxu系统安装PHP详细教程

    安装centos源 yum install epel-release –y 下载php安装压缩包 wget https://www.php.net/distributions/php-7.3.15.t ...

  3. Arm pwn学习

    本文首发于“合天智汇”公众号 作者:s0xzOrln 声明:笔者初衷用于分享与普及网络知识,若读者因此作出任何危害网络安全行为后果自负,与合天智汇及原作者无关! 刚刚开始学习ARM pwn,下面如有错 ...

  4. 使用docker快速搭建hive环境

    记录一下使用docker快速搭建部署hive环境 目录 写在前面 步骤 安装docker 安装docker 安装docker-compose 配置docker国内镜像源(可选) 安装git & ...

  5. C - 一个C语言猜字游戏

    下面是一个简陋的猜字游戏,玩了一会儿,发现自己打不过自己写的游戏,除非赢了就跑,最高分没有过1000. 说明:srand(time(NULL))和rand(),srand,time和rand都是函数, ...

  6. Qt之先用了再说系列-多线程方式1

    Qt 多线程的用法还是比较简单的,也比较好用,接下来我们就分析分析如何使用. 说起Qt 线程的使用方式,一般有2种使用方式,具体哪种比较好看自己心情了,现在有官方的推荐用法,用不用还是看你心情的 好, ...

  7. C#LeetCode刷题之#840-矩阵中的幻方(Magic Squares In Grid)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3752 访问. 3 x 3 的幻方是一个填充有从 1 到 9 的不 ...

  8. Vue 离开页面时的校验-mixin-beforeRouteLeave

    一定要看下函数前的注释, 需要在使用的页面定义[needCheckFlag]data属性 一定要看下函数前的注释, 需要在使用的页面定义[needCheckFlag]data属性 一定要看下函数前的注 ...

  9. asp.netcore3.1 将服务器配置为需要证书

    运行 asp.netcore 3.1应用程序时,弹出证书选择框. 将服务器配置为需要证书(Kestrel),在Program.cs中,按如下所示配置 Kestrel: public static vo ...

  10. 一文看懂 Netty 架构设计

    本文重点分析 Netty 的逻辑架构及关键的架构质量属性,希望有助于大家从 Netty 的架构设计中汲取营养,设计出高性能.高可靠性和可扩展的程序. Netty 的三层架构设计 Netty 采用了典型 ...