2017-05-30 14 views
1

私はAzure Active Directoryで(クッキーではなく)トークン認証を使用しています。この記事に基づいて.NET CoreとAzure Active Directoryの統合

https://www.itunity.com/article/angular-2-openid-connect-azure-active-directory-3093

私はそれは、クライアント側で動作させることができました。

public validateSignature(token): Observable<boolean> { 
     /* Retrieve from federated metadata endpoint. 
     In this sample, the document was downloaded locally */ 
     return this.httpService.get("metadata/metadata.xml") 
      .map((res: Response) => { 
       let dom = (new DOMParser()).parseFromString(res.text(), "text/xml"); 
       let json = xml2json(dom, ""); 
       let cert = "-----BEGIN CERTIFICATE-----" + 
       JSON.parse(json).EntityDescriptor[0]["ds:Signature"] 
        ["KeyInfo"]["X509Data"]["X509Certificate"] + 
       "-----END CERTIFICATE-----"; 
       let key = KEYUTIL.getKey(cert); 
       return KJUR.jws.JWS.verifyJWT(token, key, { alg: ['RS256'] }); 
      }) 
     } 

私は、.NETのコア1.0.3で再実装上記の方法にしようとしていました。この記事に基づいて

how to sign and verify signature with net and a certificate

次の行では、.NETのコア上でコンパイルされません。

RSACryptoServiceProvider csp = (RSACryptoServiceProvider)cert.PublicKey.Key; 

私が証明書に基づいてトークンを検証するための正しい方法は何かわかりません.NETコアこのQAによる

答えて

2

AzureのADにより発行されたトークンを検証する簡単な方法は、Web APIとOWINコメントを活用しています。 JwtBearerOptionsを設定し、Azure ADによって保護されているコントローラに要求を送信するだけです。トークンが検証されない場合は、401応答が返されます。コードサンプルhereを参照できます。

コードを実装して手動でトークンを確認する場合は、マイクロソフトがMicrosoft.AspNetCore.Authentication.JwtBearerのトークンをどのように確認するかコードを参照できます。

また、私はあなたの参照のためのサンプルコードを書いた:検証すべきデータが何であるか、元の質問では、

public class JsonWebTokenValidator 
{ 
    public void Validate(string token) 
    { 
     var stsDiscoveryEndpoint = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"; 
     var options = new JwtBearerOptions 
     { 
      ConfigurationManager = new ConfigurationManager<OpenIdConnectConfiguration>(stsDiscoveryEndpoint, new OpenIdConnectConfigurationRetriever()), 

      TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters() 
      { 
       ValidateIssuer = true, 
       ValidIssuer = "https://sts.windows.net/{tenantId}/", 

       ValidateAudience = true, 
       ValidAudience = "{audience}", 

       RequireExpirationTime = true, 
       ValidateLifetime = true, 

       ValidateIssuerSigningKey = true, 

       ClockSkew = TimeSpan.Zero 
      }, 
      Authority = "https://login.microsoftonline.com/{tenantId}", 
     }; 

     SecurityToken validatedToken = null; 
     ClaimsPrincipal result = null; 
     var configuration = options.ConfigurationManager.GetConfigurationAsync(new CancellationToken()).Result; 
     options.TokenValidationParameters.IssuerSigningKeys = configuration.SigningKeys; 

     options.ConfigurationManager.RequestRefresh(); 
     foreach (var validators in options.SecurityTokenValidators) 
     { 
      result = validators.ValidateToken(token, options.TokenValidationParameters, out validatedToken); 
     } 

     foreach (var claim in result.Claims) 
     { 
      Console.WriteLine($"{claim.Subject}:{claim.Value}"); 
     } 
    } 

Project.json

{ 
    "version": "1.0.0-*", 
    "buildOptions": { 
    "emitEntryPoint": true 
    }, 

    "dependencies": { 
    "Microsoft.IdentityModel.Clients.ActiveDirectory": "3.13.9", 
    "Microsoft.NETCore.App": { 
     "type": "platform", 
     "version": "1.0.1" 
    }, 

    "System.IdentityModel.Tokens.Jwt": { 
     "version": "5.1.3" 
    }, 
    "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0", 
    "Microsoft.IdentityModel.Protocols": "2.1.3", 
    "Microsoft.IdentityModel.Protocols.OpenIdConnect": "2.0.0" 
    }, 

    "frameworks": { 
    "netcoreapp1.0": { 
     "imports": "dnxcore50" 
    } 
    } 
} 
+0

期待通りに機能しました。ありがとう! –

+0

@DerekLiang問題に役立つ場合は、同じ問題を抱えているコミュニティが便利な投稿を簡単に認識できるように、回答としてマークしてください:) –

+0

ValidateIssuerSigningKeyがtrueに設定されていますが、署名キーはありません。 IssuerSigningKeyプロパティにSymmetricSecurityKey値を追加すると、何の値も与えられません。私はそれが私が持っている秘密鍵だけを検証すると仮定していました。 – RyanOC

0

implement RSA in .NET coreあなたcertオブジェクトがRSAオブジェクトを返すGetRSAPublicKey()方法を持っている必要があります - ちょうどそれがIDisposableだとしてusingでそれをラップするようにしてください。どうやらGetRSAPublicKey()

static bool Verify(string text, byte[] signature, string certPath) 
{ 
    X509Certificate2 cert = new X509Certificate2(certPath); 

    using(RSA rsa = cert.GetRSAPublicKey()) 
    using(SHA1Managed sha1 = new SHA1Managed()) 
    { 
     byte[] data = Encoding.Unicode.GetBytes(text); 
     byte[] hash = sha1.ComputeHash(data); 

     return rsa.VerifyHash(hash, CryptoConfig.MapNameToOID("SHA1"), signature); 
    } 
} 

は、拡張メソッドとして定義されます。https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.rsacertificateextensions.getrsapublickey(v=vs.110).aspx

+0

を? id_tokenには3つの部分、ヘッダー、クレーム、および '。'で区切られた署名があります。また、CryptoConfig.MapNameToOID( "SHA1")は.NET Coreでは使用できません。 –

関連する問題