【问题标题】:Dotnet Core 2.0 Authorization failed for user: (null)用户的 Dotnet Core 2.0 授权失败:(空)
【发布时间】:2018-03-12 11:34:49
【问题描述】:

我的代码与 .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)。 信息:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] 用户授权失败:(空)。 Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息: 用户授权失败:(空)。 信息:Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[3] 过滤器“Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”处的请求授权失败。 Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息: 过滤器请求授权失败 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'。 信息: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:Information: 使用身份验证方案执行 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();
        }
    }
}

【问题讨论】:

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


    【解决方案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();
            }
    

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 2017-12-25
      • 2018-08-14
      • 2018-01-30
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2020-08-02
      • 1970-01-01
      相关资源
      最近更新 更多