尝试通过邮递员调用OWIN OAuth安全的Web Api来获取JWT时,出现“错误”:“ unsupported_grant_type”


72

我已关注本文以实现OAuth授权服务器。但是,当我使用邮递员获取令牌时,响应中出现错误:

“错误”:“ unsupported_grant_type”

我读到某处需要使用来发布Postman中的数据Content-type:application/x-www-form-urlencoded。我已经在Postman中准备了所需的设置:

在此处输入图片说明

但是我的标题是这样的:

在此处输入图片说明

这是我的代码

public class CustomOAuthProvider : OAuthAuthorizationServerProvider
{
    public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
        return Task.FromResult<object>(null);
    }

    public override Task MatchEndpoint(OAuthMatchEndpointContext context)
    {
        if (context.OwinContext.Request.Method == "OPTIONS" && context.IsTokenEndpoint)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Methods", new[] { "POST" });
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "accept", "authorization", "content-type" });
            context.OwinContext.Response.StatusCode = 200;
            context.RequestCompleted();
            return Task.FromResult<object>(null);
        }
        return base.MatchEndpoint(context);       
    }

    public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        string allowedOrigin = "*";

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Headers", new[] { "Content-Type" });

        Models.TheUser user = new Models.TheUser();
        user.UserName = context.UserName;
        user.FirstName = "Sample first name";
        user.LastName = "Dummy Last name";

        ClaimsIdentity identity = new ClaimsIdentity("JWT");

        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
        foreach (string claim in user.Claims)
        {
            identity.AddClaim(new Claim("Claim", claim));    
        }

        var ticket = new AuthenticationTicket(identity, null);
        context.Validated(ticket);
    }
}

public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
    private readonly string _issuer = string.Empty;

    public CustomJwtFormat(string issuer)
    {
        _issuer = issuer;
    }

    public string Protect(AuthenticationTicket data)
    {
        string audienceId = ConfigurationManager.AppSettings["AudienceId"];
        string symmetricKeyAsBase64 = ConfigurationManager.AppSettings["AudienceSecret"];
        var keyByteArray = TextEncodings.Base64Url.Decode(symmetricKeyAsBase64);
        var signingKey = new HmacSigningCredentials(keyByteArray);
        var issued = data.Properties.IssuedUtc;
        var expires = data.Properties.ExpiresUtc;
        var token = new JwtSecurityToken(_issuer, audienceId, data.Identity.Claims, issued.Value.UtcDateTime, expires.Value.UtcDateTime, signingKey);
        var handler = new JwtSecurityTokenHandler();
        var jwt = handler.WriteToken(token);
        return jwt;
    }

    public AuthenticationTicket Unprotect(string protectedText)
    {
        throw new NotImplementedException();
    }
}

在上面的CustomJWTFormat类中,只有构造函数中的断点才会命中。在CustomOauth类中,永远不会命中GrantResourceOwnerCredentials方法中的断点。其他人做。

启动类:

public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

        HttpConfiguration config = new HttpConfiguration();
        WebApiConfig.Register(config);

        ConfigureOAuthTokenGeneration(app);
        ConfigureOAuthTokenConsumption(app);

        app.UseWebApi(config);
    }

    private void ConfigureOAuthTokenGeneration(IAppBuilder app)
    {
        var OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            //For Dev enviroment only (on production should be AllowInsecureHttp = false)
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/oauth/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new CustomOAuthProvider(),
            AccessTokenFormat = new CustomJwtFormat(ConfigurationManager.AppSettings["Issuer"])
        };

        // OAuth 2.0 Bearer Access Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
    }

    private void ConfigureOAuthTokenConsumption(IAppBuilder app)
    {
        string issuer = ConfigurationManager.AppSettings["Issuer"]; 
        string audienceId = ConfigurationManager.AppSettings["AudienceId"];
        byte[] audienceSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["AudienceSecret"]);

        // Api controllers with an [Authorize] attribute will be validated with JWT
        app.UseJwtBearerAuthentication(
            new JwtBearerAuthenticationOptions
            {
                AuthenticationMode = AuthenticationMode.Active,
                AllowedAudiences = new[] { audienceId },
                IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
                {
                    new SymmetricKeyIssuerSecurityTokenProvider(issuer, audienceSecret)
                }
            });
    }
}

我需要Content-type:application/x-www-form-urlencoded在网络api代码中的其他地方进行设置吗?有什么事吗 请帮忙。


我不想通过用户名密码,我想使用外部提供商(例如twitter用户密钥和用户密钥)进行验证,我该怎么办?
Neo:

为此,尽管您的问题和最终答案实际上并不是我想要的,但内联代码段似乎已经为我解决了。我正在为受客户端ID /秘密保护的OPTIONS身份验证令牌点苦苦挣扎。你救了我!
参议员

确保您的授权码尚未过期。我在用邮递员测试我的代码。该请求包含旧的授权代码。
Paramvir Singh Karwal

Answers:


149

响应有点晚-但是万一将来有人遇到问题...

从上面的屏幕截图-似乎您是将url数据(用户名,密码,grant_type)添加到标头中,而不是添加到body元素中。

单击主体选项卡,然后选择“ x-www-form-urlencoded”单选按钮,下面应有一个键值列表,您可以在其中输入请求数据


3
我该如何通过角度服务电话提出相同的请求?
Parshwa Shah

我犯了同样的错误。通过在当前版本的Postman中选择“ x-www-form-urlencoded”,关键字“ Content-Type”将自动添加到“标题”选项卡中。其他参数应添加在“主体”选项卡中。
Alielson Piffer

为什么它不能使用body的表单数据代替x-www-form-urlencoded?
Bambam Deo

60

使用Postman,选择“正文”选项卡,然后选择原始选项,然后键入以下内容:

grant_type=password&username=yourusername&password=yourpassword

对于包含特殊字符的正文,例如p@ssword您是否需要将“ @”替换为“%40”?
greg

1
@GregDegruy看起来只有密码必须经过url编码。用户名可以包含“ @”,但我必须用%26替换我的密码中的&
彼得

21
  1. 注意网址:(localhost:55828/token不是localhost:55828/API/token
  2. 注意请求数据。它不是json格式,只是纯数据,没有双引号。 userName=xxx@gmail.com&password=Test123$&grant_type=password
  3. 注意内容类型。内容类型:“ application / x-www-form-urlencoded”(非内容类型:“ application / json”)
  4. 当您使用JavaScript进行发布请求时,可以使用以下方法:

    $http.post("localhost:55828/token", 
      "userName=" + encodeURIComponent(email) +
        "&password=" + encodeURIComponent(password) +
        "&grant_type=password",
      {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
    ).success(function (data) {//...
    

请参阅以下Postman的屏幕截图:

邮递员要求

邮递员请求标头


3
我正在发送与上述相同的请求,但仍收到invalid_grant。请提出解决方案。
sadhana

好答案!步骤有所帮助。
OverMars

5

如果您使用的是AngularJS,则需要将body参数作为字符串传递:

    factory.getToken = function(person_username) {
    console.log('Getting DI Token');
    var url = diUrl + "/token";

    return $http({
        method: 'POST',
        url: url,
        data: 'grant_type=password&username=myuser@user.com&password=mypass',
        responseType:'json',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
    });
};

2
同样与角度2有关,我尝试将data变量作为对象传递,但遇到错误,将数据作为字符串传递解决了它。
jonathana '18


1

旧问题,但对于 angular 6,这需要在您使用HttpClient 时完成,我在此处公开公开令牌数据,但是如果通过只读属性访问它会很好。

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { delay, tap } from 'rxjs/operators';
import { Router } from '@angular/router';


@Injectable()
export class AuthService {
    isLoggedIn: boolean = false;
    url = "token";

    tokenData = {};
    username = "";
    AccessToken = "";

    constructor(private http: HttpClient, private router: Router) { }

    login(username: string, password: string): Observable<object> {
        let model = "username=" + username + "&password=" + password + "&grant_type=" + "password";

        return this.http.post(this.url, model).pipe(
            tap(
                data => {
                    console.log('Log In succesful')
                    //console.log(response);
                    this.isLoggedIn = true;
                    this.tokenData = data;
                    this.username = data["username"];
                    this.AccessToken = data["access_token"];
                    console.log(this.tokenData);
                    return true;

                },
                error => {
                    console.log(error);
                    return false;

                }
            )
        );
    }
}


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.