首页 > 解决方案 > 如何在 asp.net core 中使用 JWT 登录用户

问题描述

我有一个 IdentityServer4 实例。

此 IdentityServer4 实例由单独的 asp.net 核心 Web 应用程序(来自 http 登录操作)调用以接收 JWT。

我如何使用此 JWT 来“登录”用户?

标签: asp.net-corejwt

解决方案


您想要进行身份验证的客户端应用程序应该通过 Open ID Connect (OIDC) 协议与 Identity Server 应用程序进行通信。Asp.net 核心支持开箱即用AddAuthentication().AddOpenIdConnect(),您可以IServiceCollectionStartup.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...
}

推荐阅读