如何使用来自我的 ASP.NET Core 站点的身份验证来验证 angular 2 Web 应用程序?

Ser*_*nov 5 authentication cookies asp.net-core-mvc asp.net-core angular

我有带有 angular 2 前端的 ASP.NET Core 应用程序。我使用 cookie 身份验证。但我想将我的应用程序拆分为 2 个单独的站点 - angular2 上的一个前端站点和 asp.net 核心上的一个后端站点。

如何使用来自 ASP.NET Core 站点的身份验证来验证前端应用程序?我的后端站点中有一个登录页面。如何在前端应用程序中识别我未通过身份验证,然后重定向到后端应用程序,然后获取身份验证 cookie?我不确定我是否了解这个过程的机制。

Her*_*ong 6

对于身份验证,我更喜欢使用 cookie。

使用 cookie 身份验证而不使用 Identity

登录码

    [HttpPost("login")]
    [AllowAnonymous]
    public async Task<HttpBaseResult> Login([FromBody]LoginDto dto)
    {
        var user = db.Users.Include(u=>u.UserRoles).SingleOrDefault();
        var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                new Claim(ClaimTypes.Name, user.UserName)
        };
        var roles = user.UserRoles.Select(u => u.Role);
        foreach (var item in roles)
        {
            claims.Add(new Claim(ClaimTypes.Role, item.Name));
        }
        var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
        await HttpContext.SignInAsync(
            new ClaimsPrincipal(identity),
            new AuthenticationProperties { IsPersistent = dto.RememberMe });
        // ...
    }
Run Code Online (Sandbox Code Playgroud)

跨域

配置服务

    {
        options.SlidingExpiration = true;
        options.Cookie.HttpOnly = false;
        // Dynamically set the domain name of the prod env and dev env
        options.Cookie.Domain = Configuration["CookieDomain"];
    });
Run Code Online (Sandbox Code Playgroud)

配置

    app.UseCors(builder => builder.WithOrigins("http://localhost:4200", "http://www.example.com","http://example.com")
        .AllowAnyMethod()
        .AllowAnyHeader()
        .AllowCredentials());
Run Code Online (Sandbox Code Playgroud)

角码

    public login(userName: string, password: string, rememberMe: boolean): Observable<HttpBaseResult> {
      const url: string = `${this.url}/login`;
      var data = {
        UserName: userName,
        Password: password,
        RememberMe: rememberMe
      };
      return this.client.post<HttpBaseResult>(url, data, { withCredentials: true });
    }
Run Code Online (Sandbox Code Playgroud)

  • 后续请求将由浏览器发送,浏览器会自动带上cookie。 (2认同)