Microsoft.AspNetCore.Authorization.DefaultAuthorizationService-授权失败

时间:2019-12-10 16:47:28

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

我所拥有的:

我必须使用去年开发的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);
        }
    }

1 个答案:

答案 0 :(得分:2)

原因

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

    app.UseAuthentication();     // MUST Add this line before UseMvc()
    app.UseMvc(routes => {...});
    
结果,即使用户已经登录,ASP.NET Core也不会为该用户创建用户主体。然后,您收到一条消息:

  

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

     

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

     

Microsoft.AspNetCore.Mvc.ChallengeResult:信息:使用身份验证方案(Cookies)执行 ChallengeResult

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

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

因此它使用默认值,即/Account/Login。但是您没有这样的AccountControllerLogin操作方法,您得到的响应为404:

  

Microsoft.AspNetCore.Hosting.Internal.WebHost:信息:请求启动HTTP / 1.1 GET http://localhost:44311 /帐户/登录?ReturnUrl =%2FAuthentication%2FGetUser应用程序/ json

     

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

     

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

如何修复

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

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