为什么我的Cookie身份验证在ASP .NET Core中不起作用? [英] Why doesn't my cookie authentication work in asp .net core?

查看:550
本文介绍了为什么我的Cookie身份验证在ASP .NET Core中不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已使用Cookie启用了身份验证:

I have enabled authentication using cookies:

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

...并创建了用于测试声明的通用视图:

...and created a generic view to test claims:

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时:

When I get /api/auth/authfixed/ a cookie set:

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时,我得到了:

...but when I return to api/auth/test I get:

False

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

ie. I am not authenticated? The authentication middleware is not picking up my cookie? Why not?

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

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

???为什么我需要显式设置它?

??? Why do I need to explicitly set that?

我知道,我可以将DefaultChallengeScene,DefaultAuthenticationScheme和DefaultScheme设置为CookieAuthenticationDefaults.AuthenticationScheme,但实际上所有 都设置为字符串"Cookies",但仍然不起作用.

I know, I can set DefaultChallengeScene, DefaultAuthenticationScheme and DefaultScheme to CookieAuthenticationDefaults.AuthenticationScheme, but all that actually does is set to the string 'Cookies', and it still doesn't work.

这里实际上发生了什么?

What's actually happening here?

推荐答案

对于其他有此问题的人,诀窍是您所有的组件都必须引用相同的身份ID.

For anyone else who has this problem, the trick is that all your components need to refer to the same identity id.

就我而言,我使用的是AuthControllerAuthId作为自定义身份验证标识符,而不是默认的Cookie.我需要确保auth链的所有部分都使用此值.

In my case, I was using AuthControllerAuthId as my custom auth identifier, instead of the default Cookie. What I needed was to make sure all parts of the auth chain were using this value.

添加身份验证时:

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并确保在所有步骤中均已正确设置.

Everything was actually working, but specifically in my case, the trick is to look at the AuthenticationType on User.Identity and ensure that it is correctly set at all steps.

这篇关于为什么我的Cookie身份验证在ASP .NET Core中不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆