用户的Dotnet Core 2.0授权失败:(null)

时间:2017-09-30 23:12:09

标签: asp.net-core .net-core jwt

我的代码与.net core 2.0完美配合。我不确定出了什么问题。应用程序在授权期间抛出错误。错误消息和下面的启动类代码。

>     Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information:
     

政策执行成功。

     
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information:
         

用户授权失败:(null)。         info:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService [2]               用户授权失败:(null)。         Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:     用户授权失败:(null)。         info:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [3]               过滤器“Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”上的请求授权失败。         Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:     过滤器请求的授权失败     'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'。         info:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker [3]               过滤器“Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”上的请求授权失败。         Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:     过滤器请求的授权失败     'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'。         Microsoft.AspNetCore.Mvc.ChallengeResult:信息:使用身份验证方案执行ChallengeResult()。

  
namespace API
{
    public class Startup
    {
        public IConfigurationRoot Configuration { get; }



        public void ConfigureScopeServices(IServiceCollection services)
        {

            services.AddDbContext<AppDbContext>(options => options.UseMySql(Configuration.GetConnectionString("Default")));

        }

        public void ConfigureCompressionService(IServiceCollection services)
        {
            services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest);
            services.AddResponseCompression(options => { options.Providers.Add<GzipCompressionProvider>(); });
        }

        public void ConfigureJWTService(IServiceCollection services)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            var tokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuerSigningKey = true,
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration.GetSection("ApplicationConfiguration:TokenOptions:SigningKey").Value)),

                ValidateIssuer = true,
                ValidIssuer = Configuration.GetSection("ApplicationConfiguration:TokenOptions:Issuer").Value,

                ValidateAudience = true,
                ValidAudience = Configuration.GetSection("ApplicationConfiguration:TokenOptions:Audience").Value,

                ValidateLifetime = true,
                NameClaimType = JwtRegisteredClaimNames.Sub,
                RoleClaimType = "Roles"
            };

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(o =>
            {
                o.TokenValidationParameters = tokenValidationParameters;
            });
        }
        public void ConfigureServices(IServiceCollection services)
        {
            this.ConfigureScopeServices(services);
            this.ConfigureCompressionService(services);
            this.ConfigureJWTService(services);

            services.Configure<ApplicationConfiguration>(Configuration.GetSection("ApplicationConfiguration"));

            //Customized Response Object to Map MiddleWare Response Object
            var formatterSettings = JsonSerializerSettingsProvider.CreateSerializerSettings();
            formatterSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
            ResponseFormatter formatter = new ResponseFormatter(formatterSettings, ArrayPool<Char>.Create());
            services.AddMvcCore()
            .AddApiExplorer()
            .AddAuthorization()
            .AddFormatterMappings()
            .AddDataAnnotations()
            .AddJsonFormatters()
            .AddCors()
            .AddMvcOptions(
                options =>
                {
                    options.OutputFormatters.RemoveType<JsonOutputFormatter>();
                    options.OutputFormatters.Insert(0, formatter);
                }
            );

        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseCors(
                builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
            );

            app.UseMvc();
            app.UseResponseCompression();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

我认为您错过了身份验证中间件:app.UseAuthentication()。

请试试这个:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();
            app.UseCors(
                builder => builder
                .AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
                .AllowCredentials()
            );
            app.UseAuthentication();
            app.UseMvc();
            app.UseResponseCompression();
        }