2017-09-22 1 views
0

Ich kann Token Claims vom Bearer JWT Token nicht lesen. Login funktioniert, die HTTP-Anfrage kommt mit einem gültigen JWT-Token zum Backend. Die Anwendung wird auf IIS7 selbst gehostet. Hier ist mein Code auf Serverseite:So lesen Sie Claims von JWT Token .NET 4.5

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

Im ApiController ich versuche den Anrufer Nutzlast Informationen wie diese zu erhalten :

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

, dass die Identität Variable ausgetestet ist: identity

Antwort

0

Ich weiß nicht, was mit Ihrem AuthorizationServerProvider.cs falsch läuft, Aber von dem Moment bieten Ihnen eine jwt Token in Ihrer Anfrage-Header ich denke, es funktioniert diesen Weg.

Ich verarbeite die Kopfzeile mit einem AuthorizeAttribute auf jedem Controller, der JWT-Berechtigung akzeptiert, um den aktuellen Principal für die Anforderung festzulegen.

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

Nutzungs

[JwtAuthentication(Roles = "User")] 
public class ChatBotController : ApiController 
{} 

Hinweis i einige Probleme mit Visual Studio 2017 erlebt haben aus dem Thema des aktuellen Haupt lesen. Sie können sich ansehen, ob weiterhin Probleme auftreten. ClaimsPrincipal.Current Visual Studio 2017 different behavior

0

Alles, was ich tun musste, war die unprotect Funktion in der Klasse JWTFormat

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