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

  • 相关阅读:
    LAB02:Selenium的安装与使用
    HW03:Exercise Section 2.3
    LAB01:安装 Junit(4.12), Hamcrest(1.3) 以及 Eclemma并完成一次三角形问题的测试
    HW02:根据程序回答问题
    HW01:程序中的错误
    Postman 接口测试
    Python3.7、Eclipse 4.5、 Java 8、 PyDev 5.2.0、 selenium-3.14.0环境搭建
    Java + selenium 实现web自动化简单示例
    java Junit自动化测试框架环境搭建
    java TestNg自动化测试框架环境搭建
  • 原文地址:https://www.cnblogs.com/qinzb/p/9357515.html
Copyright © 2011-2022 走看看