【发布时间】: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是什么?有AccountController和LoginAction 吗?还是您使用默认的Identity? -
我通过整合Startup.cs和AuthenticationController.cs的代码修改了问题(这是我的访问控制器)。问题出现在登录阶段(我使用的是有效用户)。
标签: c# asp.net asp.net-core .net-core jwt