前篇請參考這裡,因為使用Jose JWT,處理起來相對簡單很多,以下是驗證資料是否被竄改過,只要有被改過,無論是簽章,或是header、payload,改過都會驗證失效的。
[HttpGet]
public Dictionary<string, string> VerifyToken(string token)
{
RSAParameters rsaParams;
var verifyPass = false;
var exp = "";
var errMsg = "";
try
{
using (var tr = new StringReader(File.ReadAllText(HttpContext.Current.Server.MapPath("~/App_Data/JwtKey/public_Key.pem"))))
{
var pemReader = new PemReader(tr);
var publicKeyParams = pemReader.ReadObject() as RsaKeyParameters;
if (publicKeyParams == null)
{
throw new Exception("無法讀取公鑰(Could not read RSA public key)");
}
rsaParams = DotNetUtilities.ToRSAParameters(publicKeyParams);
}
using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider())
{
rsa.ImportParameters(rsaParams);
// 如果表頭、內容、簽章失效皆會拋出Exception
var payload = JsonConvert.DeserializeObject<Dictionary<string, string>>(Jose.JWT.Decode(token, rsa, Jose.JwsAlgorithm.RS256));
// 將payload當作Dictionary使用
exp = payload["exp"];
// 檢查有效時間
.....
verifyPass = true;
}
}
catch (Exception e)
{
errMsg = e.Message;
}
var result = new Dictionary<string, string>()
{
{ "VerifyPass", verifyPass.ToString() },
{ "exp", exp },
{ "ErrMsg", errMsg }
};
return result;
}