【问题标题】:Microsoft.AspNetCore.Authorization.DefaultAuthorizationService - Authorization failedMicrosoft.AspNetCore.Authorization.DefaultAuthorizationService - 授权失败
【发布时间】:2020-04-03 22:05:21
【问题描述】:

我有什么:

我必须在去年开发的 Web 应用程序上工作,这不是我自己开发的。它由 Web 服务后端和 Web 应用程序前端组成。后端使用 C# 7 编写,在 .NET Core 2.1 运行时上运行并使用 ASP.NET Core MVC 框架。前端是一个用 HTML 5、CSS3、TypeScript 和 React 编写的 Web 应用程序。

我想要什么:

我想在我的 PC 上设置一个开发环境(使用 windows 10 作为操作系统)。

我做了什么:

我运行 webpack-dev-server 来为 http://localhost:8080 提供前端服务。然后我在 Visual Studio 中使用 ASP.NET Core 运行后端,以在 http://localhost:44311 处提供 Web 服务。 然后我到达http://localhost:8080 主页中的登录表单。

问题:

在登录阶段,我收到以下错误(我使用的是有效的用户名和密码):

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action method MyProject.Controllers.AuthenticationController.Login (MyProject), returned result Microsoft.AspNetCore.Mvc.OkResult in 549.6866ms.
Microsoft.AspNetCore.Mvc.StatusCodeResult:Information: Executing HttpStatusCodeResult, setting HTTP status code 200
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action MyProject.Controllers.AuthenticationController.Login (MyProject) in 620.9287ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 634.4833ms 200 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 OPTIONS http://localhost:44311/Authentication/GetUser  
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution successful.
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 2.9016ms 204 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44311/Authentication/GetUser application/json 
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution successful.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Route matched with {action = "GetUser", controller = "Authentication"}. Executing controller action with signature Microsoft.AspNetCore.Mvc.IActionResult GetUser() on controller MyProject.Controllers.AuthenticationController (MyProject).
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:Information: Authorization failed.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
Microsoft.AspNetCore.Mvc.ChallengeResult:Information: Executing ChallengeResult with authentication schemes (Cookies).
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationHandler:Information: AuthenticationScheme: Cookies was challenged.
Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:Information: Executed action MyProject.Controllers.AuthenticationController.GetUser (MyProject) in 25.582ms
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 33.6489ms 302 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 OPTIONS http://localhost:44311/Account/Login?ReturnUrl=%2FAuthentication%2FGetUser  
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution successful.
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 3.2166ms 204 
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request starting HTTP/1.1 GET http://localhost:44311/Account/Login?ReturnUrl=%2FAuthentication%2FGetUser application/json 
Microsoft.AspNetCore.Cors.Infrastructure.CorsService:Information: Policy execution successful.
Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: Request finished in 2.7855ms 404 

这是我的 Startup.cs

    public class Startup
    {
        private readonly IHostingEnvironment _env;
        private readonly IConfiguration _config;

        public Startup(IHostingEnvironment env, IConfiguration config)
        {
            _env = env;
            _config = config;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            JwtConfiguration jwtConfiguration = _config.GetSection("JwtConfiguration").Get<JwtConfiguration>();
            CustomJwtDataFormat jwtDataFormat = CustomJwtDataFormat.Create(jwtConfiguration);

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddSingleton<IConfiguration>(_config);
            services.AddSingleton<IEmailConfiguration>(_config.GetSection("EmailConfiguration").Get<EmailConfiguration>());
            services.AddSingleton(new LogService(_config.GetSection("AzureLogConfiguration").Get<AzureLogConfiguration>()));
            services.AddSingleton(jwtDataFormat);
            services.AddAuthentication().AddCookie(options => {
                options.Cookie.Name = AuthenticationCookie.COOKIE_NAME;
                options.TicketDataFormat = jwtDataFormat;
            });

            Database.ConnectionString = _config["ConnectionStrings:PostgresDatabase"];
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();
            configurationBuilder.SetBasePath(env.ContentRootPath);
            configurationBuilder.AddJsonFile("appsettings.json", false, true);

            if (env.IsDevelopment()) {
                app.UseCors(
                    builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
                );
                app.UseDeveloperExceptionPage();
                configurationBuilder.AddUserSecrets<Startup>();
            }
            else {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
            app.UseMvc(routes => {
                routes.MapRoute(name: "default", template: "{controller=Site}/{action=Index}");
            });
        }
    }

AuthenticationController.cs(用于在登录阶段对用户进行身份验证):

    public class AuthenticationController : Controller
    {
        private readonly IEmailConfiguration _emailConfiguration;
        private readonly LogService _logService;
        private readonly CustomJwtDataFormat _jwt;

        public AuthenticationController(IEmailConfiguration emailConfiguration, LogService logService, CustomJwtDataFormat jwt)
        {
            _emailConfiguration = emailConfiguration;
            _logService = logService;
            _jwt = jwt;
        }

        [AllowAnonymous]
        public IActionResult Login([FromBody] LoginNto loginNto)
        {
            string requestString = string.Format("Username: '{0}', Type: '{1}'", loginNto.Email, loginNto.Type);
            try
            {
                var requestType = ToLoginType(loginNto.Type);
                var userType = UsersMapper.GetUserType(loginNto.Email, loginNto.Pass);
                if (userType != requestType)
                    throw new UnauthorizedAccessException();
                AuthenticationCookie.CreateAndAddToResponse(HttpContext, loginNto.Email, _jwt);
                _logService.RequestResponse("[Authentication/Login]", HttpContext.Connection.RemoteIpAddress, null, requestString, Ok().StatusCode);
                return Ok();
            }
            catch (UnauthorizedAccessException e)
            {
                _logService.RequestResponse("[Authentication/Login]", HttpContext.Connection.RemoteIpAddress, null, requestString, Unauthorized().StatusCode, e);
                return Unauthorized();
            }
            catch (Exception e)
            {
                _logService.RequestResponse("[Authentication/Login]", HttpContext.Connection.RemoteIpAddress, null, requestString, 500, e);
                return StatusCode(500);
            }
        }

        [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
        public IActionResult GetUser()
        {
            try
            {
                User user = UsersMapper.Get(AuthenticationCookie.GetAuthenticatedUserEmail(HttpContext, _jwt));
                _logService.RequestResponse("[Authentication/GetUser]", HttpContext.Connection.RemoteIpAddress, AuthenticationCookie.GetAuthenticatedUserEmail(HttpContext, _jwt), null, Ok().StatusCode);
                return Ok(Json(user.ForNet()));
            }
            catch (UnauthorizedAccessException e)
            {
                _logService.RequestResponse("[Authentication/GetUser]", HttpContext.Connection.RemoteIpAddress, AuthenticationCookie.GetAuthenticatedUserEmail(HttpContext, _jwt), null, Unauthorized().StatusCode, e);
                return Unauthorized();
            }
            catch (Exception e)
            {
                _logService.RequestResponse("[Authentication/GetUser]", HttpContext.Connection.RemoteIpAddress, AuthenticationCookie.GetAuthenticatedUserEmail(HttpContext, _jwt), null, 500, e);
                return StatusCode(500);
            }
        }
    }

AuthenticationCookie.cs(用来管理JWT cookie……我想……):

    public class AuthenticationCookie
    {
        public const string COOKIE_NAME = "authentication_cookie";

        public static void CreateAndAddToResponse(HttpContext httpContext, string email, CustomJwtDataFormat jwtDataFormat) {
            httpContext.Response.Cookies.Append(COOKIE_NAME, jwtDataFormat.GenerateToken(email));
        }

        public static string GetAuthenticatedUserEmail(HttpContext httpContext, CustomJwtDataFormat jwt) {
            var tokenValue = httpContext.Request.Cookies[COOKIE_NAME];
            var authenticationTicket = jwt.Unprotect(tokenValue);
            return authenticationTicket.Principal.Claims.First().Value;
        }

        public static void Delete(HttpContext httpContext) {
            httpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        }
    }

【问题讨论】:

  • 您在启动 Web 服务时何时收到此错误?
  • 能否请您提供Startup.cs的代码? /Account/Login 是什么?有 AccountControllerLogin Action 吗?还是您使用默认的Identity
  • 我通过整合Startup.csAuthenticationController.cs的代码修改了问题(这是我的访问控制器)。问题出现在登录阶段(我使用的是有效用户)。

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


【解决方案1】:

原因

根本原因是您没有在 UseAuthentication() 之前添加 UseMvc()

app.UseAuthentication(); // 必须在 UseMvc() 之前添加这一行 app.UseMvc(路由 => {...}); 结果,即使用户已经登录,ASP.NET Core 也不会为用户创建用户主体。然后您收到以下消息:

Microsoft.AspNetCore.Authorization.DefaultAuthorizationService:信息:授权失败。

Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker:信息:过滤器“Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter”处的请求授权失败。

Microsoft.AspNetCore.Mvc.ChallengeResult:Information: 使用身份验证方案 (Cookie) 执行 ChallengeResult

由于您没有为 cookie 配置登录路径:

services.AddAuthentication().AddCookie(options => {
    options.Cookie.Name = AuthenticationCookie.COOKIE_NAME;
    options.TicketDataFormat = jwtDataFormat;
});

所以它使用默认值,即/Account/Login。但是你没有AccountControllerLogin这样的action方法,你得到的响应是404:

Microsoft.AspNetCore.Hosting.Internal.WebHost:Information: 请求开始 HTTP/1.1 GET http://localhost:44311/Account/Login?ReturnUrl=%2FAuthentication%2FGetUser application/json

Microsoft.AspNetCore.Cors.Infrastructure.CorsService:信息:策略执行成功。

Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求在 2.7855 毫秒内完成 404

如何解决

  1. UseMvc() 之前添加UseAuthentication()
    app.UseAuthentication();  // MUST add this line before UseMvc()
    app.UseMvc(routes => {...});
    
  2. 如果您没有,请创建一个控制器/视图供用户登录。然后告诉 ASP.NET Core 如何在 Startup 中重定向用户:

    services.AddAuthentication().AddCookie(options => {
        options.Cookie.Name = AuthenticationCookie.COOKIE_NAME;
        options.TicketDataFormat = jwtDataFormat;
        options.LoginPath= "/the-path-to-login-in";  // change this line
    });
    

[编辑]

  1. 您的Login([FromBody] LoginNto loginNto) 方法接受HttpGet 请求,但期望得到一个主体。 HTTP Get 根本没有正文。你需要把它改成HttpPost:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login([FromBody] LoginNto loginNto)
    {
        ...
    }
    
  2. 用户登录的方式似乎不正确。更改您的 Login() 方法以发送标准 cookie,如下所示:

    [HttpPost]
    [AllowAnonymous]
    public async Task<IActionResult> Login([FromBody] LoginNto loginNto)
    {
        string requestString = string.Format("Username: '{0}', Type: '{1}'", loginNto.Email, loginNto.Type);
        try
        {
            ...
            if (userType != requestType)
                throw new UnauthorizedAccessException();
            //AuthenticationCookie.CreateAndAddToResponse(HttpContext, loginNto.Email, _jwt);
            await SignInAsync(loginNto.Email, _jwt);
            ...           
            return Ok();
        }
        ...
    
    }
    async Task SignInAsync(string email, CustomJwtDataFormat jwtDataFormat){
        var schemeName = CookieAuthenticationDefaults.AuthenticationScheme;
        var claims = new List<Claim>(){
            new Claim(ClaimTypes.NameIdentifier,  email),
            new Claim(ClaimTypes.Name,  email),
            new Claim(ClaimTypes.Email,  email),
            // ... other claims according to the jwtDataFormat
        };
        var id = new ClaimsIdentity(claims, schemeName);
        var principal = new ClaimsPrincipal(id);
        // send credential cookie using the standard 
        await HttpContext.SignInAsync(schemeName,principal);
    } 
    
  3. 而且GetUser也可以简化:

    [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)]
    public IActionResult GetUser()
    {
        var email = HttpContext.User.FindFirstValue(ClaimTypes.Email);
        User user = UsersMapper.Get(AuthenticationCookie.GetAuthenticatedUserEmail(HttpContext, _jwt));
        _logService.RequestResponse("[Authentication/GetUser]", HttpContext.Connection.RemoteIpAddress, AuthenticationCookie.GetAuthenticatedUserEmail(HttpContext, _jwt), null, Ok().StatusCode);        
        var payload= new {
            Email = email,
            // ... other claims that're kept in cookie
        };
        // return Ok(Json(user.ForNet()));
        return Json(payload);
    }
    

【讨论】:

  • 感谢您的回复。我试图实现它,但它不起作用。我不是 .NET 专家,但我似乎明白在登录期间平台会执行两个操作:首先验证用户 (AuthenticationController.Login),然后收集所有信息 (AuthenticationController.GetUser)。此操作需要通过验证 JWT cookie 发生的授权(我添加了 AuthenticationCookie.cs)。我相信 Login 方法负责创建这个 cookie,但是从我的尝试来看,我认为它没有保存在我的浏览器中。
  • @El_Merendero 1. 当您说“尝试过......但它不起作用”时,我想您仍然会收到 Authentication Failed,对吗?我昨天发现身份验证可能有问题。但是由于您的原始帖子询问的是“请求在 404 中完成”,所以我没有多谈。
  • @El_Merendero(太长,无法在一条评论中发表) 2. 根据我的经验,新问题是因为您在登录用户时发送了 cookie: JWT_FORMAT 作为凭据。这不是标准的 Cookie 身份验证方案。 (但由于您没有提供JwtDataFormat,我对此并不完全确定)。我不知道您为什么要发送 JWT 作为 cookie 凭据。 IMO,没有必要。我建议您应该使用默认的 Cookie 身份验证方案来发送 cookie。如果您更喜欢 JWT,请使用它。不要将 JWT 与 Cookie: {JWT} 之类的 cookie 混为一谈。
  • @El_Merendero 请参阅我的编辑以了解如何更新。
猜你喜欢
  • 2021-06-02
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多