.NET Core和Azure Active Directory集成 [英] .NET Core and Azure Active Directory integration

查看:178
本文介绍了.NET Core和Azure Active Directory集成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在对Azure Active Directory使用令牌身份验证(而不是cookie)。

I am using the token authentication (instead of cookie) with Azure Active Directory.

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

我能够在客户端使用它。

I was able to get it working on the client side.

   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 Core 1.0.3。中重新实现上述方法。

I was trying to re-implement the above method in the .NET Core 1.0.3.

基于本文:如何使用网络和证书签名和验证签名

以下行将不会在.NET Core上编译:

The following line won't compile on .NET Core:

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

我不确定基于.NET Core中的证书验证令牌的正确方法是什么。

I am not sure what is correct way to verify the token based on the certificate in .NET Core.

推荐答案

一种简单的方法来验证Azure AD发出的令牌是利用带有Web API的OWIN注释。我们只需要配置 JwtBearerOptions 并将请求发送到受Azure AD保护的控制器。如果令牌未经验证,您将收到401响应。您可以在此处引用代码示例。

An easy way to verify the token issued by Azure AD is leverage the OWIN comment with web API. We just need to config the JwtBearerOptions and send the request to a controller which protected by Azure AD. If the token is not verified, you will get the 401 response. You can refer the code sample here.

如果您要实施代码以手动验证令牌,我们可以参考代码Microsoft如何在 Microsoft.AspNetCore.Authentication.JwtBearer

And if you want to implement the code to verify the token manually, we can refer the code how the Microsoft verify the token in Microsoft.AspNetCore.Authentication.JwtBearer.

我还编写了一个代码示例供您参考:

I also wrote a code sample for your reference:

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

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

这篇关于.NET Core和Azure Active Directory集成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆