2016-09-14 99 views
0

RSA身份驗證在我的Web API 2,考慮以下代碼使用Owin中間件:使用智威湯遜在Owin

public class Startup 
{ 
    public void Configuration(IAppBuilder app) 
    { 
     var config = new HttpConfiguration(); 
     ConfigureAuthentication(app); 
     app.UseCors(CorsOptions.AllowAll); 
     WebApiConfig.Register(config); 
     app.UseWebApi(config); 
     config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;  
    } 

    private static void ConfigureAuthentication(IAppBuilder app) 
    { 
     var issuer = "<<MyIssuer>>"; 
     var audience = "<<MyAudience>>"; 

     const string publicKeyBase64 = "<<MyPublicKeyBase64>>"; 

     var certificate = new X509Certificate2(Convert.FromBase64String(publicKeyBase64)); 

     app.UseJwtBearerAuthentication(
      new JwtBearerAuthenticationOptions 
      { 
       AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, 
       AllowedAudiences = new[] { audience }, 
       IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] 
       { 
        new X509CertificateSecurityTokenProvider(issuer, certificate), 
       } 
      } 
     ); 
    } 
} 

我可以從我的IDP獲得承載令牌和jwt.io結果如下測試:

Verified token

Issuer從代碼到驗證令牌的匹配。

ClientId從代碼到驗證令牌的匹配(sub)。

Audience從代碼到驗證令牌的匹配。

出於某種原因 - 然而,令牌被拒絕(401未經授權)在每個請求上,我無法理解爲什麼。我的請求包括Authorization標頭和我可以使用jwt.ioBearer ey..)驗證的相同不記名標記。如果它有什麼不同,我使用Auth0。我還可以提到,我已經嘗試下載公共證書並使用該文件,而不是僅使用具有相同結果的公鑰字符串。

+0

您的憑據不會在你的形象完全模糊;有可能讀到鑰匙,是否有人這麼傾向。如果尚未流通,我建議撤銷這些令牌。 – Rob

+0

這實際上只是一個示例項目,並且鍵很久以前就已過期,但仍然感謝您的關注;) – Marcus

回答

1

設置JwtBearerAuthenticationOptions實例TokenValidationParameters財產幫助問題:

private static void ConfigureAuthentication(IAppBuilder app) 
{ 
    var issuer = "<<MyIssuer>>"; 
    var audience = "<<MyAudience>>"; 

    const string publicKeyBase64 = "<<MyPublicKeyBase64>>"; 

    var certificate = new X509Certificate2(Convert.FromBase64String(publicKeyBase64)); 

    app.UseJwtBearerAuthentication(
     new JwtBearerAuthenticationOptions 
     { 
      AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, 
      AllowedAudiences = new[] { audience }, 
      IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[] 
      { 
       new X509CertificateSecurityTokenProvider(issuer, certificate), 
      }, 
      TokenValidationParameters = new TokenValidationParameters 
      { 
       IssuerSigningKeyResolver = (a, b, c, d) => new X509SecurityKey(certificate), 
       ValidAudience = audience, 
       ValidIssuer = issuer 
      }   
     } 
    ); 
}