【发布时间】:2017-08-11 15:48:15
【问题描述】:
我正在将我的 asp.net 服务拆分为多个微服务。作为一个流程,我使用 Node.Js 创建了我的身份服务,它使用 JWT 作为令牌。
现在我想在 C# 中使用此令牌,以便我的所有 [Authorise] 属性都使用此令牌并允许访问。
我查看了许多实现,但无法使其正常工作。由于 JWT 是标准实施,我不明白为什么这不起作用。
这是我的 C# 代码
public void ConfigureAuth(IAppBuilder app)
{
var issuer = "myorg/identity2";
string audienceId = ConfigurationManager.AppSettings["as:AudienceId"];
byte[] audienceSecret = TextEncodings.Base64Url.Decode
("xfecrrt7CV");
// Api controllers with an [Authorize] attribute will be validated with JWT
app.UseJwtBearerAuthentication(
new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AllowedAudiences = new[] { audienceId },
IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
{
new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
}
});
但是,每次我尝试访问受保护的方法时都会收到此错误。
{"Message":"Authorization has been denied for this request."}
这里有什么我遗漏的吗?如何将声明身份添加到此?
【问题讨论】:
-
您确定此密钥
xfecrrt7CV与用于签名的密钥相同并且是base64url 编码的吗? -
令牌在标头中作为不记名令牌正确传递。我在jwt.io 上测试了令牌,如果我不选择“秘密 base64 编码”,它会得到正确验证。我尝试使用 UTF8、Unicode 编码将其转换为字节数组。但它不起作用。
-
那么错误就在这里
byte[] audienceSecret = TextEncodings.Base64Url.Decode("xfecrrt7CV");你正在尝试base64url 解码一个不是的字符串。你试过Encoding.UTF8.GetBytes("xfecrrt7CV");吗? -
是的,我确实尝试过 Encoding.UTF8.GetBytes("xfecrrt7CV")
-
发行者是 NodeJS 端的 api 端点吗?你能告诉我们你是如何为那条路线声明控制器的吗?使用 express 你应该像这样注册一个中间件: app.use('/myorg/identity2', expressJwt({secret: secret}));以便请求包含令牌