asp.net-core - .net 4.6 web api2 401 未经授权使用身份服务器 4
问题描述
我已经在 .net 核心应用程序中有一个工作身份服务器 4。
namespace IdentityServer
{
public class Config
{
public static IEnumerable<ApiResource> GetApiResources()
{
return new List<ApiResource>
{
new ApiResource("myresourceapi", "My Resource API")
{
Scopes = {new Scope("apiscope")}
}
};
}
public static IEnumerable<Client> GetClients()
{
return new[]
{
// for public api
new Client
{
ClientId = "secret_client_id",
AllowedGrantTypes = GrantTypes.ClientCredentials,
ClientSecrets =
{
new Secret("secret".Sha256())
},
AllowedScopes = { "apiscope" }
}
};
}
}
}
namespace IdentityServer
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
services.AddIdentityServer()
.AddDeveloperSigningCredential()
.AddOperationalStore(options =>
{
options.EnableTokenCleanup = true;
options.TokenCleanupInterval = 30; // interval in seconds
})
.AddInMemoryApiResources(Config.GetApiResources())
.AddInMemoryClients(Config.GetClients());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseIdentityServer();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
await context.Response.WriteAsync("Hello World!");
});
});
}
}
}
问题是现在我需要向 .net 4.6 web api2(不是核心)发出经过身份验证的请求。而 IdentityServer4.AccessTokenValidation 包对此不起作用。根据这个问题(https://stackoverflow.com/questions/41992272/is-it-possible-to-use-identity-server-4-running-on-net-core-with-a-webapi-app-r
),我所要做的就是使用与身份服务器 3(IdentityServer3.AccessTokenValidation)相同的包。这是我在 webapi 2 中实现的代码
using IdentityServer3.AccessTokenValidation;
using Microsoft.Owin;
using Owin;
using Microsoft.Owin.Host.SystemWeb;
using IdentityModel.Extensions;
using System.Web.Http;
[assembly: OwinStartup(typeof(WebApplication10.Startup))]
namespace WebApplication10
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44357",
// For access to the introspection endpoint
ClientId = "secret_client_id",
ClientSecret = "secret".ToSha256(),
RequiredScopes = new[] { "apiscope" }
});
}
}
}
namespace WebApplication10.Controllers
{
public class ValuesController : ApiController
{
[Authorize]
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
}
我一直得到的状态是 401 Unauthorized。难道我做错了什么?有什么帮助吗?谢谢。
解决方案
如果没有日志,则无法确定您的情况是什么问题,但这是我为使其正常工作而进行的一些修复:
- 关于
Statup.cs
IdentityServer 项目的类- 更改
AccessTokenJwtType
为JWT
,IdentityServer4 上的默认值是at+jwt
但 .Net Framework Api (OWIN/Katana) 需要JWT
. - 通过设置为 true添加
/resources
aud ,这在 IdentityServer4 上被删除。EmitLegacyResourceAudienceClaim
- 更改
您可以通过检查和来验证https://jwt.ms/上的 access_token 。"typ"
"aud"
var builder = services.AddIdentityServer(
options =>
{
options.AccessTokenJwtType = "JWT";
options.EmitLegacyResourceAudienceClaim = true;
});
- 在
Statup.cs
.Net Framework Api 项目的类上,设置ValidationMode
为ValidationMode.Local
,此方法使用的自定义访问令牌验证端点在 IdentityServer4 上被删除。
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "https://localhost:44357",
// For access to the introspection endpoint
ClientId = "secret_client_id",
ClientSecret = "secret".ToSha256(),
RequiredScopes = new[] { "apiscope" },
ValidationMode = ValidationMode.Local,
});
我强烈建议您收集有关 API 的日志,这有助于在您的案例中找到实际问题并找到解决方法。这是在 Api 上打开 OWIN 日志的示例。
推荐阅读
- python-3.x - 如果一个类名出现在另一个类名中怎么办?
- ios - 在 IOS 设备上运行的 React Native 应用程序出现问题
- javascript - 如何在 ES6 语法中导入 firebase-functions 和 firebase-admin 以使用 Babel for Node 10 进行转译
- python - 获取networkx图python中邻居节点的属性
- node.js - ENOENT:运行 npm install 命令时没有这样的文件或目录
- google-colaboratory - 如何对 Google Colab 上的某行发表评论?
- html - 元素内的垂直居中图像
- angular - ng serve --port 4200 和 ng serve --host ip:4200 的区别
- jpa - JPA中实体的替代初始值
- flutter - 流式传输数据时如何通过小部件构建条件?