简体   繁体   English

ASP.NET Core 3.1:Web API 身份登录

[英]ASP.NET Core 3.1: Web API identity sign in

I am creating CookieAutentecation signin for my Web API.我正在为我的 Web API 创建CookieAutentecation 登录

I have read and followed the official article here and I have done everything correctly as far as I am concerned.我已阅读并遵循此处官方文章,就我而言,我已正确完成所有操作。

But when I put breakpoints in my controllers and inspect HttpContext.User , everything is always null, no Username, no claims, nothing.但是当我在控制器中放置断点并检查HttpContext.User ,一切始终为空,没有用户名,没有声明,什么都没有。

What else do I need to make this work?我还需要什么才能完成这项工作? Are additional steps needed for Web API vs MVC app? Web API 与 MVC 应用程序是否需要额外的步骤?

Startup.cs:启动.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, act => {
                act.LoginPath = "/api/login";
                act.AccessDeniedPath = "/api/login";
                act.SlidingExpiration = true;
            });

    services.AddControllers();

    services.AddServices(); // <- Own app domain services 
    services.AddDataAccess(); // <- Own app domain data access
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseCors(
            options => options.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader()
        );

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();
    app.UseRouting();

    app.UseAuthentication();
    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
}

api/login api/登录

var user = new SecurityUser()
        {
            UserID = 123,
            CompleteName = "Test user",
            FirstName = "Test",
            Email = "test.user@123.com"
        };
var identity = user.ToClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme, 123);
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), new AuthenticationProperties()
        {
            AllowRefresh = true,
           ExpiresUtc = DateTime.UtcNow.AddDays(7),
           IsPersistent = true,
        });

ToClaimsIdentity extension method: ToClaimsIdentity扩展方法:

public static ClaimsIdentity ToClaimsIdentity(this SecurityUser user, string authenticantionType, int auditUserID)
{
        var claims = new List<Claim>()
        {
            new Claim(ClaimTypes.NameIdentifier, user.UserID.ToString()),
            new Claim(ClaimTypes.Email, user.Email),
            new Claim(ClaimTypes.Name, user.FirstName),
            new Claim(SecurityUserClaimTypes.AuditUserID, auditUserID.ToString())
        };

        var identity = new ClaimsIdentity(claims, authenticantionType);
        return identity;
}

Any help would be greatly appreciated.任何帮助将不胜感激。

Edit - This is what I am taking about 👇编辑 - 这就是我要考虑的👇 在此处输入图片说明

Thanks for your help guys!谢谢你们的帮助!

I finally realised it was a client thing, I did three things:我终于意识到这是客户的事情,我做了三件事:

  • CORS was an issue, in my .UseCors method call my my Api I allowed credentials: .AllowCredentials() CORS 是一个问题,在我的.UseCors方法中调用我的 Api 我允许凭据: .AllowCredentials()
  • My client app in using Blazor, I found this article here which told me I needed to set the http request configuration to include credentials, so in my client side app startup.cs:我的客户端应用程序在使用 Blazor,我在这里找到了这篇文章,它告诉我需要设置 http 请求配置以包含凭据,因此在我的客户端应用程序 startup.cs 中:
    WebAssemblyHttpMessageHandlerOptions.DefaultCredentials = FetchCredentialsOption.Include;
  • I am using Http not Https on my local, and Chrome was complaining about SameSite, so im my Api StartUp.cs, where I call AddAuthentication...AddCookie I added this: options.Cookie.SameSite = SameSiteMode.Unspecified;我在本地使用 Http 而不是 Https,Chrome 抱怨 SameSite,所以我在我的 Api StartUp.cs 中调用AddAuthentication...AddCookie我添加了这个: options.Cookie.SameSite = SameSiteMode.Unspecified;

I don't fully understand the SameSite... and I have also come across JSON Web Tokens (JWT) .我不完全了解 SameSite...而且我还遇到了JSON Web Tokens (JWT)
But I'm not interested, as long as it's working.但我不感兴趣,只要它有效。 ;-) ;-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM