zoukankan      html  css  js  c++  java
  • 37-生成 JWT Token

    接到上篇文章

     安装扩展插件nuget package方法安装包

    使用 ctrl+shift+p打开命令面板

    增加这个包,  Microsoft.AspNetCore.Authentication.JwtBearer
     
    增加完后, 保存安装的包

    生成Token

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Authorization;
    using Microsoft.AspNetCore.Authentication;
    using Microsoft.Extensions.Options;
    using System.Security.Claims;
    using Microsoft.AspNetCore.Authentication.JwtBearer;
    using System.IdentityModel.Tokens.Jwt;
    
    namespace JwtAuthSample.Controllers
    {
    
        [Route("api/[controller]")]
        public class AuthorizeController : ControllerBase
        {
            private Models.JwtSettings _jwtSettings{get;set;}
    
            public AuthorizeController(IOptions<Models.JwtSettings> _jwtSettings){
                this._jwtSettings = _jwtSettings.Value;
            }
    
           public IActionResult Token(LoginViewModel loginViewModel){
               if(ModelState.IsValid) {
                  if(loginViewModel.User!="qinzb" && loginViewModel.Password!="123"){
                      return BadRequest();
                  }
    
                  var claims = new Claim[]{
                        new Claim(ClaimTypes.Name,"qinzb"),
                        new Claim(ClaimTypes.Role,"admin")
                   };
                  
                  var key = new Microsoft.IdentityModel.Tokens.SymmetricSecurityKey
                  (System.Text.Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
    
                  var creds = new Microsoft.IdentityModel.Tokens.SigningCredentials
                  (key, Microsoft.IdentityModel.Tokens.SecurityAlgorithms.HmacSha256);
    
                  var token = new System.IdentityModel.Tokens.Jwt.JwtSecurityToken(
                      _jwtSettings.Issure,
                    _jwtSettings.Audience,
                    claims,
                    null,
                    DateTime.Now.AddMinutes(30),
                    creds
                  );
                  return Ok(new {token = new JwtSecurityTokenHandler().WriteToken(token)});
               }
               return BadRequest();
           }
        }
    
    
    }

    我们就可以根据 http://localhost:5000/api/Authorize?User=qinzb&Password=123获取返回的token

     

    根据获取到的token就可以访问之前的网址了,我们也可以去https://jwt.io/去校验我们的toekn

  • 相关阅读:
    xpath解析以及lxml解析库
    python sort()和sorted()的不同
    爬取电影天堂-二级页面抓取
    爬取猫眼电影榜单TOP100榜-以mysql数据库保存
    爬取猫眼电影榜单TOP100榜-以csv文件保存
    爬取猫眼电影榜单TOP100榜-以命令行输出
    爬虫 贪婪匹配以及非贪婪匹配
    爬取百度贴吧
    python 面试
    python 从array保存伪色彩图片 —— 发现的坑
  • 原文地址:https://www.cnblogs.com/qinzb/p/9357515.html
Copyright © 2011-2022 走看看