asp.net-core - 如何在 asp.net core 中使用 JWT 登录用户
问题描述
我有一个 IdentityServer4 实例。
此 IdentityServer4 实例由单独的 asp.net 核心 Web 应用程序(来自 http 登录操作)调用以接收 JWT。
我如何使用此 JWT 来“登录”用户?
解决方案
您想要进行身份验证的客户端应用程序应该通过 Open ID Connect (OIDC) 协议与 Identity Server 应用程序进行通信。Asp.net 核心支持开箱即用AddAuthentication().AddOpenIdConnect()
,您可以IServiceCollection
在Startup.cs
文件中使用扩展名。
在该Configure
方法中,调用UseAuthetication
是用户实际“登录”的内容(它将用户声明添加到传入请求中)。因此,如果您使用例如 MVC,请确保在调用UseMvc()
.
Identity Server 文档甚至在此处提供了一个示例:http ://docs.identityserver.io/en/latest/quickstarts/3_interactive_login.html#creating-an-mvc-client
一个非常简单的示例如下所示:
public void ConfigureServices(IServiceCollection services)
{
// other configuration...
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
})
.AddCookie()
.AddOpenIdConnect(options =>
{
options.Authority = Configuration["auth:oidc:authority"];
options.ClientId = Configuration["auth:oidc:clientid"];
});
// other configuration...
}
public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
{
// other configuration...
app.UseAuthentication();
// other configuration...
}
推荐阅读
- python-3.x - 如何在 Django 项目中使用 Celery 4.4.6 crontab 计划
- sql-server - 使用 trim() 后 Azure SQL 数据库不显示为动态掩码模式
- vim - 有没有办法模拟 Vimscript/VimL 函数?
- spring-boot - Apache Ignite:Hibernate 5 二级缓存
- jenkins - 如何为 sh 命令隐藏管道中的敏感数据
- java - 通过我自己的 RESTful API 路由 API 调用是否被视为可接受的策略?
- autotools - m4 宏和 shell 重定向
- javascript - 在 Wordpress 中自定义 HTML、CSS、JS、PHP 页面
- r - 为什么将 inputId 添加到我闪亮的应用程序的 pickerInput 段会破坏我的代码?
- css - object-fit:根据 Mozilla 和 caniuse 覆盖兼容性差异