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令牌的更多相关文章

  1. 一、Core授权-2 之.net core 基于Jwt实现Token令牌

    一.Startup类配置 ConfigureServices中 //添加jwt验证: services.AddAuthentication(JwtBearerDefaults.Authenticati ...

  2. ASP.NET Core 基于JWT的认证(一)

    ASP.NET Core 基于JWT的认证(一) Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).该token被设计 ...

  3. ASP.NET Core 基于JWT的认证(二)

    ASP.NET Core 基于JWT的认证(二) 上一节我们对 Jwt 的一些基础知识进行了一个简单的介绍,这一节我们将详细的讲解,本次我们将详细的介绍一下 Jwt在 .Net Core 上的实际运用 ...

  4. Asp.Net Core基于JWT认证的数据接口网关Demo

    近日,应一位朋友的邀请写了个Asp.Net Core基于JWT认证的数据接口网关Demo.朋友自己开了个公司,接到的一个升级项目,客户要求用Aps.Net Core做数据网关服务且基于JWT认证实现对 ...

  5. ASP.NET Web API 2系列(四):基于JWT的token身份认证方案

    1.引言 通过前边的系列教程,我们可以掌握WebAPI的初步运用,但是此时的API接口任何人都可以访问,这显然不是我们想要的,这时就需要控制对它的访问,也就是WebAPI的权限验证.验证方式非常多,本 ...

  6. ASP.NET WebApi 基于JWT实现Token签名认证

    一.前言 明人不说暗话,跟着阿笨一起玩WebApi!开发提供数据的WebApi服务,最重要的是数据的安全性.那么对于我们来说,如何确保数据的安全将会是需要思考的问题.在ASP.NET WebServi ...

  7. 基于JWT的Token开发案例

    代码地址如下:http://www.demodashi.com/demo/12531.html 0.准备工作 0-1运行环境 jdk1.8 maven 一个能支持以上两者的代码编辑器,作者使用的是ID ...

  8. token 与 基于JWT的Token认证

    支持跨域访问,无状态认证 token特点 支持跨域访问: Cookie是不允许垮域访问的,这一点对Token机制是不存在的,前提是传输的用户认证信息通过HTTP头传输 无状态(也称:服务端可扩展行): ...

  9. 基于JWT的Token认证机制及安全问题

    [干货分享]基于JWT的Token认证机制及安全问题 https://bbs.huaweicloud.com/blogs/06607ea7b53211e7b8317ca23e93a891

随机推荐

  1. ECMAScript5新特性之获取对象特有的属性

    'use strict'; // 父类 function Fruit(){ } Fruit.prototype.name = '水果'; // 子类 function Apple(desc){ thi ...

  2. python之面向对象之反射运用

    先看下hasattr和getattr在反射中的用法 import sys class apache(object): def __init__(self,tcp): self.tcp = tcp de ...

  3. Mac 终端便利工具: 管理工具-Homebrew 和提示工具oh my zsh

    命令行提示工具 第一步: Homebrew - 安装与使用 https://blog.csdn.net/sir_coding/article/details/77509602 Homebrew安装问题 ...

  4. 判断浏览器是ie9座特殊处理

    function ie(){ var agent = navigator.userAgent.toLowerCase();//判断浏览器版本 return (!!window.ActiveXObjec ...

  5. macos安装postman

    安装命令 brew cask install postman brew 是从下载源码解压然后./configure && make install,同时会包含相关依存库.并自动配置 好 ...

  6. TPM、read counts、RPKM/FPKM你选对了吗?

    TPM.read counts.RPKM/FPKM你选对了吗? 已有 3940 次阅读 2017-12-15 15:04 |个人分类:RNA-seq|系统分类:科普集锦|关键词:RNA-seq| RN ...

  7. 洛谷 P2986 [USACO10MAR]伟大的奶牛聚集(树形动规)

    题目描述 Bessie is planning the annual Great Cow Gathering for cows all across the country and, of cours ...

  8. 品味性能之道<二>:性能工程师可以具备的专业素养

          性能工程师可以具备的专业素养 程序语言原理,包括:C.C++.java及jvm.ASP,因为建站大部分外围应用和中间件都是JAVA编写,大部分的电商平台采用的ASP编写,底层核心系统是C/ ...

  9. jsp札记

    日期格式化 <s:date name="creaetime" format="yyyy-MM-dd HH:mm:ss" /> <base hr ...

  10. hive 报错 java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.metastore.HiveMetaStoreClient

    Exception in thread "main" java.lang.RuntimeException: java.lang.RuntimeException: Unable ...