【问题标题】:Get custom claims from a JWT using Owin使用 Owin 从 JWT 获取自定义声明
【发布时间】:2015-03-18 16:12:22
【问题描述】:

我正在使用带有 JWTBearerAuthentication 的 Owin 来授权用户并验证他们的令牌。我是这样做的:

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)
            }
        });
    }
}

但是,我的令牌中有一些自定义声明,并希望在我的 ApiController 中使用它们的值,如下所示:

[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();
    }
}

有没有类似User.Claims["myCustomClaim"].Value 的东西,它提供了所有声明的值?

谢谢你, 卢卡斯

【问题讨论】:

    标签: c# asp.net-web-api asp.net-identity owin jwt


    【解决方案1】:

    这样的事情可能会有所帮助:

    var identity = User.Identity as ClaimsIdentity;
    
            return identity.Claims.Select(c => new
            {
                Type = c.Type,
                Value = c.Value
            });
    

    【讨论】:

    • 这会返回 null,但调试身份对象显示 identity -&gt; Non-Public members -&gt; m_instanceClaims 包含我想要访问的声明。如何访问该对象?编辑:我猜我的令牌或其他任何东西都错了,重新启动并使用另一个令牌后,它可以工作。谢谢!
    猜你喜欢
    • 2016-01-06
    • 1970-01-01
    • 2018-07-05
    • 2017-12-27
    • 2016-01-01
    • 2020-03-15
    • 2019-02-26
    • 2023-04-10
    • 2019-04-15
    相关资源
    最近更新 更多