5

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.

6
  • Maybe people knowing answers, would profit from displaying core code pieces for present solution and already present ideas - so is this cross domain or ...? Commented Jun 19, 2016 at 16:59
  • I don't think code is needed here. I use pretty standart cookie-based auth like in docs.asp.net example. Commented Jun 19, 2016 at 17:01
  • This won't be cross-domain for now. It's an intranet app with UI project being hosten on a Linux server, and backend will be on windows server for now (with migration on linux after getting rid of windows-specific libs). But ability to make it cross-domain would be definitely useful. I just need to understand in which direction I should look. I saw 1 example of single sign-on between multiple asp core apps on docs.asp.net, but my case is different, as frontend isn't asp.core app. Commented Jun 19, 2016 at 17:03
  • My experience with SSO is minor, but in every project I used it, we simply followed the prescriptions that special framework needed ... but long forgotten ;-) Commented Jun 19, 2016 at 17:04
  • 1
    try this github.com/openiddict Commented Jun 19, 2016 at 20:42

2 Answers 2

6

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 });
    }
Sign up to request clarification or add additional context in comments.

3 Comments

And how do you send the cookies on subsequent requests?
Subsequent requests will be sent by the browser and the browser will automatically bring the cookies.
What if the cookie gets deleted? How are you catching that in Angular and ensuring you send the user back to the login page?
4

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

2 Comments

Looks very promising. I'm in the middle of implementing this. Thanks!
How is it comparing to IdentityServer4 ? identityserver4.readthedocs.io this one mentioned in the Docs of asp,net core -> docs.asp.net/en/latest/security

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.