Angular Oauth2 OIDC - How to check if user is logged in?

4k Views Asked by At

I am using Angular 11 with version 10 of augular-oauth-oidc

Is this the correct way to check whether the user is currently logged in?

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(
    private oauthService: OAuthService,
    private router: Router,
  ) {

 .
 .
 .

  isLoggedIn(): boolean {
    const identityClaim = this.oauthService.getIdentityClaims();
    return identityClaim && identityClaim['name'] ? true : false;
  }

I feel this is hacky... I am just checking whether the name field exists within identity?

How does this prevent a user from just modifying this variable in his console - apart from server sided checks upon api submission or something.

Does Angular route guard and interceptor do this job?

Thanks!

1

There are 1 best solutions below

0
On

check whether the user is currently logged in?

Depends on whether you're looking for either:

  • (A) is the user authorized to make API calls?
  • (B) is the user authenticated and what do we know about their identity?

For (B) authentication looking at the identity claims is perfectly fine. For (A) authorization you typically do this:

const isAuthorized = this.oauthService.hasValidAccessToken();

This is because the identity claims are only useful inside the SPA, whereas the access token is typically a bearer token that gets sent to the API, which again does its own validation and checks of the token.

How does this prevent a user from just modifying this variable in his console

This is inherent to browser applications. You cannot prevent the user (or a bad browser) from tampering with code that runs, well, in the browser. This is indeed why the server must do its own check when you send along an access token.

Does Angular route guard and interceptor do this job?

Angular routes don't know anything about OAuth2/OIDC by default. You could have a peek at my sample route guard that does check for authentication, which indirectly just checks hasValidAccessToken().

Interceptors on their own also don't know about OAuth2/OIDC, but if you configure resourceServer in the library's OAuthModuleConfig a default interceptor gets registered from the library, which will send the access token along to all requests to a specific set of APIs.