配置授权服务器端点

Configure the authorization server endpoint

问题

我们如何使用不记名令牌 ASP.NET 5 使用用户名和密码流程?对于我们的场景,我们想让用户使用 AJAX 调用注册和登录,而无需使用外部登录。

为此,我们需要一个授权服务器端点。 在 ASP.NET 的早期版本中,我们将执行以下操作,然后在 ourdomain.com/Token URL.

处登录
// Configure the application for OAuth based flow
PublicClientId = "self";
OAuthOptions = new OAuthAuthorizationServerOptions
{
    TokenEndpointPath = new PathString("/Token"),
    Provider = new ApplicationOAuthProvider(PublicClientId),
    AccessTokenExpireTimeSpan = TimeSpan.FromDays(14)
};

但是,在当前版本的 ASP.NET 中,以上内容不起作用。我们一直在努力找出新的方法。 aspnet/identity example on GitHub, for instance, configures Facebook, Google, and Twitter authentication but does not appear to configure a non-external OAuth authorization server endpoint, unless that's what AddDefaultTokenProviders() 会,在这种情况下我们想知道提供者的 URL 是什么。

研究

我们从 reading the source here 了解到,我们可以通过在 Startup class 中调用 IAppBuilder.UseOAuthBearerAuthentication 将 "bearer authentication middleware" 添加到 HTTP 管道。这是一个好的开始,尽管我们仍然不确定如何设置其令牌端点。这没有用:

public void Configure(IApplicationBuilder app)
{  
    app.UseOAuthBearerAuthentication(options =>
    {
        options.MetadataAddress = "meta";
    });

    // if this isn't here, we just get a 404
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Hello World.");
    });
}

在前往 ourdomain.com/meta 时,我们刚刚收到我们的 hello world 页面。

进一步的研究表明,我们还可以使用 IAppBuilder.UseOAuthAuthentication 扩展方法,并且它需要一个 OAuthAuthenticationOptions 参数。该参数有一个 TokenEndpoint 属性。因此,虽然我们不确定我们在做什么,但我们尝试了这个,当然没有用。

public void Configure(IApplicationBuilder app)
{
    app.UseOAuthAuthentication("What is this?", options =>
    {
        options.TokenEndpoint = "/token";
        options.AuthorizationEndpoint = "/oauth";
        options.ClientId = "What is this?";
        options.ClientSecret = "What is this?";
        options.SignInScheme = "What is this?";
        options.AutomaticAuthentication = true;
    });

    // if this isn't here, we just get a 404
    app.Run(async context =>
    {
        await context.Response.WriteAsync("Hello World.");
    });
}

换句话说,在转到 ourdomain.com/token 时,没有错误,只是再次出现我们的 hello world 页面。

编辑 (01/28/2021):AspNet.Security.OpenIdConnect.Server 已合并到 OpenIddict as part of the 3.0 update. To get started with OpenIddict, visit documentation.openiddict.com


好吧,让我们回顾一下 OWIN/Katana3 提供的不同 OAuth2 中间件(及其各自的 IAppBuilder 扩展)移植到 ASP.NET 核心:

  • app.UseOAuthBearerAuthentication/OAuthBearerAuthenticationMiddleware:它的名字不是很明显,但它曾经(现在仍然是,因为它已经被移植到 ASP.NET 核心)负责验证访问令牌由 OAuth2 服务器中间件发布。它基本上是 cookie 中间件的令牌对应物,用于保护您的 API。 在 ASP.NET Core 中,它增加了可选的 OpenID Connect 功能(它现在能够从颁发令牌的 OpenID Connect 服务器自动检索签名证书)。

注:从ASP.NETCore beta8开始,现命名为app.UseJwtBearerAuthentication/JwtBearerAuthenticationMiddleware.

  • app.UseOAuthAuthorizationServer/OAuthAuthorizationServerMiddleware:顾名思义,OAuthAuthorizationServerMiddleware是一个OAuth2授权服务器中间件,用于创建和发布访问令牌。 此中间件不会移植到 ASP.NET 核心 : .

  • app.UseOAuthBearerTokens:这个扩展并没有真正对应于一个中间件,只是 app.UseOAuthAuthorizationServerapp.UseOAuthBearerAuthentication 的包装器。它是 ASP.NET 身份包的一部分,只是一种配置 OAuth2 授权服务器和 OAuth2 承载中间件的便捷方式,用于在单个调用中验证访问令牌。 不会移植到ASP.NET核心

ASP.NET Core 将提供一个全新的中间件(我很自豪地说它是我设计的):

  • app.UseOAuthAuthentication/OAuthAuthenticationMiddleware:这个新的中间件是一个通用的 OAuth2 交互式客户端,其行为与 app.UseFacebookAuthenticationapp.UseGoogleAuthentication 完全相同,但它几乎支持任何标准的 OAuth2 提供程序,包括你的。 Google,Facebook 和 Microsoft 提供程序都已更新为继承这个新的基础中间件。

因此,您实际要查找的中间件是 OAuth2 授权服务器中间件,又名 OAuthAuthorizationServerMiddleware.

尽管它被社区的大部分人视为必不可少的组件,但它不会被移植到 ASP.NET Core.

幸运的是,已经有一个直接的替代品:AspNet.Security.OpenIdConnect.Server (https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server)

此中间件是 Katana 3 附带的 OAuth2 授权服务器中间件的高级分支,但它的目标是 OpenID Connect(这是本身基于 OAuth2)。它使用相同的低级方法提供细粒度控制(通过各种通知)并允许您使用自己的框架(Nancy,ASP.NET Core MVC)来提供您的授权页面,就像您可以使用 OAuth2服务器中间件。配置很简单:

ASP.NET核心1.x:

// Add a new middleware validating access tokens issued by the server.
app.UseOAuthValidation();

// Add a new middleware issuing tokens.
app.UseOpenIdConnectServer(options =>
{
    options.TokenEndpointPath = "/connect/token";

    // Create your own `OpenIdConnectServerProvider` and override
    // ValidateTokenRequest/HandleTokenRequest to support the resource
    // owner password flow exactly like you did with the OAuth2 middleware.
    options.Provider = new AuthorizationProvider();
});

ASP.NET核心2.x:

// Add a new middleware validating access tokens issued by the server.
services.AddAuthentication()
    .AddOAuthValidation()

    // Add a new middleware issuing tokens.
    .AddOpenIdConnectServer(options =>
    {
        options.TokenEndpointPath = "/connect/token";

        // Create your own `OpenIdConnectServerProvider` and override
        // ValidateTokenRequest/HandleTokenRequest to support the resource
        // owner password flow exactly like you did with the OAuth2 middleware.
        options.Provider = new AuthorizationProvider();
    });

有一个 OWIN/Katana 3 版本,以及一个支持 .NET 桌面的 ASP.NET Core 版本和 .NET 核心。

不要犹豫,提供 the Postman sample a try to understand how it works. I'd recommend reading the associated blog post,它解释了如何实现资源所有者密码流程。

如果您仍然需要帮助,请随时联系我。 祝你好运!

在@Pinpoint 的帮助下,我们已经将答案的基本内容联系在一起。它显示了组件如何连接在一起而不是一个完整的解决方案。

Fiddler 演示

通过我们的基本项目设置,我们能够在 Fiddler 中进行以下请求和响应。

请求

POST http://localhost:50000/connect/token HTTP/1.1
User-Agent: Fiddler
Host: localhost:50000
Content-Length: 61
Content-Type: application/x-www-form-urlencoded

grant_type=password&username=my_username&password=my_password

回应

HTTP/1.1 200 OK
Cache-Control: no-cache
Pragma: no-cache
Content-Length: 1687
Content-Type: application/json;charset=UTF-8
Expires: -1
X-Powered-By: ASP.NET
Date: Tue, 16 Jun 2015 01:24:42 GMT

{
  "access_token" : "eyJ0eXAiOi ... 5UVACg",
  "expires_in" : 3600,
  "token_type" : "bearer"
}

响应提供了一个不记名令牌,我们可以使用它来访问应用程序的安全部分。

项目结构

这是我们在 Visual Studio 中的项目结构。我们必须将其 Properties > Debug > Port 设置为 50000 以便它充当我们配置的身份服务器。以下是相关文件:

ResourceOwnerPasswordFlow
    Providers
        AuthorizationProvider.cs
    project.json
    Startup.cs

Startup.cs

为了便于阅读,我将 Startup class 分成两个部分。

Startup.ConfigureServices

对于最基本的,我们只需要 AddAuthentication()

public partial class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication();
    }
}

Startup.Configure

public partial class Startup
{
    public void Configure(IApplicationBuilder app)
    {
        JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
        JwtSecurityTokenHandler.DefaultOutboundClaimTypeMap.Clear();

        // Add a new middleware validating access tokens issued by the server.
        app.UseJwtBearerAuthentication(new JwtBearerOptions
        {
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
            Audience = "resource_server_1",
            Authority = "http://localhost:50000/",
            RequireHttpsMetadata = false
        });

        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer(options =>
        {
            // Disable the HTTPS requirement.
            options.AllowInsecureHttp = true;

            // Enable the token endpoint.
            options.TokenEndpointPath = "/connect/token";

            options.Provider = new AuthorizationProvider();

            // Force the OpenID Connect server middleware to use JWT
            // instead of the default opaque/encrypted format.
            options.AccessTokenHandler = new JwtSecurityTokenHandler
            {
                InboundClaimTypeMap = new Dictionary<string, string>(),
                OutboundClaimTypeMap = new Dictionary<string, string>()
            };

            // Register an ephemeral signing key, used to protect the JWT tokens.
            // On production, you'd likely prefer using a signing certificate.
            options.SigningCredentials.AddEphemeralKey();
        });

        app.UseMvc();

        app.Run(async context =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }
}

AuthorizationProvider.cs

public sealed class AuthorizationProvider : OpenIdConnectServerProvider
{
    public override Task ValidateTokenRequest(ValidateTokenRequestContext context)
    {
        // Reject the token requests that don't use
        // grant_type=password or grant_type=refresh_token.
        if (!context.Request.IsPasswordGrantType() &&
            !context.Request.IsRefreshTokenGrantType())
        {
            context.Reject(
                error: OpenIdConnectConstants.Errors.UnsupportedGrantType,
                description: "Only grant_type=password and refresh_token " +
                             "requests are accepted by this server.");

            return Task.FromResult(0);
        }

        // Since there's only one application and since it's a public client
        // (i.e a client that cannot keep its credentials private), call Skip()
        // to inform the server that the request should be accepted without 
        // enforcing client authentication.
        context.Skip();

        return Task.FromResult(0);
    }

    public override Task HandleTokenRequest(HandleTokenRequestContext context)
    {
        // Only handle grant_type=password token requests and let the
        // OpenID Connect server middleware handle the other grant types.
        if (context.Request.IsPasswordGrantType())
        {
            // Validate the credentials here (e.g using ASP.NET Core Identity).
            // You can call Reject() with an error code/description to reject
            // the request and return a message to the caller.

            var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
            identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique identifier]");

            // By default, claims are not serialized in the access and identity tokens.
            // Use the overload taking a "destinations" parameter to make sure 
            // your claims are correctly serialized in the appropriate tokens.
            identity.AddClaim("urn:customclaim", "value",
                OpenIdConnectConstants.Destinations.AccessToken,
                OpenIdConnectConstants.Destinations.IdentityToken);

            var ticket = new AuthenticationTicket(
                new ClaimsPrincipal(identity),
                new AuthenticationProperties(),
                context.Options.AuthenticationScheme);

            // Call SetResources with the list of resource servers
            // the access token should be issued for.
            ticket.SetResources("resource_server_1");

            // Call SetScopes with the list of scopes you want to grant
            // (specify offline_access to issue a refresh token).
            ticket.SetScopes("profile", "offline_access");

            context.Validate(ticket);
        }

        return Task.FromResult(0);
    }
}

project.json

{
  "dependencies": {
    "AspNet.Security.OpenIdConnect.Server": "1.0.0",
    "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.0",
  }

  // other code omitted
}