.net core 基於Jwt實現Token令牌


Startup類ConfigureServices中

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,//validate the server
                ValidateAudience = true,//ensure that the recipient of the token is authorized to receive it 
                ValidateLifetime = true,//check that the token is not expired and that the signing key of the issuer is valid 
                ValidateIssuerSigningKey = true,//verify that the key used to sign the incoming token is part of a list of trusted keys
                ValidIssuer = Configuration["Jwt:Issuer"],//appsettings.json文件中定義的Issuer
                ValidAudience = Configuration["Jwt:Issuer"],//appsettings.json文件中定義的Audience
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Jwt:Key"]))
            };//appsettings.json文件中定義的JWT Key
        });

Configure 啟用中間件

 app.UseAuthentication();//配置授權

appsetting.json中配置

"Jwt": {
    "Key": "veryVerySecretKey",
    "Issuer": "http://localhost:65356"
  }

Api控制器中  根據登錄信息生成token令牌

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
using OnlineClassroom.Common;
using OnlineClassroom.Entity;
using OnlineClassroom.IService;

namespace OnlineClassroom.Api.Controllers
{
  [Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UsersApiController : ControllerBase
    {
        private IConfiguration _config;
        public IUsersService iUsersService = null;

        public UsersApiController(IConfiguration config, IUsersService _iUsersService)
        {
            _config = config;
            iUsersService = _iUsersService;
        }/// <summary>
        /// 登錄
        /// </summary>
        /// <param name="Name">用戶名</param>
        /// <param name="Pwd">密碼</param>
        /// <returns>自定義結果</returns>
        [HttpPost, AllowAnonymous]
        public IActionResult Login(string Name, string Pwd)
        {
            IActionResult response = Unauthorized();
            LoginModel login = new LoginModel();
            login.Username = Name;
            login.Password = Pwd;
            var user = Authenticate(login);
            if (user != null)
            {
                var tokenString = BuildToken(user);
                response = Ok(new {User=user.user, token = tokenString});
            }
            return response;
        }
/// <summary>
        /// 根據用戶信息生成token
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        private string BuildToken(UserModel user)
        {
            //添加Claims信息
            var claims = new[] {
                new Claim(JwtRegisteredClaimNames.Sub, user.Name),
                new Claim(JwtRegisteredClaimNames.Email, user.Password),
                new Claim(JwtRegisteredClaimNames.Birthdate, user.Birthdate.ToString("yyyy-MM-dd")),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString())
            };

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:Key"]));
            var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(_config["Jwt:Issuer"],
              _config["Jwt:Issuer"],
              claims,//添加claims
              expires: DateTime.Now.AddMinutes(30),
              signingCredentials: creds);
            //一個典型的JWT 字符串由三部分組成:

            //header: 頭部,meta信息和算法說明
            //payload: 負荷(Claims), 可在其中放入自定義內容, 比如, 用戶身份等
            //signature: 簽名, 數字簽名, 用來保證前兩者的有效性

            //三者之間由.分隔, 由Base64編碼.根據Bearer 認證規則, 添加在每一次http請求頭的Authorization字段中, 這也是為什么每次這個字段都必須以Bearer jwy - token這樣的格式的原因.
            return new JwtSecurityTokenHandler().WriteToken(token);
        }

        private UserModel Authenticate(LoginModel login)
        {
            UserModel user = null;

            var users = iUsersService.Login(login.Username, login.Password);

            if (users != null)
            {
                user = new UserModel { Name = login.Username, Password = login.Password,user=users };
            }

            return user;
        }

        public class LoginModel
        {
            public string Username { get; set; }
            public string Password { get; set; }
        }

        private class UserModel
        {
            public Users user { get; set; }
            public string Name { get; set; }
            public string Password { get; set; }
            public DateTime Birthdate { get; set; }
        }
    }
}

 


免責聲明!

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



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