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 3 years have passed since last update.

リクエストヘッダーに付与されたBearer Tokenを解析して情報を取得する

Posted at

備忘録として後世の自分に残す。

概要

APIにリクエストされた情報(Bearer Token)を取得 → Tokenの情報を解析してほしい情報を持ってこれるようにする

まずはリクエストヘッダーのToken情報を取得する

リクエスト情報の取得はHttpContextAccesorを使う。
DIして👇みたいに使ってみる。
Headers[""]の中身にKeyを指定すれば他のヘッダー情報もひっこぬける。

private readonly IHttpContextAccessor _httpContextAccessor;

public hogeController(IHttpContextAccessor httpContextAccessor)
{
  // DIする
  _httpContextAccessor = httpContextAccessor;
}

[HttpGet]
public Task<ActionResult> GetHoge()
{
  var request = _httpContextAccessor.HttpContext.Request;
  string token = req.Headers["Authorization"] // Authorizationヘッダーにセットされてる値を取得する
}

取得したTokenを解析

取得したtokenにBearerついてる場合はReplaceメソッドなりで置き換えておきましょう。

token = token.Replace("Bearer", "").Trim();

Token解析には
JwtSecurityTokenHandler()使います。
System.IdentityModel.Tokens.Jwtをパッケージに追加しておく。

var handler = new JwtSecurityTokenHandler();
var ArrayToken = token.Split("&");
var result = "";
var target = "name";

target変数には取得したい情報を指定します。
何を引っこ抜きたいかはJWTなどのサイトで
事前に解析したいTokenをセットしてペイロードなり確認してください。
Tokenを「&」でSplitしてるのは解析で使うのは最初のほうの情報になってくるのでSplitしてる。
早速解析してみる。👇

if (handler.CanReadToken(ArrayToken[0]))
 {
  var readToken = handler.ReadToken(ArrayToken[0]) as JwtSecurityToken;
  var res = readToken.Claims.Where(w => w.Type == target);
  if (res.Any())
  {
    var prop = res.First();
    result = prop != null ? prop.Value : "";
  }
}

ReadToken()で読み取る。
Claimsに情報が入ってるのでそこから欲しい情報を引っこ抜く。

終わり

自分はよくリクエストの情報を取得するのに毎回調べてる感じあるので今回残してみた。

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?