.net Core Api身份验证与ADFS 2012 [英] .net Core Api authentication with ADFS 2012

查看:258
本文介绍了.net Core Api身份验证与ADFS 2012的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要配置.Net Core Web Api(.Net Framework)以使用ADFS 3.0(2012)来验证移动客户端发送的Bearer令牌。

I need to configure my .Net Core Web Api (.Net Framework) to use ADFS 3.0 (2012) to validate the Bearer tokens sent by our mobile clients.

我能够从ADFS服务器生成access_token,并将其传递到Authorization标头中。

I am able to generate the access_token from the ADFS server, and I pass it in the Authorization header.

我的问题在API中:如何将其配置为验证并授权用户?

My problem is in the API: how do I configure it to validate and autorize the user?

我在很多地方搜索过,但找不到确定的方法。

I searched in many places and I could not find a definitive method of doing it.

到目前为止我尝试过的操作:

What I tried so far:

使用了IdentityServer4(失败,因为它使用JWT和ADFS不提供OpenID
尝试了UseOpenIdConnectAuthentication(在IdentityServer4上找到了示例) )
a自定义中间件
我不能使用其他方法,我需要支持oAuth2。

Used IdentityServer4 (Failed because it uses JWT and ADFS doesn't offer OpenID Tried UseOpenIdConnectAuthentication (found example at IdentityServer4) a custom Middleware I can't use another method, I need to support oAuth2.

那么,我该怎么做?

So, how do I do it?

这是我的最新尝试:

    var connectOptions = new OpenIdConnectOptions
    {
        AuthenticationScheme = "adfs",
        SignInScheme = "idsrv.external", //IdentityServerConstants.ExternalCookieAuthenticationScheme,
        SignOutScheme = "idsrv", //IdentityServerConstants.SignoutScheme,
        AutomaticChallenge = false,
        DisplayName = "ADFS",
        Authority = $"https://{options.AdfsHostName}/adfs/oauth2",
        ClientId = options.ClientID,
        ResponseType = "id_token",
        Scope = { "openid profile" },
        CallbackPath = new PathString("/signin-adfs"),
        SignedOutCallbackPath = new PathString("/signout-callback-adfs"),
        RemoteSignOutPath = new PathString("/signout-adfs"),
        ClaimsIssuer = $"https://{options.AdfsHostName}/adfs/services/trust",
        //TokenValidationParameters = new TokenValidationParameters
        //{
        //    ValidateIssuer = true,
        //    ValidIssuer = $"https://{options.AdfsHostName}/adfs/services/trust"
        //},

    };

    app.UseOpenIdConnectAuthentication(connectOptions);

每次通话我都会得到一个非常快速的401,带有有效令牌。实际上,虽然我在控制台窗口中看到了连接,但在Roslyn控制台窗口中没有看到其他有关安全性验证的日志。

I get a very quick 401 on every calls, with a valid token. In fact, while I see the connection in the console window, I don't see any other log in the Roslyn console window regarding the security validation.

我目前使用ASP.Net Core 1.1.X,如果可以的话,我会避免转向.Net Core 2.0,因为我们在项目中处于后期阶段,它包含许多重大更改...

I'm currently using ASP.Net Core 1.1.X, and if I can I'd avoid moving to .Net Core 2.0, as we are late in the project and it contains many breaking changes...

随时询问更多信息,我将不胜感激所有的好建议!

Feel free to ask for more info, and I'll appreciate all the good advices!

推荐答案

事实证明,我们可以将JwtBearerAuthentication与ADFS 3.0一起使用。

As it turns out, we can use the JwtBearerAuthentication with ADFS 3.0.

我最初遇到的问题是它去了/.well-known/openid-configuration的元数据获取。 ,但ADFS 3.0不支持OpenID,这将返回404。

My initial problem with it was that it went to fetch the metadata at /.well-known/openid-configuration, but ADFS 3.0 does not support OpenID and this returns a 404.

我在另一篇文章中读到(找到后会更新),如果正确配置,则无需获取配置。但是什么配置呢?

I read in another post (I'll update it when I find it) that if with the right configuration, it won't need to fetch the config. But what configuration?

我在(MS)代码的深处发现,如果将OpenIdConnectConfiguration对象传递给JwtBearerOptions的Configuration属性,它将不会获取元数据。

Well I found deep in the (MS) code that if one pass an OpenIdConnectConfiguration object to the Configuration property of the JwtBearerOptions, it wont fetch the metadata.

所以这是我的代码:

var rawCertData = Convert.FromBase64String(options.X509SigninCertificate);

X509Certificate2 cert = new X509Certificate2(rawCertData);

SecurityKey signingKey = new X509SecurityKey(cert);

X509证书数据来自此URL支持的adfs元数据

The X509 cert data comes from the supported adfs metadata at this url

https://Your.ADFS.Site/FederationMetadata/2007-06/FederationMetadata.xml 

它包含以下内容:

<KeyDescriptor use="signing">
    <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
        <X509Data>
            <X509Certificate>SOMEUUENCDODEDSTRING=</X509Certificate>
        </X509Data>
    </KeyInfo>
</KeyDescriptor>

我只是将UUEncoded字符串复制到设置的X509SigninCertificate属性中。

I simply copied the UUEncoded string in my settings' X509SigninCertificate property.

var tokenValidationParameters = new TokenValidationParameters
        {
            // The signing key must match!
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = signingKey,

            // Validate the JWT Issuer (iss) claim
            ValidateIssuer = true,
            ValidIssuer = $"https://{options.AdfsHostName}/adfs/services/trust",

            // Validate the JWT Audience (aud) claim
            ValidateAudience = true,
            ValidAudience = options.ClientUri, //"https://YOUR-AUDIENCE/",

            // Validate the token expiry
            ValidateLifetime = true,


            // If you want to allow a certain amount of clock drift, set that here:
            ClockSkew = TimeSpan.Zero
        };

        var connectOptions = new OpenIdConnectConfiguration
        {
            Issuer = $"https://{options.AdfsHostName}/adfs/services/trust",
        };

        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            TokenValidationParameters = tokenValidationParameters,
            Configuration = connectOptions                
        });

这里重要的一行是

Configuration = connectOptions

这样做,告诉验证者不要获取元数据。如此简单。

By doing this, you tell the validator to not fetch the metadata. Simple as that.

我能够验证令牌(AUD,ISS和SIGN),并且可以在项目中使用ADFS。

I was able to validate my token (AUD, ISS and SIGN) and I can use ADFS in my project.

这篇关于.net Core Api身份验证与ADFS 2012的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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