2015-11-19 47 views
4

我想弄清楚如何從我的令牌中獲得索賠。 我會盡量的保持說明短期MVC與歐文JWT身份

  • 我有一個HTML網頁,做了後到我的網頁API,確實與認證 檢查,並返回一個JWT令牌
  • 當我得到令牌回來,我想把它發送到不同的網址,我這樣做的方式是使用查詢字符串。我知道我可以使用cookies,但對於這個應用程序,我們不想使用它們。所以,如果我的網址看起來像這樣http://somedomain/checkout/?token=bearer token comes here

我使用Owinmiddleware,這是我迄今爲止

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

但我如何得到ClaimsToken或只是檢查IsAuthenticated

我想我controller內以下只是爲了檢查,但IsAuthenticated總是false

var identity = (ClaimsIdentity) HttpContext.Current.GetOwinContext().Authentication.User.Identity; 
    if (!identity.IsAuthenticated) 
     return; 

    var id = identity.FindFirst(ClaimTypes.NameIdentifier); 

回答

2

好吧,我設法弄明白了。上面的代碼是一切正常,但我需要添加UseJwtBearerAuthentication中間件。

有一件事我也結束了從我原來的代碼改變是我改變了context.Token = token;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); 
      } 
     } 
    }