.net core 基于Jwt实现Token令牌
Startup类ConfigureServices中
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,//validate the server
ValidateAudience = true,//ensure that the recipient of the token is authorized to receive it
ValidateLifetime = true,//check that the token is not expired and that the signing key of the issuer is valid
ValidateIssuerSigningKey = true,//verify that the key used to sign the incoming token is part of a list of trusted keys
ValidIssuer = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Issuer
ValidAudience = Configuration["Jwt:Issuer"],//appsettings.json文件中定义的Audience
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
};//appsettings.json文件中定义的JWT Key
});
Configure 启用中间件
app.UseAuthentication();//配置授权
appsetting.json中配置
"Jwt": {
"Key": "veryVerySecretKey",
"Issuer": "http://localhost:65356"
}
Api控制器中 根据登录信息生成token令牌
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using OnlineClassroom.Common;
using OnlineClassroom.Entity;
using OnlineClassroom.IService; namespace OnlineClassroom.Api.Controllers
{
[Authorize]
[Route("api/[controller]/[action]")]
[ApiController]
public class UsersApiController : ControllerBase
{
private IConfiguration _config;
public IUsersService iUsersService = null; public UsersApiController(IConfiguration config, IUsersService _iUsersService)
{
_config = config;
iUsersService = _iUsersService;
}/// <summary>
/// 登录
/// </summary>
/// <param name="Name">用户名</param>
/// <param name="Pwd">密码</param>
/// <returns>自定义结果</returns>
[HttpPost, AllowAnonymous]
public IActionResult Login(string Name, string Pwd)
{
IActionResult response = Unauthorized();
LoginModel login = new LoginModel();
login.Username = Name;
login.Password = Pwd;
var user = Authenticate(login);
if (user != null)
{
var tokenString = BuildToken(user);
response = Ok(new {User=user.user, token = tokenString});
}
return response;
}
/// <summary>
/// 根据用户信息生成token
/// </summary>
/// <param name="user"></param>
/// <returns></returns>
private string BuildToken(UserModel user)
{
//添加Claims信息
var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.Name),
new Claim(JwtRegisteredClaimNames.Email, user.Password),
new Claim(JwtRegisteredClaimNames.Birthdate, user.Birthdate.ToString("yyyy-MM-dd")),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
}; var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256); var token = new JwtSecurityToken(_config["Jwt:Issuer"],
_config["Jwt:Issuer"],
claims,//添加claims
expires: DateTime.Now.AddMinutes(),
signingCredentials: creds);
//一个典型的JWT 字符串由三部分组成: //header: 头部,meta信息和算法说明
//payload: 负荷(Claims), 可在其中放入自定义内容, 比如, 用户身份等
//signature: 签名, 数字签名, 用来保证前两者的有效性 //三者之间由.分隔, 由Base64编码.根据Bearer 认证规则, 添加在每一次http请求头的Authorization字段中, 这也是为什么每次这个字段都必须以Bearer jwy - token这样的格式的原因.
return new JwtSecurityTokenHandler().WriteToken(token);
} private UserModel Authenticate(LoginModel login)
{
UserModel user = null; var users = iUsersService.Login(login.Username, login.Password); if (users != null)
{
user = new UserModel { Name = login.Username, Password = login.Password,user=users };
} return user;
} public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
} private class UserModel
{
public Users user { get; set; }
public string Name { get; set; }
public string Password { get; set; }
public DateTime Birthdate { get; set; }
}
}
}
.net core 基于Jwt实现Token令牌的更多相关文章
- 一、Core授权-2 之.net core 基于Jwt实现Token令牌
一.Startup类配置 ConfigureServices中 //添加jwt验证: services.AddAuthentication(JwtBearerDefaults.Authenticati ...
- ASP.NET Core 基于JWT的认证(一)
ASP.NET Core 基于JWT的认证(一) Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计 ...
- ASP.NET Core 基于JWT的认证(二)
ASP.NET Core 基于JWT的认证(二) 上一节我们对 Jwt 的一些基础知识进行了一个简单的介绍,这一节我们将详细的讲解,本次我们将详细的介绍一下 Jwt在 .Net Core 上的实际运用 ...
- Asp.Net Core基于JWT认证的数据接口网关Demo
近日,应一位朋友的邀请写了个Asp.Net Core基于JWT认证的数据接口网关Demo.朋友自己开了个公司,接到的一个升级项目,客户要求用Aps.Net Core做数据网关服务且基于JWT认证实现对 ...
- ASP.NET Web API 2系列(四):基于JWT的token身份认证方案
1.引言 通过前边的系列教程,我们可以掌握WebAPI的初步运用,但是此时的API接口任何人都可以访问,这显然不是我们想要的,这时就需要控制对它的访问,也就是WebAPI的权限验证.验证方式非常多,本 ...
- ASP.NET WebApi 基于JWT实现Token签名认证
一.前言 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebServi ...
- 基于JWT的Token开发案例
代码地址如下:http://www.demodashi.com/demo/12531.html 0.准备工作 0-1运行环境 jdk1.8 maven 一个能支持以上两者的代码编辑器,作者使用的是ID ...
- token 与 基于JWT的Token认证
支持跨域访问,无状态认证 token特点 支持跨域访问: Cookie是不允许垮域访问的,这一点对Token机制是不存在的,前提是传输的用户认证信息通过HTTP头传输 无状态(也称:服务端可扩展行): ...
- 基于JWT的Token认证机制及安全问题
[干货分享]基于JWT的Token认证机制及安全问题 https://bbs.huaweicloud.com/blogs/06607ea7b53211e7b8317ca23e93a891
随机推荐
- 【校招面试 之 C/C++】第1题 为什么优先使用构造函数的初始化列表
1.首先看一个例子: #include<iostream> using namespace std; class Test1 { public: Test1() // 无参构造函数 { c ...
- 解读超轻量级DI容器-Guice与Spring框架的区别【转载】
依赖注入,DI(Dependency Injection),它的作用自然不必多说,提及DI容器,例如spring,picoContainer,EJB容器等等,近日,google诞生了更轻巧的DI容器… ...
- Excel单元格内容拆分、合并
例:如何将EXCEL单元格A1中的“1-2-1”,在B1.C1.D1单元格中分别显示”1“.”2“.”1“.方法一: 在B1中输入“=mid(A1,1,1)”在C1中输入“=mid(AI,3,1)”在 ...
- [leetcode]349. Intersection of Two Arrays数组交集
Given two arrays, write a function to compute their intersection. Example 1: Input: nums1 = [1,2,2,1 ...
- php session阻塞页面分析及优化 (session_write_close session_commit使用)
转: http://www.tuicool.com/articles/bqeeey 首先看下下面代码, session1.php 文件 <?php ini_set('session.save_p ...
- BZOJ3170: [Tjoi2013]松鼠聚会 - 暴力
描述 有N个小松鼠,它们的家用一个点x,y表示,两个点的距离定义为:点(x,y)和它周围的8个点即上下左右四个点和对角的四个点,距离为1.现在N个松鼠要走到一个松鼠家去,求走过的最短距离. 题解 简直 ...
- canvas标签的基本用法
1.canvas和其他标签一样使用,但是IE8以下是不支持的,可以在canvas里面加一个span用来提示,例如: <canvas> <span>IE8不支持canvas< ...
- 【JAVA】通过HttpURLConnection 上传和下载文件(二)
HttpURLConnection文件上传 HttpURLConnection采用模拟浏览器上传的数据格式,上传给服务器 上传代码如下: package com.util; import java.i ...
- 《完全版线段树》——notonlysuccess
转载自:NotOnlySuccess的博客 [完全版]线段树 很早前写的那篇线段树专辑至今一直是本博客阅读点击量最大的一片文章,当时觉得挺自豪的,还去pku打广告,但是现在我自己都不太好意思去看那篇文 ...
- VBA替换函数
Sub test() On Error Resume Next Dim arr1, arr2, i, j arr1 = Range("T1:EI3") arr2 = Range(& ...