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. JavaScript小游戏实例:简单的键盘练习

    键盘是一种常用的输入设备,灵活熟练地使用键盘进行输入是计算机用户需掌握的一门基本功.下面我们编写一个简单的键盘练习游戏. 1.刺破气泡交互式小动画 在编写简单的键盘练习游戏之前,先设计一个简单地刺破气 ...

  2. [机器学习] keras:MNIST手写数字体识别(DeepLearning 的 HelloWord程序)

    深度学习界的Hello Word程序:MNIST手写数字体识别 learn from(仍然是李宏毅老师<机器学习>课程):http://speech.ee.ntu.edu.tw/~tlka ...

  3. 动态路由 - EIGRP

    EIGRP 特性 EIGRP(增强内部网关路由协议)是思科的私有协议,属于距离矢量路由协议,但又具有链路状态的特性.并且支持 VLSM(可变长子网和无类路由协议).但在本质上说还是传送路由条目. 具有 ...

  4. 2020-05-21:es底层读写原理?倒排索引原理?

    福哥答案2020-05-21: es不熟悉,答案仅供参考:es写数据过程1.客户端选择一个node发送请求过去,这个node就是coordinating node(协调节点)2.coordinatin ...

  5. C#LeetCode刷题之#409-最长回文串(Longest Palindrome)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3788 访问. 给定一个包含大写字母和小写字母的字符串,找到通过这 ...

  6. go微服务系列(四) - gRPC入门

    1. 前言 2. gRPC与Protobuf简介 3. 安装 4. 中间文件演示 4.1 编写中间文件 4.2 运行protoc命令编译成go中间文件 5. 创建gRPC服务端 5.1 新建Produ ...

  7. SQL Server 异常代码处理

    SQL Server使用TRY...CATCH 结构实现TSQL语句的错误处理,TRY命令负责监控语句执行的情况,如果有TSQL语句发生异常,并且严重级别(Severity Level)大于10,并且 ...

  8. Alink漫谈(十八) :源码解析 之 多列字符串编码MultiStringIndexer

    Alink漫谈(十八) :源码解析 之 多列字符串编码MultiStringIndexer 目录 Alink漫谈(十八) :源码解析 之 多列字符串编码MultiStringIndexer 0x00 ...

  9. 企业微信人员日程推送接口(python版)

    企业在使用企业微信中,有时想批量推送员工日程信息.这里写了个接口工具分享给大家,供交流学习. 主入口程序: # -*- coding: utf-8 -*-import time as time imp ...

  10. 汇编in和out实例解析

    直接看例子: IN AL,21H 从21H端口读取一字节数据到AL IN AX,21H 从端口地址21H读取1字节数据到AL,从端口地址22H读取1字节到AH MOV DX,379HIN AL,DX ...