gpt4 book ai didi

authentication - 为什么我的 cookie 身份验证在 asp .net core 中不起作用?

转载 作者:行者123 更新时间:2023-12-02 08:11:54 24 4
gpt4 key购买 nike

我启用了使用 cookie 的身份验证:

using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using WebBasic.Core.Controllers;

namespace WebBasic.Core
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddAuthentication().AddCookie(AuthController.AuthControllerAuthId);
services.AddAuthorization(options => { options.AddPolicy("IsFoo", policy => policy.RequireClaim("FooType")); });
}

public void Configure(IApplicationBuilder app, ILoggerFactory loggerfactory)
{
app.UseMvc();
app.UseAuthentication();
}
}
}

...并创建了一个通用 View 来测试声明:

using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;

namespace WebBasic.Core.Controllers
{
[Route("/api/[controller]/[action]")]
public class AuthController : Controller
{
public const string AuthControllerAuthId = "AuthControllerAuthId";

public IActionResult Test()
{
var claims = string.Join(", ", User.Claims.Select(i => i.Type));
return Ok($"{User.Identity.IsAuthenticated}: {claims}");
}

public async Task<IActionResult> AuthFixed()
{
var claims = new List<Claim> {new Claim("FooType", "FooValue", ClaimValueTypes.String)};
var userIdentity = new ClaimsIdentity(claims);
var userPrincipal = new ClaimsPrincipal(userIdentity);
await HttpContext.SignInAsync(AuthControllerAuthId, userPrincipal);
return Ok("ok");
}

public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(AuthControllerAuthId);
return Ok("ok");
}
}
}

当我得到 /api/auth/authfixed/ 一个 cookie 集时:

Cache-Control:no-cache
Content-Type:text/plain; charset=utf-8
Date:Tue, 05 Sep 2017 13:57:39 GMT
Expires:-1
Pragma:no-cache
Server:Kestrel
Set-Cookie:.AspNetCore.AuthControllerAuthId=...; path=/; samesite=lax; httponly

...但是当我返回到 api/auth/test 时,我得到:

False

即。我没有认证?身份验证中间件没有获取我的 cookie?为什么不呢?

如果我添加 [Authorize] 我得到:

System.InvalidOperationException: No authenticationScheme was specified, and there was no DefaultChallengeScheme found.
at Microsoft.AspNetCore.Authentication.AuthenticationService.<ChallengeAsync>d__11.MoveNext()

???为什么我需要明确设置它?

我知道,我可以将 DefaultChallengeScene、DefaultAuthenticationScheme 和 DefaultScheme 设置为 CookieAuthenticationDefaults.AuthenticationScheme,但所有实际做的都设置为字符串“Cookies”,而且它仍然不起作用。

这里到底发生了什么?

最佳答案

对于遇到此问题的任何其他人,诀窍在于您的所有组件都需要引用相同的身份 ID。

在我的例子中,我使用 AuthControllerAuthId 作为我的自定义身份验证标识符,而不是默认的 Cookie。我需要的是确保身份验证链的所有部分都在使用这个值。

添加身份验证时:

services.AddAuthentication(options =>
{
options.DefaultChallengeScheme = AuthController.AuthControllerAuthId;
options.DefaultAuthenticateScheme = AuthController.AuthControllerAuthId;
options.DefaultScheme = AuthController.AuthControllerAuthId;
}).AddCookie(AuthController.AuthControllerAuthId)

构造ClaimsIdentity时:

var userIdentity = new ClaimsIdentity(claims, AuthControllerAuthId);
var userPrincipal = new ClaimsPrincipal(userIdentity);

登录时:

await HttpContext.SignInAsync(AuthControllerAuthId, userPrincipal);

一切实际上都在工作,但特别是在我的情况下,诀窍是查看 User.Identity 上的 AuthenticationType 并确保它在所有步骤中都正确设置.

关于authentication - 为什么我的 cookie 身份验证在 asp .net core 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46057109/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com