首页 > 解决方案 > 在 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);

        }
    }
}

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

解决方案


推荐阅读