在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"}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM