单页应用程序模板获取承载令牌功能不适用于Grant_type密码invalid_client错误

问题描述 投票:0回答:1

我在Visual Studio 2019中实现了默认的单页应用程序模板,因为我认为这是为webApi实施良好授权的最简单方法。但是,通过邮递员调用时,用于获取webApi承载令牌的Token函数返回以下错误。

"error": "Invalid_client"

我打赌我可能缺少一些我需要启用的配置设置,但是一些广泛的Google搜索未显示任何工作结果。任何人都知道要真正使这项工作还缺少什么?

enter image description here

后面的默认代码是Startup.Auth.cs

static Startup()
{
    PublicClientId = "Web";

    OAuthOptions = new OAuthAuthorizationServerOptions
    {
        TokenEndpointPath = new PathString("/Token"),
        AuthorizeEndpointPath = new PathString("/Account/Authorize"),
        Provider = new ApplicationOAuthProvider(PublicClientId),
        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        AllowInsecureHttp = true
    };
}

public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

public static string PublicClientId { get; private set; }

public void ConfigureAuth(IAppBuilder app)
{
    app.bunchofotherregistrationsfordefaultapp();

    // Enable the application to use bearer tokens to authenticate users
    app.UseOAuthBearerTokens(OAuthOptions);
}
c# asp.net-web-api oauth-2.0 owin bearer-token
1个回答
0
投票

我绝对不推荐使用SPA模板来设置WebApi授权,但是如果您想...


要完成此任务,您需要在ApplicationOAuthProvider中覆盖2个方法:

public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
    context.Validated(); // Set up your context to be valid every time
}

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" }); // Disable CORS policies
    var identity = new ClaimsIdentity(context.Options.AuthenticationType);

    identity.AddClaim(new Claim("email", context.UserName)); // Add required claims you want to encrypt in bearer token

    context.Validated(identity); // Return valid token
}

您可以通过这两种方法更改验证或授予资源逻辑来完成授权工作流程。至少在没有任何其他条件的情况下,我们可以收到有效的访问令牌。

© www.soinside.com 2019 - 2024. All rights reserved.