Single Sign On between ASP.NET MVC and Angular 6

Viewed 1619

I am currently using ASP.NET MVC and Web Api to authenticate users. I want my users to sign in through my ASP.NET MVC login page but be authenticated to access my Angular 6 application.

I want to take this approach because I would like to have links to other applications that require authentication in the future but allow the user to access these applications after signing in on the Login page.

What Single Sign On method can I use to authenticate users?

2 Answers

I'm able to generate an access token on my mvc application and authenticate but how can I authenticate the user on my angular application using the same access token?

The best approach is not to create custom token. Instead, you want to use industry standard - OAuth 2.0 with OpenID Connect.

You can either setup IdentityServer yourself or use identity providers like Azure Active Directory, Auth0.

You can try to generate a token (JWT) after authentication using your ASP.NET MVC login.

public ActionResult Test()
{
    string currentUser = User.Identity.GetUserName();
    if (currentUser.Length != 0)
    {
        // build JWT Token
        DataAccess dataAccess = new DataAccess();
        ViewBag.Token = dataAccess.BuildTokenObject(currentUser).BearerToken;
    }
    return View();
}

Build Token function. You can set an expiration time to token, you may google JWT for a detailed code on setting time expiration in a token.

public TokenInfo BuildTokenObject(string user)
{
   TokenInfo token = new TokenInfo();
   UserRole roleInfo = new UserRole();
   List<ClaimInfo> claims = new List<ClaimInfo>();

   roleInfo = GetRole(user);
   token.UserName = user;
   token.BearerToken = new Guid().ToString();
   token.RoleName = roleInfo.Role_Name;
   token.IsSysAdmin = roleInfo.isSysAdmin;
   token.Claims = GetClaims(roleInfo.Role_Name);

   // Set JWT bearer token
   token.IsAuthenticated = token.RoleName == "" ? false : true;
   token.BearerToken = BuildJwtToken(token);
   return token;
}

Angular application to read token using Route Guard. if have problem with authentication then redirect to error page.

export class AuthGuardService implements CanActivate {

    constructor(private _authService: AuthService, 
            private _router: Router) {}

    canActivate(): Observable<boolean> | Promise<boolean> | boolean {
        // check if token has expired
        if (this._authService.isAuthenticated()) {
            return true;
        } else {
           this._router.navigate(['/error']);
            return false;
        }
   }    
}

function for reading token expiration.

isAuthenticated(): boolean {        
    let jwt = localStorage.getItem('cs-token');
    if (HELPER.isTokenExpired(jwt)) {
        return false;
    } else {
        return true;
    }
}

additional reference: https://jwt.io/

Related