[英]How to read Claims from JWT Token .NET 4.5
I can't read token claims from Bearer JWT token. 我无法读取Bearer JWT令牌的令牌声明。 Login is working, the http request comes with a valid jwt token to the backend.
登录正常,http请求带有到后端的有效jwt令牌。 The application is self hosted on IIS7.
该应用程序是自托管在IIS7上的。 Here is my code on server side:
这是我在服务器端的代码:
SecurityConfig.cs SecurityConfig.cs
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromHours(24),
Provider = new AuthorizationServerProvider() ,
AccessTokenFormat = new JwtFormat(TimeSpan.FromHours(24))
});
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
AuthorizationServerProvider.cs AuthorizationServerProvider.cs
ClaimsIdentity id = new ClaimsIdentity(context.Options.AuthenticationType);
id.AddClaim(new Claim(InosysClaimTypes.UserId, Convert.ToString(appContext.UserId)));
id.AddClaim(new Claim(InosysClaimTypes.Username, context.UserName));
id.AddClaim(new Claim(InosysClaimTypes.Password, context.Password));
id.AddClaim(new Claim(InosysClaimTypes.FirNr, Convert.ToString(appContext.FirmenNummer)));
id.AddClaim(new Claim(InosysClaimTypes.FirNdl, Convert.ToString(appContext.Niederlassung)));
id.AddClaim(new Claim(InosysClaimTypes.Bereich, Convert.ToString(appContext.Bereich)));
id.AddClaim(new Claim(InosysClaimTypes.Sprache, Convert.ToString(appContext.Sprache)));
id.AddClaim(new Claim(InosysClaimTypes.SchiffNummern, appContext.SchiffNummern == null ? "" : string.Join(",", appContext.SchiffNummern)));
id.AddClaim(new Claim(InosysClaimTypes.Geschaeftsjahr, Convert.ToString(appContext.Geschaeftsjahr)));
var principal = new ClaimsPrincipal(id);
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
context.Validated(id);
In the ApiController i try to get the caller's payload information like this: 在ApiController中,我尝试获取调用者的有效负载信息,如下所示:
ClaimsIdentity identity = User.Identity as ClaimsIdentity;
if (identity != null)
{
appContext.UserId = Convert.ToInt32(identity.FindFirst(InosysClaimTypes.UserId).Value);
appContext.Username = identity.FindFirst(InosysClaimTypes.Username).Value;
}
That is the identity variable debugged: identity 也就是说调试,身份变量: 身份
I don't know what is going wrong with your AuthorizationServerProvider.cs , But from the moment you provide a jwt token in your request header i think it will work this way. 我不知道您的AuthorizationServerProvider.cs出了什么问题,但是从您在请求标头中提供jwt令牌的那一刻起,我认为它将以这种方式工作。
I process the Header with an AuthorizeAttribute on each Controller accepting JWT authorization to set the Current Principal for the request. 我在每个接受JWT授权以设置请求的当前主体的Controller上使用AuthorizeAttribute处理Header。
public class JwtAuthentication : AuthorizeAttribute
{
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var authHeader=actionContext.Request.Headers.Authorization;
if (authHeader!=null&& !String.IsNullOrWhiteSpace(authHeader.Parameter))
System.Threading.Thread.CurrentPrincipal = JwtAuthenticationHandler.GetPrincipal(authHeader.Parameter);
return ClientAuthorize.Authorize(Roles);
}
}
Usage 用法
[JwtAuthentication(Roles = "User")]
public class ChatBotController : ApiController
{}
Note i have been experiencing some issues with visual studio 2017 reading the Current Principal from the Thread. 请注意,我在Visual Studio 2017中遇到一些问题,该问题从线程读取Current Principal。 You might have a look at if you still experience issues.
如果您仍然遇到问题,可以看看。 ClaimsPrincipal.Current Visual Studio 2017 different behavior
ClaimsPrincipal.Visual Studio 2017当前行为不同
All I needed to do was to implement the unprotect function in the JWTFormat class 我要做的就是在JWTFormat类中实现unprotect函数
public AuthenticationTicket Unprotect(string protectedText)
{
try
{
var handler = new JwtSecurityTokenHandler();
AppContext = new AppContext(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString)
{
EventLogPriority = Properties.Settings.Default.EventLogPriority
};
SecurityToken validToken;
_validationParameters.IssuerSigningKey = new SymmetricSecurityKey(TextEncodings.Base64Url.Decode(Secret));
ClaimsPrincipal principal = handler.ValidateToken(protectedText, _validationParameters, out validToken);
var validJwt = validToken as JwtSecurityToken;
if (validJwt == null)
{
throw new ArgumentException("Invalid JWT");
}
ClaimsIdentity identity = principal.Identities.FirstOrDefault();
return new AuthenticationTicket(identity, new AuthenticationProperties());
}
catch (SecurityTokenException ex)
{
var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Access Token is manipulated" };
throw new HttpResponseException(msg);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.