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. JS pc端网页特效

    offset     offset翻译就是偏移量,可以使用他相关的属性可以动态的得到该元素的位置.大小等等     获得元素距离带有定位父元素的位置     获得元素自己的大小(宽度高度)     注 ...

  2. java_List、Set、Conllections工具类

    List接口 java.util.List 接口继承自 Collection 接口 List接口特点: 它是一个元素存取有序的集合.例如,存元素的顺序是11.22.33.那么集合中,元素的存储就是按照 ...

  3. C# ASP JS引用路径不正确导致的错误

    假设JS包放在根目录下的Scripts文件夹下 当前页的路径在另一个文件夹下,那么他引用JS应该:<script src="../Scripts/jquery-1.4.1.min.js ...

  4. java 启动Tomcat报错:The specified JRE installation does not exist

    启动TomCat服务报错: The specified JRE installation does not exist 解决方法: Eclipse:window->perferences-> ...

  5. 2020-06-27:ACID是什么?描述一下?

    福哥答案2020-06-27: 福哥口诀法:事原一隔持(事务属性ACID:原子性.一致性.隔离性.持久性) 用银行数据库来举例子解释一下这四个特性 原子性: 一个事务可能会包含多种操作,比如转账操作包 ...

  6. C#LeetCode刷题之#605-种花问题( Can Place Flowers)

    问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3724 访问. 假设你有一个很长的花坛,一部分地块种植了花,另一部 ...

  7. C++判断是回文串还是镜像串

    #include <iostream> #include <string> #include <cstdio> #include <cctype> #p ...

  8. PC,移动端H5实现实现小球加入购物车效果

    HTML部分: <!DOCTYPE html> <html> <head> <meta http-equiv="content-type" ...

  9. 构造 IPv6 报文

    #!/usr/bin/python from scapy.all import * a=IPv6(nh=58, src='fe80::214:f2ff:fe07:af0', dst='ff02::1' ...

  10. scp 转

    linux之cp/scp命令   名称:cp 使用权限:所有使用者 使用方式: cp [options] source dest cp [options] source... directory 说明 ...