Owin

2016-09-14 7 views
0

にJWTを使用してRSAで認証するOwinミドルウェアを使用して自分のWeb API 2でこのコードを考えてみましょう: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 Unauthorized)、私はなぜその理由を知ることができません。私のリクエストには、jwt.ioBearer ey..)を使用して確認できる同じベアラトークンを持つAuthorizationヘッダーが含まれています。それが何か違いがあれば、私はAuth0を使用します。公開された証明書をダウンロードして、同じ結果を持つ公開鍵文字列を使用する代わりにファイルを使用しようとしたことにも言及することができます。 JwtBearerAuthenticationOptionsインスタンスのTokenValidationParametersプロパティを設定

+0

あなたの資格情報は完全にあなたのイメージに難読化されていません。誰かがそんなに傾いていたかどうか、鍵を読むことは可能です。あなたがまだ持っていないのであれば、彼らがまだ流通しているなら、それらのトークンを取り消すことを提案したいと思います。 – Rob

+0

これは実際にはほんのサンプルプロジェクトであり、キーはずっと前に失効しましたが、それでも気になります。 – Marcus

答えて

1

は問題を助けた:

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