多种身份验证中间件

时间:2018-10-26 15:49:15

标签: c# asp.net authentication identityserver3 authorize-attribute

美好的一天

我正在将API从使用中移走:

if (claim != null)
{
    var conversionType = typeof(T);

    if (Nullable.GetUnderlyingType(conversionType) != null)
    {
        if (claim.Value == null) //check the null case!
            return default(T);

        //use conversion to `int` instead if `int?`
        conversionType = Nullable.GetUnderlyingType(conversionType);
    }

    return (T)Convert.ChangeType(claim.Value, conversionType);
}

用于验证令牌,以使用IdentityServer。

但是,我还希望能够使用上述中间件来验证以前发行的所有令牌。

因此,首先我将上面的行替换为以下内容(IdentityServer3.AccessTokenValidation):

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); 

这可以有效且正确地授权对受保护端点的请求,但仅适用于IdentityServer发行的令牌。 因此,我相信我在IdentityServer中的设置很好,因为使用了经过正确验证并允许访问的参考令牌。

但是我希望旧的OAuth令牌也得到验证,因此可以支持旧的OAuth令牌以及我的IdentityServer发行的所有JwT或参考令牌。

我发现这样做的方法(如果有更好的方法,请告诉我)是将两个中间件添加到管道中,如下所示:

    .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
        {
            Authority = "http://localhost:5000",
            RequiredScopes = new[] { "api.tablet" },
            ClientId = "TabletAPI",
            ClientSecret = "secret",
        });

这是我所困,似乎IdentityServer中间件始终是试图验证令牌的中间件,一旦失败,似乎就永远不会尝试“旧式” OAuth中间件。

我是否需要向所有[Authorize]端点显式添加一些内容,以指示应尝试两种类型?还是有一种全局指定此方法的方法?

I've found this, which seems more or less exactly like what I want to achieve, but is unfortunately in Asp.Net Core.

在正确的方向上提供任何帮助或帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我找到了这个link,他们建议在其中从IdentityServerBearerTokenAuthenticationOptions中删除RequiredScopes。我尝试了一下,它开始起作用。 所以本质上是这样:

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
    {
        AuthenticationType = "BearerLegacy",
    })
    .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = WebConfigurationManager.AppSettings["AuthServer"],
        RequiredScopes = new[] { "api.tablet" },
        AuthenticationType = "BearerIdSrv",
        ClientId = "TabletAPI",
        ClientSecret = "secret",
    });

需要成为这个:

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
    {
        AuthenticationType = "BearerLegacy",
    })
    .UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
    {
        Authority = WebConfigurationManager.AppSettings["AuthServer"],
        AuthenticationType = "BearerIdSrv",
        ClientId = "TabletAPI",
        ClientSecret = "secret",
    });