How to extract and get a claim from token?

断了今生、忘了曾经 提交于 2019-12-10 10:16:22

问题


I've been looking for an exact answer but it seems most answers are client call and out of the scope.

Question: I already have an access token access token. How to get a claim using c# code given an access token ONLY?

I think: Below are the same questions but no answers i think fits.

How to get the claims out of a authenticated SecurityToken

How do I read claims from my Oauth token?


回答1:


Install-Package Newtonsoft.Json

The access token is just base64 encoded JSON. You can parse the token as follows

        string token =
            "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.TJVA95OrM7E2cBab30RMHrHDcEfxjoYZgeFONFh7HgQ";
        var parts = token.Split('.');
        var decoded = Convert.FromBase64String(parts[1]);
        var part = Encoding.UTF8.GetString(decoded);
        var jwt = JObject.Parse(part);
        var name = jwt["name"].Value<string>();

UPDATE

  1. Parsing access token on the client is not recommended, access token should be parsed only on the resource server.
  2. You must validate the access token on the resource server to make sure that token has not tampered on the way.
  3. Most of the time you dont need to parse token as above, Just use a recommended JWT library that does both validation and parsing. e.g.

    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());



来源:https://stackoverflow.com/questions/43839214/how-to-extract-and-get-a-claim-from-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!