Get custom claims from a JWT using Owin

我的未来我决定 提交于 2019-12-04 06:35:55

问题


I'm using Owin with JWTBearerAuthentication to authorize users and validate their tokens. I'm doing it like this:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

        ConfigureOAuth(app);
        app.UseWebApi(config);
    }

    private void ConfigureOAuth(IAppBuilder app)
    {
        string issuer = ConfigurationManager.AppSettings.Get("auth_issuer");
        string audience = ConfigurationManager.AppSettings.Get("auth_clientId");
        byte[] secret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings.Get("auth_secret"));

        app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions 
        {
            AuthenticationMode = AuthenticationMode.Active,
            AllowedAudiences = new [] { audience },
            IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
            {
                new SymmetricKeyIssuerSecurityTokenProvider(issuer, secret)
            }
        });
    }
}

However, I have some custom claims in my token, and want to use their values in my ApiController, which looks like this:

[RoutePrefix("endpoint")]
public class MyApiController : ApiController
{
    [Route("action")]
    [Authorize]
    public IHttpActionResult Post(string someValue)
    {
        bool res = DoSomeAction.withTheString(someValue);

        if (res)
        {
            return Ok<string>(someValue);
        }

        return InternalServerError();
    }
}

Is there anything like User.Claims["myCustomClaim"].Value, which provides the values of all claims?

Thank you, Lukas


回答1:


Something like this might help:

var identity = User.Identity as ClaimsIdentity;

        return identity.Claims.Select(c => new
        {
            Type = c.Type,
            Value = c.Value
        });


来源:https://stackoverflow.com/questions/28045242/get-custom-claims-from-a-jwt-using-owin

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