Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/279.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 用户授权失败:(null)_C#_Asp.net Core - Fatal编程技术网

C# 用户授权失败:(null)

C# 用户授权失败:(null),c#,asp.net-core,C#,Asp.net Core,我正在使用ASP.NET MVC核心的自定义身份验证,它不使用标识。这是Startup.cs: public class Startup { public IConfiguration Configuration { get; set; } // Configure IoC container // https://docs.asp.net/en/latest/fundamentals/dependency-injection.html public void

我正在使用ASP.NET MVC核心的自定义身份验证,它不使用
标识
。这是
Startup.cs

public class Startup
{
    public IConfiguration Configuration { get; set; }

    // Configure IoC container
    // https://docs.asp.net/en/latest/fundamentals/dependency-injection.html
    public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<AppSettings>(options => Configuration.GetSection(nameof(AppSettings)).Bind(options));

        // https://docs.asp.net/en/latest/security/anti-request-forgery.html
        services.AddAntiforgery(options => options.CookieName = options.HeaderName = "X-XSRF-TOKEN");

        services.AddDbContext<DbSesamContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("SesamConnection"));
        });

        services.AddDbContext<TerminalDbContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("TerminalConnection"));
        });

        services.AddMvcCore()
            .AddAuthorization()
            .AddViews()
            .AddRazorViewEngine()
            .AddJsonFormatters();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory factory)
    {
        // Configure logging
        // https://docs.asp.net/en/latest/fundamentals/logging.html
        factory.AddConsole(Configuration.GetSection("Logging"));
        factory.AddDebug();

        // Serve static files
        // https://docs.asp.net/en/latest/fundamentals/static-files.html
        app.UseStaticFiles();

        // Enable external authentication provider(s)
        // https://docs.asp.net/en/latest/security/authentication/sociallogins.html
        //app.UseIdentity();

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationScheme = "ResWebAuth",
            LoginPath = new PathString("/login"),
            AccessDeniedPath = new PathString("/unauthorized/"),
            AutomaticAuthenticate = true,
            AutomaticChallenge = true,
        });

        // Configure ASP.NET MVC
        // https://docs.asp.net/en/latest/mvc/index.html
        app.UseMvc(routes =>
        {
            routes.MapRoute("default", "{*url}", new { controller = "Home", action = "Index" });
        });
    }

    public static void Main()
    {
        var cwd = Directory.GetCurrentDirectory();
        var web = Path.GetFileName(cwd) == "server" ? "../public" : "public";

        var host = new WebHostBuilder()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseWebRoot(web)
            .UseKestrel()
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}
因此,基本上,它在控制器的
Index()
方法中成功地授权了用户,但在同一控制器的
GetChartData()
方法中没有这样做


Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
之间似乎存在差异,我不明白它是什么以及如何修复它

对于ASP.NETCore2.0,我添加了:
app.UseAuthentication()中,这为我解决了此错误

参考:


注意:在中调用
UseMvc()
之前,请务必按照注释中的说明调用
UseAuthentication()

在Configure方法中添加中间件组件的顺序定义了它们在请求中被调用的顺序,以及响应的相反顺序。这种排序对于安全性、性能和功能至关重要


Source->->

为什么不使用
AddMvc
而调用
AddMvcCore
?以下调用执行
AddMvc
所做的操作,因此没有理由在此处使用
AddMvcCore
这是我使用的默认设置。您可以发布没有构造函数的完整启动类吗?发布没有构造函数的完整启动类。尝试改用AddMvc,这样可以解决问题(请参阅)谢谢。对我来说,我使用的是
app.UseAuthentication()在方法的最后。我把那行移到了方法体的顶部,它成功了
[Authorize]
public class HomeController : Controller
{
    public async Task<IActionResult> Index()
    {
        ...

        return View();
    }

    [HttpGet("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login(string ReturnUrl)
    {
        ...

        return View();
    }

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<IActionResult> Login(LoginInfo loginInfo)
    {
        if (LoginUser(loginInfo.Username, loginInfo.Password))
        {
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, loginInfo.Username),
                    new Claim("DbVersion", loginInfo.Terminal.SesamDbVersion),
                    new Claim("DbUrl", loginInfo.Terminal.SesamDbUrl),
                    new Claim("DbName", loginInfo.Terminal.SesamDbName),
                    new Claim("DbUsername", loginInfo.Terminal.SesamDbUserName),
                    new Claim("DbPasswordHash", loginInfo.Terminal.SesamDbPasswordHash),
                };

            var userIdentity = new ClaimsIdentity(claims, "login");

            ClaimsPrincipal principal = new ClaimsPrincipal(userIdentity);
            await HttpContext.Authentication.SignInAsync("ResWebAuth", principal);

            //Just redirect to our index after logging in. 
            return Redirect("/");
        }
        return View();
    }

    [HttpGet("getchartdata")]
    //[AllowAnonymous]
    public JsonResult GetChartData()
    {
        ...
    }
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[3]
      HttpContext.User merged via AutomaticAuthentication from authenticationScheme: ResWebAuth.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1]
      Authorization was successful for user: admin.

...

info: Microsoft.AspNetCore.Hosting.Internal.WebHost[1]
      Request starting HTTP/1.1 GET http://localhost:5000/getchartdata/
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: ResWebAuth was challenged.
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[2]
      Executed action Server.Controllers.HomeController.GetChartData (server) in 5.2905ms
info: Microsoft.AspNetCore.Hosting.Internal.WebHost[2]
      Request finished in 10.1037ms 302 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
        app.UseBrowserLink();
    }
    else
    {
        app.UseExceptionHandler("/Error");
    }

    app.UseStaticFiles();

    app.UseAuthentication();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller}/{action=Index}/{id?}");
    });
}