【问题标题】:Client can't get cookies with Identity客户端无法通过身份获取 cookie
【发布时间】:2021-11-02 19:14:45
【问题描述】:

我正在使用 ASP.NET Core 和 Angular 编写一个 SPA 应用程序。我正在使用 CORS 在前端和后端之间进行通信。我发现我登录后无法获得授权,并且客户端没有cookie。我已经卡了2天了,请帮助我。

startup.cs,我有:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(...)      
        services.AddDbContext<TaskMatrixContext>(...);
        services.AddControllers(...)
        services.Configure<IdentityOptions>(options =>
        {...}); 
        services.AddIdentity<AppUser,IdentityRole().
                 AddEntityFrameworkStores<TaskMatrixContext>();
        services.AddAuthentication().AddCookie();
        services.ConfigureApplicationCookie(options =>
        {...});
        services.AddAuthorization(options =>
        {...});  
         ...
    } 

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        ...
        app.UseRouting();
        app.UseCors("AllowMyOrigin");
        app.UseAuthentication();
        app.UseAuthorization();

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

这是我的AccountController

[HttpPost("/login")]
public async Task<ActionResult<LoginDto>> Login(LoginDto model)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, true);

        if (result.Succeeded)
        {
            model.IsLoggedIn = true;
        }

        if (result.IsLockedOut)
        {
            model.IsLockedOut = true;
            model.RedirectUrl = "/account/lockedout";
        }
    }

    return model;
}

在我的前端:

login(dto:LoginInput):Observable<LoginResult> {
    return this.http.post<LoginResult>
                (this.baseUrl+'/login',dto).pipe(
                    tap(...)
                );
}

【问题讨论】:

    标签: c# angular asp.net-core cookies asp.net-core-identity


    【解决方案1】:

    您应该使用withCredentials 选项:

    https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials

    在你的前端:

    login(dto:LoginInput):Observable<LoginResult> {
        return this.http.post<LoginResult>
                    (this.baseUrl+'/login',dto,{withCredentials: true}).pipe(
                        tap(...)
                    );
    }
    

    每个需要身份验证cookie的请求都应该这样做

    【讨论】:

    • 感谢您的帮助,但它不起作用。
    【解决方案2】:

    又经过几天的研究,我发现我们无法使用 Identity Core 在 REST Api 中实现身份验证。我们应该使用 JWT 生成令牌并进行验证。推荐的前端教程是: https://jasonwatmore.com/post/2019/10/14/aspnet-core-3-simple-api-for-authentication-registration-and-user-management 对于后端: https://dev.to/moe23/asp-net-core-5-rest-api-authentication-with-jwt-step-by-step-140d

    【讨论】:

    • 而不仅仅是提供链接。最好包含有关使用 REST API 的包的信息和可以帮助开发人员解决类似问题的示例代码。
    • 请添加更多详细信息以扩展您的答案,例如工作代码或文档引用。
    猜你喜欢
    • 1970-01-01
    • 2018-11-24
    • 2018-01-24
    • 2019-01-25
    • 1970-01-01
    • 2019-10-29
    • 1970-01-01
    • 2012-04-25
    • 2018-11-21
    相关资源
    最近更新 更多