VSCode+.Net Core 2.0 WebAPI JWT身份驗證
阿新 • • 發佈:2019-01-27
一、使用VSCode 建立WebApi
1、在官網下載 VSCode以及dotnet-sdk-2.1的安裝包(本人為windows64)
2、安裝包安裝完成後,啟動VSCode,使用dotnet 命令 dotnet new webapi 建立一個webAPi專案
二、appsettings.json 配置JWT基礎資訊
1、JWT 官網 https://jwt.io
2、webapi 專案建立完成後,開啟檔案appsettings.json檔案,新增下面的配置
"JwtSettings":{ "Issuer":"http://localhost:5000", "Audience":"http://localhost:5000", "SecretKey":"Hello-key-----wyt" }
此處的配置分別為JWT口令簽發人、口令接收人、祕鑰key
2、專案中建立JwtSettings.cs
using System; namespace DotNet.Utilities { ///<summary> ///JWT配置資訊 ///</summary> public class JwtSettings { //token是誰頒發的 public string Issuer { get; set; } //token可以給哪些客戶端使用 public string Audience { get; set; } //加密的key public string SecretKey{get;set;} } }
三、Startup.cs 檔案配置註冊身份認證
1、在建立的webapi csproj檔案中新增如下引用
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.6" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="2.0.2" />
</ItemGroup>
2、首先在Startup.cs檔案中新增如下引用
using System.Text; using Microsoft.AspNetCore.Authorization; using Microsoft .AspNetCore.Authentication.JwtBearer; using Microsoft.IdentityModel.Tokens;
3、在ConfigureServices方法中寫如下程式碼:
public void ConfigureServices(IServiceCollection services)
{
#region "JWT"
//Get JwtSettings from appsettings.json
services.Configure<JwtSettings>(Configuration.GetSection("JwtSettings"));
// assign JwtSettings model
var jwtSettings=new JwtSettings();
Configuration.Bind("JwtSettings",jwtSettings);
services.AddAuthentication(options=>{
//Auth middleware config
options.DefaultAuthenticateScheme=JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme=JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o=>{
// set jwt token parameters
o.TokenValidationParameters=new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
ValidIssuer =jwtSettings.Issuer,//Issuer
ValidAudience =jwtSettings.Audience,//Audience
//Encryption secret key
IssuerSigningKey=new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.SecretKey)),
ValidateIssuer = true, //whether or not valid Issuer
ValidateAudience = true, //whether or not valid Audience
ValidateLifetime = true, //whether or not valid out-of-service time
ValidateIssuerSigningKey = true, //whether or not valid SecurityKey
ClockSkew=TimeSpan.Zero//Allowed server time offset
};
});
#endregion
services.AddMvc();
}
4、在Configure方法中新增
app.UseAuthentication();
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseMvc();
}
四、建立生成Token的controller
1、建立TokenController.cs檔案,用於生成Token時呼叫此請求,程式碼如下:
[Route("api/[controller]")]
/// <summary>
/// Token
/// </summary>
public class TokenController : Controller
{
private JwtSettings _jwtSettings;
JWtToken jwttoken = new JWtToken();
private HttpResponseMessage WriteMsg(string Msg)
{
return new HttpResponseMessage { Content = new StringContent(Msg, System.Text.Encoding.UTF8, "application/json") };
}
/// <summary>
/// 構造方法
/// </summary>
/// <param name="_jwtSettingsAccesser">Token Model</param>
public TokenController(IOptions<JwtSettings> _jwtSettingsAccesser)
{
_jwtSettings = _jwtSettingsAccesser.Value;
}
///<summary>
///生成Token
///</summary>
///<param name="Loginuser">登入資訊<param>
///<returns></returns>
[HttpPost]
[Route("CreateToken")]
public ActionResult CreateToken([FromBody] LoginInfo Loginuser)
{
string strResult = "";
//判斷使用者是否存在
List<UserInfo> userlist =UserinfoBLL.Login(Loginuser.UserName,Loginuser.PassWord);
if (userlist != null)
{
//使用者唯一 返回口令
if (userlist.Count == 1)
{
jwttoken.Token = MakeToken(userlist[0]);
strResult=RequestReturn.ReturnInfo("","",jwttoken).ToString();
}
//使用者不唯一
if (userlist.Count > 1)
{
strResult=RequestReturn.ReturnInfo("00002","使用者不唯一,請聯絡管理員","").ToString();
}
}
else
{
strResult=RequestReturn.ReturnInfo("00001","使用者名稱或密碼錯誤","").ToString();
}
return Content(strResult);
}
/// <summary>
/// MakeToken
/// </summary>
/// <param name="item">使用者Model</param>
/// <returns>Token</returns>
private string MakeToken(UserInfo item)
{
string strToken = "";
var claim = new Claim[]{
new Claim(ClaimTypes.Name,item.UserName),
new Claim(ClaimTypes.Role,item.RoleID),
new Claim("UserTrueName",item.UserTrueName),
new Claim("UserID",item.UserID)
};
//對稱祕鑰
var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_jwtSettings.SecretKey));
//簽名證書(祕鑰,加密演算法)
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
//生成token [注意]需要nuget新增Microsoft.AspNetCore.Authentication.JwtBearer包,並引用System.IdentityModel.Tokens.Jwt名稱空間
var token = new JwtSecurityToken
(
issuer: _jwtSettings.Issuer,
audience: _jwtSettings.Audience,
claims: claim,
notBefore: DateTime.Now,
expires: DateTime.Now.AddHours(2),//過期時間
signingCredentials: creds
);
try
{
//生成口令
strToken = new JwtSecurityTokenHandler().WriteToken(token);
}
catch
{
}
return strToken;
}
/// <summary>
/// 使用者登入資訊
/// </summary>
public class LoginInfo
{
/// <summary>
/// 登入名
/// </summary>
public string UserName { get; set; }
/// <summary>
/// 登入密碼
/// </summary>
public string PassWord { get; set; }
}
}
五、JWT身份驗證使用測試
1、我這邊建立一個用於獲取使用者資訊的controller檔案,新增[Authorize]
///<summary>
///獲取使用者列表
///</summry>
[HttpGet]
[Authorize]
[Route("GetAllList")]
public ActionResult GetAllList()
{
string strResult = "";
List<UserInfo> userlist= new List<UserInfo>();
userlist=UserinfoBLL.GetALLList();
if (userlist != null)
{
strResult = RequestReturn.ReturnInfo("", "", userlist).ToString();
}
else
{
strResult = RequestReturn.ReturnInfo("00003", "無資料", "").ToString();
}
return Content(strResult);
}
2、使用Potman,先獲取生成的token命令,再將Token從headers傳入,進行身份驗證,若Token驗證失敗,則無法獲取任何資訊