Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use authentication from my ASP.NET Core site to authenticate angular 2 web app?

I have ASP.NET Core app with angular 2 front-end. I use cookie auth. But I want to split my app into 2 separate sites - one front-end site on angular2 and one back-end site on asp.net core.

How do I use auth from ASP.NET Core site to authenticate front-end app? There's a login page in my back-end site. How do I identify in front-end app that I'm not authenticated, then redirect to back-end app and then get auth cookies? I'm not sure I understand mechanic of this process.

like image 888
Sergey Durnov Avatar asked Jun 19 '16 15:06

Sergey Durnov


2 Answers

I used token based authentication. I choosed this solution: https://stormpath.com/blog/token-authentication-asp-net-core & https://github.com/nbarbettini/SimpleTokenProvider

like image 52
Juergen Gutsch Avatar answered Oct 18 '22 12:10

Juergen Gutsch


For Authentication I prefer to use cookies.

Use cookie authentication without Identity

Login Code

    [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 });
        // ...
    }

Cross Domain

ConfigureServices

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

Configure

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

Angular Code

    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 });
    }
like image 31
HeroWong Avatar answered Oct 18 '22 13:10

HeroWong