gpt4 book ai didi

c# - 无法验证 UseJwtBearerAuthentication 中的 token 。授权被拒绝

转载 作者:太空狗 更新时间:2023-10-30 01:15:13 26 4
gpt4 key购买 nike

使用单个 asp.net(4.6.1) web 项目,显然我无法验证在同一服务器上生成的 jwt token 。
Startup.cs:

        var secret = Encoding.UTF8.GetBytes("12341234123412341234");
var jwtFormatter = new CustomJwtFormat("Any", "local", secret);

// This part checks the tokens
app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
AuthenticationMode = AuthenticationMode.Active, // Block requests
AllowedAudiences = new []{"Any"},
TokenValidationParameters = new TokenValidationParameters
{
IssuerSigningKey = new InMemorySymmetricSecurityKey(secret),
ValidAudience = "Any",
ValidIssuer = "local"
}
});

// This part issues tokens
app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = false,
TokenEndpointPath = new PathString("/auth"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new CustomOAuthProvider(),
AccessTokenFormat = jwtFormatter,
RefreshTokenFormat = jwtFormatter

});

app.UseWebApi(config);

生成 token 的类看起来像

public class CustomJwtFormat : ISecureDataFormat<AuthenticationTicket>
{
private readonly string _allowedAudience;
private readonly string _issuer;
private readonly byte[] _jwtTokenSignKey;

public CustomJwtFormat(string allowedAudience, string issuer, byte[] jwtTokenSignKey)
{
_allowedAudience = allowedAudience;
_issuer = issuer;
_jwtTokenSignKey = jwtTokenSignKey;
}

public string Protect(AuthenticationTicket data)
{
if (data == null) throw new ArgumentNullException(nameof(data));

var signingCredentials = new SigningCredentials
(
new InMemorySymmetricSecurityKey(_jwtTokenSignKey),
"http://www.w3.org/2001/04/xmldsig-more#hmac-sha256",
"http://www.w3.org/2001/04/xmlenc#sha256"
);

return new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
_issuer,
_allowedAudience,
data.Identity.Claims,
DateTime.UtcNow, DateTime.UtcNow.AddMinutes(10),
signingCredentials
));

}

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

我从 /auth 收到的 token 看起来有效,并通过了 jwt.io 上的调试器(没有标记 base64 用于签名) image

但是 UseJwtBearerAuthentication 拒绝验证 token 。 image

这可能是什么原因?

此外,我已经尝试在没有 [Authorize] 的 Controller 中手动验证相同的 token ,它会完美地验证:

        var t = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6IjEiLCJpc3MiOiJsb2NhbCIsImF1ZCI6IkFueSIsImV4cCI6MTQ3MjkxMDcwMSwibmJmIjoxNDcyOTEwMTAxfQ.ipSrRSGmje7wfzERsd-M1IDFJnN99AIC4Hs7YX4FIeI";
var TokenHandler = new JwtSecurityTokenHandler();;
var key = Encoding.UTF8.GetBytes("12341234123412341234");
SecurityToken validatedToken;
TokenValidationParameters paras = new TokenValidationParameters()
{
IssuerSigningKey = new InMemorySymmetricSecurityKey(key),
ValidAudience = "Any",
ValidIssuer = "local"
};
TokenHandler.ValidateToken(t, paras, out validatedToken);

欧文 3.0.1.0System.IdentityModel.Tokens.Jwt 4.0.3.308261200

最佳答案

问题不在于 token 验证,而是声明未传递到 [Authorize] 属性正在读取的 Thread.CurrentPrincipal .

在 webapi 配置中:

config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(DefaultAuthenticationTypes.ExternalBearer));

在启动配置中:

app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
{
AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
...
});

app.UseJwtBearerAuthentication1(new JwtBearerAuthenticationOptions()
{
AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
..
});

在 OAuthAuthorizationServerProvider 的 GrantResourceOwnerCredentials 中:
使用相同的身份验证类型,您可以从 context.Options

中读取
var identity = new ClaimsIdentity(youClaimsList, context.Options.AuthenticationType);
context.Validated(identity);

并确保所有四个 位置都与AuthenticationType 具有相同的字符串。如果 HostAuthenticationFilter 将不同的 authenticationType 作为输入,它不会将声明从 owin 传递到 webapi。

关于c# - 无法验证 UseJwtBearerAuthentication 中的 token 。授权被拒绝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307640/

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