首页 > 解决方案 > Microsoft.Owin.Security.OAuth.OAuthAuthorizationServerProvider - 尝试从 Postman 生成令牌时,clientId 和 clientSecret 为空

问题描述

我正在为我的 asp.net web api 2 应用程序使用 OWIN 安全性,这是我的身份验证启动类设置。

 public void ConfigureOAuth(IAppBuilder app)
    {

        var oAuthServerOptions = new OAuthAuthorizationServerOptions
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new CustomAuthorizationServerProvider()
        };

        // Token Generation
        app.UseOAuthAuthorizationServer(oAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }

这是CustomAuthorizationServerProvider类实现,

public class CustomAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.TryGetFormCredentials(out var clientId, out var clientSecret);

        if (clientId == "987459827985" && clientSecret == "lkfjldsfjkld")
        {
            context.Validated(clientId);
        }

        return base.ValidateClientAuthentication(context);
    }

    public override Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
    {
        var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
        oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, "TestClient"));
        var ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties());
        context.Validated(ticket);
        return base.GrantClientCredentials(context);
    }
}

现在,在尝试使用 endpoint 生成令牌http://localhost:8080/token时,我的 clientId 和 clientSecret 都为 NULL,因此我得到了"error": "invalid_client". 我在这里缺少什么?

在此处输入图像描述

在此处输入图像描述

编辑:编辑

当我raw用作正文时,我可以看到令牌生成正在工作,并且客户端和秘密都具有价值。为什么它不起作用form-data

在此处输入图像描述

标签: c#asp.net-web-api2owin

解决方案


查看邮递员文档:发送 API 请求

最重要的是:

网站表单通常将数据作为 multipart/form-data 发送到 API。您可以使用表单数据正文选项卡在 Postman 中复制此内容。表单数据允许您发送键值对,并指定内容类型。

通过在网络上进行快速搜索,API 需要有一种特殊类型的处理来绑定multipart/form-data

如何为 multipart/form-data 设置 Web API 控制器

甚至还有一个插件

内容类型很重要。


推荐阅读