我试图找出如何从我的令牌中获得索赔.
我会尽量保持解释简短
>我有一个HTML页面,发布到我的web api的帖子,确实和auth
检查并返回JWT令牌
>当我收到令牌后,我想将它发送到不同的URL,我这样做的方式是使用查询字符串.我知道我可以使用cookies,但对于这个应用程序,我们不想使用它们.所以,如果我的网址看起来像这样http:// somedomain / checkout /?token = bearer token来到这里
我正在使用Owin中间件,这是我到目前为止所拥有的
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
Provider = new ApplicationOAuthBearerAuthenticationProvider(),
});
public class ApplicationOAuthBearerAuthenticationProvider
: OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var token = HttpContext.Current.Request.QueryString["token"];
if (!string.IsNullOrEmpty(token))
context.Token = token;
return Task.FromResult<object>(null);
}
}
但是我如何从令牌中获取声明或只是检查IsAuthenticated
我在我的控制器内部尝试了以下检查,但是IsAuthenticated总是假的
var identity = (ClaimsIdentity) HttpContext.Current.GetOwinContext().Authentication.User.Identity;
if (!identity.IsAuthenticated)
return;
var id = identity.FindFirst(ClaimTypes.NameIdentifier);
最佳答案 好的,所以我设法搞清楚了.我上面的代码都运行良好,但我需要添加UseJwtBearerAuthentication中间件.
我最后改变原始代码的一件事是改变了context.Token = token; to context.Request.Headers.Add(“Authorization”,new [] {string.Format(“Bearer {0}”,token)});
所以我的启动课看起来像这样……
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
{
Provider = new ApplicationOAuthBearerAuthenticationProvider(),
});
app.UseJwtBearerAuthentication(JwtOptions());
ConfigureAuth(app);
}
private static JwtBearerAuthenticationOptions JwtOptions()
{
var key = Encoding.UTF8.GetBytes(ConfigurationManager.AppSettings["auth:key"]);
var jwt = new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters
{
ValidAudience = Some Audience,
ValidIssuer = Some Issuer,
IssuerSigningToken = new BinarySecretSecurityToken(key),
RequireExpirationTime = false,
ValidateLifetime = false
}
};
return jwt;
}
public class ApplicationOAuthBearerAuthenticationProvider
: OAuthBearerAuthenticationProvider
{
public override Task RequestToken(OAuthRequestTokenContext context)
{
if (context == null)
throw new ArgumentNullException("context");
var token = HttpContext.Current.Request.QueryString["token"];
if (!string.IsNullOrEmpty(token))
context.Request.Headers.Add("Authorization", new[] { string.Format("Bearer {0}", token) });
return Task.FromResult<object>(null);
}
}
}