c# - 在 ASP.Net Web Api 2.0 中使用 OAuth 令牌
问题描述
我使用 ASP.Net Web Api 2.0 创建了一个全新的 WebService,并尝试使用基于 OAuth JWT 令牌的授权。我已经使用 OWIN 完成了所有基本连接,但是当我使用 [Authorize] 属性时,它会失败,即使是有效令牌也是如此。你能帮我吗。
编辑:我缩小了问题的范围。似乎密钥是 RS256,而 SymmetricKeyIssuerSecurityKeyProvider 没有处理这个问题……或者我向密钥提供者传递了错误的信息。任何想法如何解决这个问题?
这是我的startup.cs的代码
using System.Configuration;
using System.Web.Http;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Owin;
using Microsoft.AspNet.Identity;
namespace SecuredApi
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
var config = ConfigureWebApi();
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
private HttpConfiguration ConfigureWebApi()
{
var config = new HttpConfiguration();
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter("Bearer"));
config.MapHttpAttributeRoutes();
return config;
}
private void ConfigureOAuth(IAppBuilder app)
{
var issuer = ConfigurationManager.AppSettings.Get("Issuer");
var audience = ConfigurationManager.AppSettings.Get("Audience");
var secret = ConfigurationManager.AppSettings.Get("Secret");
// Api controllers with an [Authorize] attribute will be validated with JWT
var jwtBearerAuthenticationOptions = new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
AuthenticationType = DefaultAuthenticationTypes.ExternalBearer,
AllowedAudiences = new[] { audience },
IssuerSecurityKeyProviders = new IIssuerSecurityKeyProvider[]
{
new SymmetricKeyIssuerSecurityKeyProvider(issuer, secret)
}
};
app.UseJwtBearerAuthentication(
jwtBearerAuthenticationOptions);
}
}
}
解决方案
推荐阅读
- html - Flexbox 列在 IE11 中无法正确考虑包装内容
- jenkins - Jenkins Gradle 失败,无法将缓存值写入“/home/bldadm/.gradle/daemon/4.8/registry.bin”
- perl - 如何在perl中将字节数组转换为int64
- javascript - Google Apps 脚本:如何从二维数组中删除特定字符
- javascript - Javascript 在页面加载时隐藏 div 在按钮之间切换
- php - Laravel 7 中的分页 + URL 参数
- selenium-webdriver - 使用代理 InvalidArgumentError 运行 webdriver
- mongodb - 将 2 个数组对象合并为 1 个
- c# - 如何检查是否已在 Blazor 中设置属性?
- javascript - Vue.js 将数组中的值发送到端点的问题