如何在ASP.NET Core中使用JWT登录用户

时间:2019-07-05 05:12:31

标签: asp.net-core jwt

我有一个IdentityServer4实例。

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

该JWT如何“登录”用户?

1 个答案:

答案 0 :(得分:3)

您要进行身份验证的客户端应用程序应通过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...
}