如何在没有IdentityServer或OAuth的情况下配置JWT STS

时间:2019-04-14 19:53:39

标签: c# asp.net-core jwt asp.net-core-webapi sts-securitytokenservice

我想构建一个JWT安全令牌服务(.net核心2+),以便在不使用IdentityServer或OAuth的情况下为许多API(.net核心2+)提供身份验证和授权,因为我希望不重定向 >。

下图描述了这种情况:

diagram

“ JWT身份验证器”工作正常,并且具有路由

  • POST帐户:注册新用户
  • POST身份验证/登录:如果凭据有效,则返回jwt令牌
  • POST令牌:刷新令牌
  • POST令牌/撤消:撤消令牌

但是,我努力提供第4步和第5步。我在API1 / Startup.cs-> ConfigureServices中尝试了许多选项,并且在调用GET API1 / Resource时无法得到任何结果,但404。 ConfigureServices方法仍然是这样:

 public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
        })
       .AddJwtBearer(options =>
       {
           options.Authority = "http://localhost:6000"; // JWT Authenticator address
           options.RequireHttpsMetadata = false;
           options.SaveToken = true;
           options.TokenValidationParameters = new TokenValidationParameters
           {    
               ValidIssuer = _configuration.GetValue<string>("JwtIssuer"),
               ValidAudience = _configuration.GetValue<string>("JwtAudience"),
               IssuerSigningKey = new SymmetricSecurityKey(
                   Encoding.UTF8.GetBytes(_configuration.GetValue<string>("JwtSecretKey"))),
               ClockSkew = TimeSpan.Zero
           };
       });

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    }

是否可以使用AddJwtBearer之类的方法配置第4步和第5步?如果没有,我该怎么办?使用对API1的授权过滤器来拦截请求,并向JWT Authenticator发出请求以验证令牌/获取声明/等?

1 个答案:

答案 0 :(得分:0)

一些想法...

您的4和5条路径;通常,您不询问令牌的提供者是否有效。您要做的就是验证这一点,很可能使用签名进行验证,可以(可选)从提供程序下载哪些参数。

请注意细微的差别:提供程序本身不会对其进行检查。

下一步: ClockSkew = TimeSpan.Zero,这很少。我至少会给它一些懈怠。

至少拥有404表示找不到资源。它不是401403。这表明授权成功,但是找不到请求的资源。


签名验证的典型实现:

注意,这不能解决您的404问题。

options.TokenValidationParameters = new TokenValidationParameters
{
    IssuerSigningKeyResolver = (s, securityToken, identifier, parameters) =>
    {
        // get from provider 
        // todo: cache this
        var json = new WebClient().DownloadString(
             issuer + "/.well-known/jwks.json"); //typical endpoint

        // serialize the result
        var keys = JsonConvert.DeserializeObject<JsonWebKeySet>(json).Keys;
        // cast the result to be the type expected by IssuerSigningKeyResolver
        return (IEnumerable<SecurityKey>) keys;
    }
//...