zoukankan      html  css  js  c++  java
  • 在Asp.Net Core Web API中使用JWT鉴权(1)创建鉴权中心

    该系列简单介绍了在Asp.Net Core Web API中如何使用JWT创建token进行鉴权。

    1、创建Asp.Net Core Web API项目

    这里使用的环境是VS2019 + .Net Core 3.1。

    2、添加JWT服务

    (1) 使用Nuget安装System.IdentityModel.Tokens.Jwt。
    (2) 实现JWT服务

    public interface IJwtService
    {
        string GetToken(string name);
    }
    
    using Microsoft.Extensions.Configuration;
    using Microsoft.IdentityModel.Tokens;
    using System;
    using System.IdentityModel.Tokens.Jwt;
    using System.Security.Claims;
    using System.Text;
    
    namespace TestWebApi.AuthCenter.Utility
    {
        public class JwtService : IJwtService
        {
            private readonly IConfiguration _configuration;
    
            public JwtService(IConfiguration configuration)
            {
                _configuration = configuration;
            }
    
            public string GetToken(string name)
            {
                /**
                 * Claims(Payload)
                 * Claims包含了一些跟这个token有关的重要信息。JWT标准规定的字段:
                 * 
                 * iss: The issuer of the token, 签发人
                 * sub: The subject of the token, 主题
                 * exp: Expiration Time. 过期时间(Unix时间戳格式)
                 * iat: Issued At. 签发时间(Unix时间戳格式)
                 * jti: JWT ID. 编号
                 * aud: audience. 受众
                 * nbf: Not Before. 生效时间
                 * 
                 * 除了规定的字段外,可以包含其他任何JSON兼容的字段。
                 * */
                var claims = new[]
                {
                    new Claim(ClaimTypes.Name, name),
                    new Claim("NickName", "NetCore"),
                    new Claim("Role", "Administrator")
                };
    
                var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["SecurityKey"]));
                var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
    
                var token = new JwtSecurityToken(
                    issuer: _configuration["issuer"], //签发人
                    audience: _configuration["audience"],
                    claims: claims,
                    expires: DateTime.Now.AddMinutes(20), //20分钟有效期
                    signingCredentials: credentials);
                var tokenStr = new JwtSecurityTokenHandler().WriteToken(token);
                return tokenStr;
            }
        }
    }

    (3) 注入JWT服务

    //注入JWT服务
    services.AddScoped<IJwtService, JwtService>();

    3、添加JWT配置信息(appsettings.json)

    "issuer": "http://localhost:9527",
    "audience": "http://localhost:9527",
    "SecurityKey": "4A9A70D2-B8AD-42E1-B002-553BDEF4E76F"

    其中,SecurityKey为新建的一个GUID。

    4、添加授权控制器
    (1) 使用Nuget安装Newtonsoft.Json
    (2) 控制器类实现

    using Microsoft.AspNetCore.Mvc;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.Logging;
    using Newtonsoft.Json;
    using TestWebApi.AuthCenter.Utility;
    
    namespace TestWebApi.AuthCenter.Controllers
    {
        [Route("api/[controller]")]
        [ApiController]
        public class AuthController : ControllerBase
        {
            //需要注入的服务
            private readonly ILogger<AuthController> _logger;
            private readonly IConfiguration _configuration;
            private readonly IJwtService _jwtService;
    
            public AuthController(IConfiguration configuration,
                ILogger<AuthController> logger,
                IJwtService jwtService)
            {
                _configuration = configuration;
                _logger = logger;
                _jwtService = jwtService;
            }
    
            [Route("Login")]
            [HttpGet]
            public string Login(string username, string password)
            {
                var result = VerifyLogin(username, password);
                var token = result ? _jwtService.GetToken(username) : "";
    
                return JsonConvert.SerializeObject(new
                {
                    result,
                    token
                });
            }
    
            private bool VerifyLogin(string username, string password)
            {
                return "admin".Equals(username) && "123456".Equals(password);
            }
        }
    }

    5、运行

    (1) 运行Web API项目,在浏览器中输入https://localhost:5001/api/auth/Login,正常情况下会输出下面的内容:

    {"result":false,"token":""}

    (2) 在浏览器中输入https://localhost:5001/api/auth/Login?username=admin&password=123456,正常情况下会输出类似下面的内容:

    {"result":true,"token":"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJodHRwOi8vc2NoZW1hcy54bWxzb2FwLm9yZy93cy8yMDA1LzA1L2lkZW50aXR5L2NsYWltcy9uYW1lIjoiYWRtaW4iLCJOaWNrTmFtZSI6Ik5ldENvcmUiLCJSb2xlIjoiQWRtaW5pc3RyYXRvciIsImV4cCI6MTYxMzk1OTM0NSwiaXNzIjoiaHR0cDovL2xvY2FsaG9zdDo5NTI3IiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo5NTI3In0.JdkUR3MV2uC8dQAnqzskFreVFdrHK4WTRrMJSDm7STY"}
  • 相关阅读:
    WIN8开启AHCI的方法终于得到解决。
    Androidx86入门之让你的Androidx86竖屏起来
    Android软件去广告教程
    opencv 3 core组件进阶(2 ROI区域图像叠加&图像混合;分离颜色通道、多通道图像混合;图像对比度,亮度值调整)
    opencv 4 图像处理 (1 线性滤波,非线性滤波)
    opencv 3 core组件进阶(3 离散傅里叶变换;输入输出XML和YAML文件)
    php正则指定字符串内容preg_match函数之说明
    dedecms pagelist标签修改方法
    php后台多用户权限组思路与实现程序代码
    php中获取文件后缀名多种方法
  • 原文地址:https://www.cnblogs.com/xhubobo/p/14428519.html
Copyright © 2011-2022 走看看