【发布时间】:2019-09-04 20:39:12
【问题描述】:
我想在不使用 IdentityServer 或 OAuth 的情况下构建 JWT 安全令牌服务(.net core 2+)来为许多 API(.net core 2+)提供身份验证和授权,因为我希望 没有重定向.
“JWT Authenticator”工作正常并且有路由
- POST 帐户:注册新用户
- POST Auth/Login:如果凭据有效,则返回 jwt 令牌
- POST 令牌:刷新令牌
- POST Token/Revoke:撤销令牌
但是,我很难提供第 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 发出请求以验证令牌/获取声明/等?
【问题讨论】:
-
看起来您刚刚重新发明了资源所有者密码流程。无论如何,JWT 通常不会通过反向通道调用重新验证,因为它们使用非对称加密来证明颁发者和有效性。
-
“因为我不想重定向” – 重定向只是 OAuth 中少数特定身份验证流程的一部分,主要是为了保护用户,因为应用程序不可信用密码。这并不意味着没有允许此如果您可以信任该应用程序的流程。 – 实现自己的身份验证协议通常是一个非常糟糕的主意,因为它非常困难。所以我建议你改用现有的协议和经过良好测试的库来实现这些。
标签: c# asp.net-core jwt asp.net-core-webapi sts-securitytokenservice