1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でJWTのデコード・検証を行う

Posted at

やんごとなき事情により他所で作成した JWT のデコード・検証を行う必要があった為、やり方をメモ。

他所で作ったJWTをデコードして〇〇のエントリを抜いて使うという設計は一度始めてしまうとJWTの内容に依存する形になってしまう為ロクな事にならない予感しかしない。昔良くあった「IDの〇桁目がNなら~」みたいな仕組みに通じるものを感じる。

var tokenValidationParameters = new TokenValidationParameters {
    ValidateIssuerSigningKey = true,
    IssuerSigningKey = SigningCredentialsProvider.GetVerificationKey(),

    ValidateIssuer = true,
    ValidIssuer = Issuer,

    ValidateAudience = true,
    ValidAudience = Audience,

    ValidateLifetime = true,
    ClockSkew = TimeSpan.Zero
};
var tokenHandler = new JwtSecurityTokenHandler();

JwtSecurityToken jwt = tokenHandler.ReadToken(token) as JwtSecurityToken;
return tokenHandler.ValidateToken(token, tokenValidationParameters, out SecurityToken securityToken);
  • TokenValidationParameters.ValidateXXXX フラグでJWTのどこをバリデーション対象にするか選択可能
  • 検証に失敗すると例外(SecurityTokenInvalidXXXXException)が発生する
  • ValidateToken() の戻り値 ClaimsPrincipal の Claims にJWT各エントリが詰められているので後で取り出して使用できる
  • サンプルでは共通鍵を使ってますが秘密鍵/公開鍵を使う場合は SigningCredentialsProvider を別に実装してください

サンプルソースはこちら

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?