资源服务器API

时间:2017-09-26 09:22:11

标签: .net api asp.net-core-mvc jwt openiddict

我一直在设置一个OpenIdDict authserver,用于我们现有的mvc core 2.0 Web应用程序。我正在使用代码流并在我们的生产应用程序上实现OpenIdConnect部分之前制作了测试mvc webapp资源服务器。

一切似乎都按预期工作,我可以登录并访问我的资源。

我需要让api bearer身份验证在我的其他客户端的新auth架构下工作。 Api放在同一资源服务器上。

我使用以下方法为JWT设置了OpenIddict:

            options.AllowPasswordFlow();
            options.UseJsonWebTokens();
            options.AddSigningKey(new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value)));

...添加了JwtBearer

        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

        services.AddAuthentication()
            .AddJwtBearer(options =>
            {
                options.Authority = "http://localhost:17004/";
                options.Audience = "MyAudience";
                options.RequireHttpsMetadata = false;
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = OpenIdConnectConstants.Claims.Subject,
                    RoleClaimType = OpenIdConnectConstants.Claims.Role,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value))
                };
            });

...并在AuthorizationController.Exchange中添加了用于处理密码流令牌请求的代码。

在我的资源服务器Startup.cs上,我添加了AddOpenIdConnect并添加了signingKey(与我的auth服务器上的密钥相同)。

            options.ResponseType = OpenIdConnectResponseType.Code;
            options.AuthenticationMethod = OpenIdConnectRedirectBehavior.RedirectGet;
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration.GetSection("TokenAuthentication:SecretKey").Value))
            };
            options.Authority = "http://localhost:17004/";

设置完成后,我的资源服务器仍然可以进行身份​​验证,一切正常,我可以使用restclient从我的auth服务器获取jwt令牌,但是当尝试访问资源服务器上的api时,它会失败,因为没有验证器不记名计划。

如果我在资源服务器上添加调用AddBearerToken,在TokenValidationParameters中使用相同的signingKey,它实际上是有效的。挑战是成功的,我可以访问我的资源。

但是我怀疑我的设置远非正确,因为我可以看到,在调用我的api时,我的令牌的验证发生在资源服务器上,所以我留下2个问题。

  1. 是否可以让JwtBearer中间件将验证转发给我的auth服务器? (可以用openidConnect处理吗?)

  2. 我的auth服务器是否有可能使我的资源服务器转发/ passthru令牌发出请求所以我的其他api客户端不必处理2台服务器?

2 个答案:

答案 0 :(得分:1)

  

是否可以让JwtBearer中间件将验证转发给我的auth服务器? (可以用openidConnect处理吗?)

JWT承载中间件始终使用从OpenIddict的配置端点检索到的签名密钥执行本地验证。您无法强制它将此任务委派给OpenIddict。

  

是否有可能使我的资源服务器转发/ passthru令牌发出请求也是我的auth服务器所以我的其他api客户端不必处理2台服务器?

如果要将令牌验证部件委派给授权服务器,则不要使用JWT中间件。相反,在OpenIddict选项中启用内省,创建新的机密客户端应用程序注册并使用aspnet-contrib introspection middleware,它将使用反向通道HTTP调用来验证传入的令牌。

答案 1 :(得分:0)

JWT是一种令牌格式,是OpenIdConnect所必需的。您可以将任何令牌格式与Oauth2(包括JWT)一起使用。所以你不需要跳过JWT。