[英]How to read Claims from JWT Token .NET 4.5
我無法讀取Bearer JWT令牌的令牌聲明。 登錄正常,http請求帶有到后端的有效jwt令牌。 該應用程序是自托管在IIS7上的。 這是我在服務器端的代碼:
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
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);
在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;
}
也就是說調試,身份變量: 身份
我不知道您的AuthorizationServerProvider.cs出了什么問題,但是從您在請求標頭中提供jwt令牌的那一刻起,我認為它將以這種方式工作。
我在每個接受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);
}
}
用法
[JwtAuthentication(Roles = "User")]
public class ChatBotController : ApiController
{}
請注意,我在Visual Studio 2017中遇到一些問題,該問題從線程讀取Current Principal。 如果您仍然遇到問題,可以看看。 ClaimsPrincipal.Visual Studio 2017當前行為不同
我要做的就是在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.