12-4.ASP.NET Core Web API 入門教學 - JWT身分驗證

ASP.NET Core Web API 入門教學

影片講解


這篇來教一個常見的Token認證JWT要如何在.NET Core這邊實作。

一些需要用到的內容我們先放在appsettings.json

{
  "JWT": {
    "KEY": "ASDZXASDHAUISDHASDOHAHSDUAHDS",
    "Issuer": "todo.com",
    "Audience": "my"
  }
}

首先我們做一支新的JWTLogin的API,此API可以產生出JWT Token

LoginController.cs

[HttpPost("jwtLogin")]
public string jwtLogin(LoginPost value)
{
    var user = (from a in _todoContext.Employees
                where a.Account == value.Account
                && a.Password == value.Password
                select a).SingleOrDefault();

    if (user == null)
    {
        return "帳號密碼錯誤";
    }
    else
    {
//設定使用者資訊
        var claims = new List<Claim>
                {
                    new Claim(JwtRegisteredClaimNames.Email, user.Account),
                    new Claim("FullName", user.Name),
                    new Claim(JwtRegisteredClaimNames.NameId, user.EmployeeId.ToString())
                };

        var role = from a in _todoContext.Roles
                   where a.EmployeeId == user.EmployeeId
                   select a;
//設定Role
        foreach (var temp in role)
        {
            claims.Add(new Claim(ClaimTypes.Role, temp.Name));
        }

//取出appsettings.json裡的KEY處理
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["JWT:KEY"]));

//設定jwt相關資訊
        var jwt = new JwtSecurityToken
        (
            issuer: _configuration["JWT:Issuer"],
            audience: _configuration["JWT:Audience"],
            claims: claims,
            expires: DateTime.Now.AddMinutes(30),
            signingCredentials: new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256)
        );

//產生JWT Token
        var token = new JwtSecurityTokenHandler().WriteToken(jwt);

//回傳JWT Token給認證通過的使用者
        return token;
    }
}

之後我們可以先試一試這支api

如圖,可以得到一串JWT

我們可以將這串貼到JWT.IO看一下內容

如圖,PAYLOAD:DATA的部分可以發現我們設定的資料都有正確的在這個產生的JWT內容中,代表產生的JWT是正確的。

那接著要到Startup設定此網站採用JWT方式認證,以下相關設定

Startup.cs

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
  {
     options.TokenValidationParameters = new TokenValidationParameters
    {
       ValidateIssuer = true,
       ValidIssuer = Configuration["Jwt:Issuer"],
       ValidateAudience = true,
       ValidAudience = Configuration["Jwt:Audience"],
       ValidateLifetime = true,
       IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["JWT:KEY"]))
    };
  });

設定完後我們就要測試能不能使用這個JWT成功取得api/todo

如圖在Headers中進行Authorization值的設定,開頭是bearer然後空一格加上得到的JWT,就可以成功讀取API了。

以上是簡單介紹,想要看詳細操作步驟和更多解說可以看影片。

新手分享學習成果,若有錯誤,煩請告知修正,感謝🙏

範例檔:下載




Copyright © 凱哥寫程式 2022 | Powered by TalllKai ❤