ASP.NET JSON Web令牌“401 Unauthorized”

前端之家收集整理的这篇文章主要介绍了ASP.NET JSON Web令牌“401 Unauthorized”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用分离的资源和身份验证服务器.
当我成功获得 JSON Web Token时,我使用jwt.io进行检查,所有内容都可以使用令牌格式,这是秘密.

请求具有授权标头:

Authorization: Bearer TOKEN_HERE

响应总是“401 Unauthorized”:

{
  "message": "Authorization has been denied for this request."
}

这是我的资源服务器的Startup.cs

using Microsoft.Owin;
using Microsoft.Owin.Cors;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Jwt;
using Newtonsoft.Json.Serialization;
using Owin;
using System.Web.Http;
using Test.Database;
using Test.Infrastructure;
using Microsoft.WindowsAzure.ServiceRuntime;

[assembly: OwinStartup(typeof(Test.API.Startup))]
namespace Custodesk.API
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => 
                ApplicationDbContext.Create(RoleEnvironment.GetConfigurationSettingValue("sqlConnectionString")));
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            GlobalConfiguration.Configuration.SuppressDefaultHostAuthentication();

            ConfigureOAuthTokenConsumption(app);

            GlobalConfiguration.Configure(config =>
            {
                //global filters
                config.Filters.Add(new AuthorizeAttribute());

                // Web API routes
                config.MapHttpAttributeRoutes();
                config.Routes.MapHttpRoute(
                    name: "DefaultApi",routeTemplate: "{controller}/{action}/{id}",defaults: new { id = RouteParameter.Optional }
                );

                config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            });

            app.UseCors(CorsOptions.AllowAll);

            app.UseWebApi(GlobalConfiguration.Configuration);
        }

        private void ConfigureOAuthTokenConsumption(IAppBuilder app)
        {
            var issuer = "http://localhost";
            var audience = "Universal_application";
            var secret = Helper.GetHash("helper_class_to_get_the_same_hash_as_authentication_server");

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

        }
    }
}

以下是令牌解密的示例:

{
  "typ": "JWT","alg": "HS256"
}
{
  "nameid": "b22a825e-60ce-45ed-b2cb-b2ee46a47936","unique_name": "begunini","role": [
    "Owner","Admin","ManagerViewer"
  ],"iss": "http://localhost","aud": "Universal_application","exp": 1454876502,"nbf": 1454876202
}

我已经检查了秘密,双方都是相同的(身份验证和资源服务器).
观众比赛,发行人也.
已经尝试将System.IdentityModel.Tokens.Jwt降级到版本3.0.2但没有运气

我猜配置顺序有一些问题,但没有任何帮助.

有任何想法吗 ?

解决方法

TL; DR:您是否尝试删除GlobalConfiguration.Configuration.SuppressDefaultHostAuthentication()?

使用此方法时,Web API将删除由Web主机(在您的情况下由JWT承载中间件)注册的主机或中间件创建并添加到OWIN上下文的用户主体.

方法旨在与HostAuthenticationFilter或HostAuthenticationAttribute一起使用,该方法直接调用与指定的身份验证类型对应的身份验证中间件,并在OWIN上下文中保留生成用户主体.

由于您在没有HostAuthenticationAttribute的情况下使用SuppressDefaultHostAuthentication,因此Web API始终会看到未经身份验证的请求,这就是AuthorizeAttribute拒绝它们的原因.

原文链接:https://www.f2er.com/aspnet/247419.html

猜你在找的asp.Net相关文章