【发布时间】:2018-01-22 23:57:21
【问题描述】:
我一直在冒险让 JWT 在 DotNet 核心 2.0 上工作(今天已达到最终版本)。有 ton 的文档,但所有示例代码似乎都在使用已弃用的 API 并且对 Core 来说是新鲜的,弄清楚它应该如何实现确实令人眼花缭乱。我尝试使用 Jose,但应用程序。 UseJwtBearerAuthentication 已被弃用,并且没有关于下一步做什么的文档。
是否有人拥有使用 dotnet core 2.0 的开源项目,该项目可以简单地从授权标头中解析 JWT,并允许我授权对 HS256 编码的 JWT 令牌的请求?
下面的类没有抛出任何异常,但是没有请求被授权,我没有得到任何指示为什么它们是未经授权的。响应是空的 401,所以对我来说这表明没有例外,但秘密不匹配。
奇怪的是,我的令牌是使用 HS256 算法加密的,但我没有看到任何指示符告诉它强制它在任何地方使用该算法。
这是我目前上过的课程:
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json.Linq;
using Microsoft.IdentityModel.Tokens;
using System.Text;
namespace Site.Authorization
{
public static class SiteAuthorizationExtensions
{
public static IServiceCollection AddSiteAuthorization(this IServiceCollection services)
{
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("SECRET_KEY"));
var tokenValidationParameters = new TokenValidationParameters
{
// The signing key must match!
ValidateIssuerSigningKey = true,
ValidateAudience = false,
ValidateIssuer = false,
IssuerSigningKeys = new List<SecurityKey>{ signingKey },
// Validate the token expiry
ValidateLifetime = true,
};
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.IncludeErrorDetails = true;
o.TokenValidationParameters = tokenValidationParameters;
o.Events = new JwtBearerEvents()
{
OnAuthenticationFailed = c =>
{
c.NoResult();
c.Response.StatusCode = 401;
c.Response.ContentType = "text/plain";
return c.Response.WriteAsync(c.Exception.ToString());
}
};
});
return services;
}
}
}
【问题讨论】:
-
我关闭了没有更改的签名验证,所有请求都使用 [Authorize] 401
-
你能发布完整的代码吗?或者一个演示项目,我很想看看你是如何让它工作的......
-
还有一篇文章可以帮助你。 stackoverflow.com/a/48295906/8417618