用户授权失败:(空) [英] Authorization failed for user: (null)

查看:77
本文介绍了用户授权失败:(空)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为ASP.NET MVC Core使用自定义身份验证,该身份验证不使用 Identity .这是 Startup.cs :

I am using a custom authentication for ASP.NET MVC Core which does not use Identity. This is 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();
    }
}

并在我的控制器中:

[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 

因此,基本上,它可以通过控制器的 Index()方法成功授权用户,但不能在同一控制器的 GetChartData()方法中授权用户.

So basically it successfully authorizes the user in the Index() method of the controller but fails to do so in the GetChartData() method of the same controller.

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService [1] Microsoft.AspNetCore.Authorization.DefaultAuthorizationService [2] 之间似乎有区别,我不理解它是什么以及如何修复.

There seems to be a difference between Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[1] and Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2] and I do not understand what it is and how to fix it.

推荐答案

对于ASP.Net Core 2.0,我在app.UseAuthentication(); docs.microsoft.com/zh-CN/aspnet/core/fundamentals/startup#the-configure-method"rel =" noreferrer> Startup.Configure() 即可解决此问题对我来说是错误的.

For ASP.Net Core 2.0, I added: app.UseAuthentication(); in Startup.Configure() and that resolved this error for me.

参考: Auth 2.0迁移公告

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?}");
    });
}


注意:请确保在UseMvc()之前先调用 UseAuthentication().如注释中所述,microsoft.com/zh-cn/aspnet/core/fundamentals/startup#the-configure-method"rel =" noreferrer> Startup.Configure() .


Note: be sure to call UseAuthentication() before calling UseMvc() in Startup.Configure() as noted in the comments.

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

The order that middleware components are added in the Configure method defines the order in which they're invoked on requests, and the reverse order for the response. This ordering is critical for security, performance, and functionality.

ASP.NET核心文档-> 订购

这篇关于用户授权失败:(空)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆