- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我必须开发去年开发的网络应用程序,而不是我自己开发的。它由 Web 服务后端和 Web 应用程序前端组成。后端用 C# 7 编写,在 .NET Core 2.1 运行时上运行并使用 ASP.NET Core MVC 框架。前端是一个用 HTML 5、CSS3、TypeScript 和 React 编写的 Web 应用程序。
我想在我的电脑上设置一个开发环境(使用 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);
}
}
最佳答案
根本原因是您没有在 UseMvc()
之前添加 UseAuthentication()
:
app.UseAuthentication(); // MUST Add this line before UseMvc() app.UseMvc(routes => {...});As a result, ASP.NET Core won't create a User Principal for user even he has already signed in. And then you got a message of :
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).
Since you didn't configure the Login Path for cookie:
services.AddAuthentication().AddCookie(options => {
options.Cookie.Name = AuthenticationCookie.COOKIE_NAME;
options.TicketDataFormat = jwtDataFormat;
});
因此它使用默认的,即/Account/Login
。但是您没有这样的 AccountController
和 Login
操作方法,您会得到 404 响应:
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
UseMvc()
之前添加 UseAuthentication()
: app.UseAuthentication(); // MUST add this line before UseMvc()
app.UseMvc(routes => {...});
创建一个 Controller / View 供用户登录(如果您没有)。然后告诉 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
});
[编辑]
您的 Login([FromBody] LoginNto loginNto)
方法接受 HttpGet
请求,但期望获取正文。 HTTP Get 根本没有主体。您需要将其更改为 HttpPost
:
[HttpPost]
[AllowAnonymous]
public async Task<IActionResult> Login([FromBody] LoginNto loginNto)
{
...
}
用户登录的方式似乎不正确。更改您的 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);
}
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);
}
关于c# - Microsoft.AspNetCore.Authorization.DefaultAuthorizationService - 授权失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59271983/
我们需要实现如下授权规则。 如果用户是 super 管理员,则向他提供所有客户信息。比如订单信息。如果用户是客户管理员,只提供他自己的客户信息。等等 我们计划在 DAO 层实现过滤。 创建通用设计来处
我有 https 设置的 Spring Security。 尝试以安全方式在 URL 上运行 curl GET 时,我看到了意外行为。 当 curl 第一次向服务器发送请求时,它没有授权数据(为什么?
关闭。这个问题是 opinion-based 。它目前不接受答案。 想改进这个问题?更新问题,以便 editing this post 可以用事实和引用来回答它。 1年前关闭。 Improve thi
我正在构建以下内容: 一个 JavaScript 单页应用程序; 一个暴露 RESTful API 的 Node.js 后端,它将存储用户数据; 用户凭据(电子邮件/密码)可以通过单页应用程序创建并存
在带有RESTful Web服务的Spring Boot应用程序中,我已将Spring Security与Spring Social和SpringSocialConfigurer一起配置。 现在,我有
我正在为真实世界组织的成员在 Rails 中构建一个基于社区的站点。我正在努力遵循 RESTful 设计的最佳实践,其中大部分或多或少是书本上的。使我的大脑在整洁的 RESTful 圈子中运转的问题是
我想启用 ABAC mode对于我在 Google 容器引擎中使用的 Kubernetes 集群。 (更具体地说,我想限制自动分配给所有 Pod 的默认服务帐户对 API 服务的访问)。但是,由于 -
奇怪的事情 - 在 git push gitosis 上不会将新用户的 key 添加到/home/git/.ssh/authorized_keys。当然-我可以手动添加 key ,但这不好:( 我能做
我很好奇您提供 的顺序是否正确和元素中的元素重要吗? 最佳答案 是的,顺序很重要。本页介绍了基本原理:http://msdn.microsoft.com/en-us/library/wce3kxhd
我阅读了如何使用 @login_required 的说明以及其他带有解析器的装饰器。但是,如果不使用显式解析器(而是使用默认解析器),如何实现类似的访问控制? 就我而言,我将 Graphite 烯与
我用 php 开发了一个审核应用程序,通过它我可以审核所有帖子和评论。我还可以选择在 Facebook 粉丝页面墙上发布帖子。但是,当我尝试这样做时,会引发异常,显示“用户尚未授权应用程序执行此操作”
我使用 jquery-ajax 方法 POST 来发布授权 header ,但 Firebug 显示错误“401 Unauthorized” header 作为该方法的参数。 我做错了什么?我该怎么办
我有两组用户,一组正在招聘,一组正在招聘。 我想限制每个用户组对某些页面的访问,但是当我在 Controller 中使用 [Authorize] 时,它允许访问任何已登录的用户而不区分他们来自哪个组?
我有一个简单直接的授权实现。好吧,我只是认为我这样做,并且我想确保这是正确的方法。 在我的数据库中,我有如下表:users、roles、user_role、permissions、 role_perm
我的 soap 连接代码: MessageFactory msgFactory = MessageFactory.newInstance(); SOAPMessage message
我想知道是否可以将 mysql 用户设置为只对数据库中的特定表或列具有读取权限? 最佳答案 是的,您可以使用 GRANT 为数据库在细粒度级别执行此操作。见 http://dev.mysql.com/
我试图获得发布流和离线访问的授权,但出现此错误。 而且它没有显示我想要获得的权限。我的代码如下: self.fb = [[Facebook alloc] initWithAppId:@"xxxxxxx
我是 NodeJS 的初学者,我尝试使用 NodeJS + Express 制作身份验证表单。我想对我的密码进行验证(当“confirmpassword”与“password”不同时,它应该不返回任何
我能够为测试 paypal 帐户成功生成访问 token 和 TokenSecret。然而,下一步是为调用创建授权 header 。 在这种情况下,我需要提供我不确定的 Oauth 签名或 API 签
我正在尝试获取授权 steam 页面的 html 代码,但我无法登录。我的代码是 public string tryLogin(string EXP, string MOD, string TIME)
我是一名优秀的程序员,十分优秀!