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

  • 相关阅读:
    LeetCode #1021. Remove Outermost Parentheses 删除最外层的括号
    使用Maven运行测试提示Module sdk 1.5的解决方法
    Map.Entry使用详解
    c++基础(一)
    Python_正则表达式
    使用PIL生成验证码
    OpenCV_图像平滑
    OpenCV—图像阈值
    OpenCV形状变换
    使用OpenCV读写图片
  • 原文地址:https://www.cnblogs.com/qinzb/p/9357515.html
Copyright © 2011-2022 走看看