oauth-2.0 - 带有 Identity Server 4 的 Web API 2 Framework 4.x 中的访问令牌验证
问题描述
希望有人能指出我正确的方向,我需要在我的 api 中验证身份服务器 4 发出的访问令牌。
API 中已设置授权属性。
从服务器正确检索访问令牌,但是当将访问令牌传递给请求时,我收到 401 Unauthorized 错误,并且没有任何处理请求被拒绝。我正在使用 IdentityServer3.AccessTokenValidation nuget 包。
我注意到对于 AccessTokenValidation 的 v4,您可以设置 RequireHttpsMetadata = false 但我看不到在 v3 中如何设置。
这是最好的方法还是我应该寻找另一个方向?
public void ConfigureAuth(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies",
});
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string,
string>
();
app.UseIdentityServerBearerTokenAuthentication
(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:5000",
RequiredScopes = new[] { "api2" },
});
}
谢谢
解决方案
您需要删除UseCookieAuthentication
并使用UseIdentityServerBearerTokenAuthentication
.
使用部分
using System.IdentityModel.Tokens.Jwt;
using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin;
using Owin;
using System.Net;
下面的配置适用于我使用 .Net 4.7 和dentityServer3.Contrib.AccessTokenValidation nuget 包
public void ConfigureAuth(IAppBuilder app)
{
JwtSecurityTokenHandler.DefaultInboundClaimFilter.Clear();
JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "http://localhost:5000",
RequireHttps = false, // For development
RequiredScopes = new List<string> { "openid", "profile", "address", "roles", "offline_access" },
});
}
使用的 nuget 包
Install-Package IdentityModel -Version 3.10.10
Install-Package IdentityServer3.Contrib.AccessTokenValidation -Version 4.0.36
Install-Package Microsoft.IdentityModel.Tokens -Version 5.3.0
Install-Package System.IdentityModel.Tokens.Jwt -Version 5.3.0
Install-Package Microsoft.IdentityModel.Protocols.OpenIdConnect -Version 5.3.0
Install-Package Microsoft.IdentityModel.Protocols -Version 5.3.0
Install-Package Microsoft.IdentityModel.Logging -Version 5.3.0
Install-Package Microsoft.IdentityModel.JsonWebTokens -Version 5.3.0
推荐阅读
- c# - 您好,我的 AI 不起作用,可能是因为它没有听到我的声音。我该如何解决?
- vue.js - Vue/Vuetiy 1.5 - 添加和删除行+显示和隐藏基于所选项目问题的字段
- javascript - eslint:箭头主体周围的意外块语句
- codeigniter - 生成多个文件 mPDF codeigniter 的问题
- android - ElevatedButton highlightColor?
- python - pandas 对数据透视表中的值进行排序
- c++ - 了解此 for 循环的条件
- wordpress - Gatsby 和 WordPress graphQL:按 id 查询多个图像
- android - KOTLIN:使用列表视图表示从 Firebase 中提取数据
- javascript - 如何根据类是否处于活动状态来更改按钮的href