在ASP中获取访问令牌.净5

本文关键字:访问令牌 获取 ASP | 更新日期: 2023-09-27 18:17:43

我的ASP。. NET 5 (MVC 6 + beta7) web应用程序(MVC + WebAPI)需要从WebAPI登录调用中获取access_token。

到目前为止,我已经为startup.cs创建了以下代码:
app.UseOAuthBearerAuthentication(options => {
    options.AutomaticAuthentication = true;
    options.Audience = "http://localhost:62100/";
    options.Authority = "http://localhost:62100/";
});
我的客户端是:
var login = function ()
{
    var url = "http://localhost:62100/";
    var data = $("#userData").serialize();
    data = data + "&grant_type=password";
    $.post(url, data)
        .success(saveAccessToken)
        .always(showResponse);
    return false;
};

是否需要使用UseOpenIdConnectServer ?如果是这样,我如何使用SigningCredentials,让我得到一个令牌(例如MVC5 ApplicationOAuthProvider)?

请注意,我的网站是简单的演示HTTP网站,我不需要任何SSL

在ASP中获取访问令牌.净5

是否需要使用UseOpenIdConnectServer?

不需要使用AspNet.Security.OpenIdConnect.Server。当然,您可以自由选择其他服务器(如IdentityServer)或自定义解决方案。作为aspnet-contrib背后的主要开发人员,我不是很客观,所以我一定会建议使用app.UseOpenIdConnectServer()

如果是这样,我如何使用SigningCredentials使我获得令牌(例如MVC5 ApplicationOAuthProvider)?

当实现密码并使用默认令牌类型时,不强制注册签名密钥/证书。

你可以这样开始:

ASP。. Core 1.x:

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication();
    }
    public void Configure(IApplicationBuilder app)
    {
        // Add a new middleware validating the encrypted
        // access tokens issued by the OIDC server.
        app.UseOAuthValidation();
        // Add a new middleware issuing tokens.
        app.UseOpenIdConnectServer(options =>
        {
            options.TokenEndpointPath = "/connect/token";
            // Override OnValidateTokenRequest to skip client authentication.
            options.Provider.OnValidateTokenRequest = 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 the request should be
                // accepted without enforcing client authentication.
                context.Skip();
                return Task.FromResult(0);
            };
            // Override OnHandleTokenRequest to support
            // grant_type=password token requests.
            options.Provider.OnHandleTokenRequest = context =>
            {
                // Only handle grant_type=password token requests and let the
                // OpenID Connect server middleware handle the other grant types.
                if (context.Request.IsPasswordGrantType())
                {
                    // Do your credentials validation here.
                    // Note: you can call Reject() with a message
                    // to indicate that authentication failed.
                    var identity = new ClaimsIdentity(context.Options.AuthenticationScheme);
                    identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]");
                    // 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 inserted 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 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);
            };
        });
    }
}

.csproj

<ItemGroup>
  <PackageReference Include="AspNet.Security.OpenIdConnect.Server" Version="1.0.2" />
</ItemGroup>

ASP。. Core 2.x:

Startup.cs

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddAuthentication()
            // Add a new middleware validating the encrypted
            // access tokens issued by the OIDC server.
            .AddOAuthValidation()
            // Add a new middleware issuing tokens.
            .AddOpenIdConnectServer(options =>
            {
                options.TokenEndpointPath = "/connect/token";
                // Override OnValidateTokenRequest to skip client authentication.
                options.Provider.OnValidateTokenRequest = 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.CompletedTask;
                    }
                    // 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 the request should be
                    // accepted without enforcing client authentication.
                    context.Skip();
                    return Task.CompletedTask;
                };
                // Override OnHandleTokenRequest to support
                // grant_type=password token requests.
                options.Provider.OnHandleTokenRequest = context =>
                {
                    // Only handle grant_type=password token requests and let the
                    // OpenID Connect server middleware handle the other grant types.
                    if (context.Request.IsPasswordGrantType())
                    {
                        // Do your credentials validation here.
                        // Note: you can call Reject() with a message
                        // to indicate that authentication failed.
                        var identity = new ClaimsIdentity(context.Scheme.Name);
                        identity.AddClaim(OpenIdConnectConstants.Claims.Subject, "[unique id]");
                        // 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 inserted 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.Scheme.Name);
                        // 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.CompletedTask;
                };
            });
    }
}

.csproj

<ItemGroup>
  <PackageReference Include="AspNet.Security.OpenIdConnect.Server" Version="2.0.0-*" />
</ItemGroup>

您也可以阅读这篇博客文章,它解释了如何实现资源所有者密码授予:http://kevinchalet.com/2016/07/13/creating-your-own-openid-connect-server-with-asos-implementing-the-resource-owner-password-credentials-grant/