gpt4 book ai didi

c# - 获取 "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

转载 作者:IT王子 更新时间:2023-10-29 03:43:36 36 4
gpt4 key购买 nike

我关注了this article实现 OAuth 授权服务器。但是,当我使用 post man 获取 token 时,响应中出现错误:

"error": "unsupported_grant_type"

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

enter image description here

然而我的标题是这样的:

enter image description here

这是我的代码

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)
}
});
}
}

我是否需要在 Web API 代码的其他地方设置 Content-type:application/x-www-form-urlencoded?有什么问题吗?请帮忙。

最佳答案

回复有点晚了 - 但万一以后有人遇到这个问题......

从上面的屏幕截图来看 - 似乎您正在将 url 数据(用户名、密码、grant_type)添加到 header 而不是正文元素。

点击正文标签,然后选择“x-www-form-urlencoded”单选按钮,下面应该有一个键值列表,您可以在其中输入请求数据

关于c# - 获取 "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29360349/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com