question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Feature: support CanLoad and CanActivateChild implementation in KeycloakAuthGuard

See original GitHub issue

Bug Report or Feature Request (mark with an x)

- [ ] bug report -> please search for issues before submitting
- [x ] feature request

Versions.

Repro steps.

The log given by the failure.

Desired functionality.

Can we extend KeycloakAuthGuard to support CanLoad and CanActivateChild.

This will be very useful for lazy routed modules.

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:6
  • Comments:8 (1 by maintainers)

github_iconTop GitHub Comments

8reactions
igorlinocommented, Jul 22, 2020

My current workaround/solution, for whoever needs it. @mauriciovigolo if you would like a MR, let me know.

Assuming that a route uses lazy load:

  1. point to our auth guard in the respective angular route definition
       canLoad: [AuthGuard],
        loadChildren: () => import('./feature/feature.module').then(m => m.FeatureModule)
  1. implement CanLoad in the AuthGuard
@Injectable()
export class AuthGuard extends KeycloakAuthGuard implements CanLoad {

    constructor(protected router: Router, protected keycloakAngular: KeycloakService) {
        super(router, keycloakAngular);
    }

    canLoad(route: Route, segments: UrlSegment[]): boolean | Observable<boolean> | Promise<boolean> {
        return new Promise(async (resolve, reject) => {
            try {
                this.authenticated = await this.keycloakAngular.isLoggedIn();
                this.roles = await this.keycloakAngular.getUserRoles(true);

                const result = await this.checkAccessAllowed(route.data);
                resolve(result);
            } catch (error) {
                reject('An error happened during access validation. Details:' + error);
            }
        });
    }

    isAccessAllowed(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Promise<boolean> {
        return this.checkAccessAllowed(route.data);
    }

    checkAccessAllowed(data: Data): Promise<boolean> {
        return new Promise(async (resolve, reject) => {
            if (!this.authenticated) {
                this.keycloakAngular.login().catch(e => console.error(e));
                return reject(false);
            }
            const requiredRoles = data as string[];
            if (!requiredRoles || requiredRoles.length === 0) {
                return resolve(true);
            } else {
                if (!this.roles || this.roles.length === 0) {
                    resolve(false);
                }
                let granted = false;
                for (const requiredRole of requiredRoles) {
                    if (this.roles.indexOf(requiredRole) > -1) {
                        granted = true;
                        break;
                    }
                }
                resolve(granted);
            }
        });
    }
}

3reactions
mauriciovigolocommented, Jul 24, 2018

@NehalDamania, I will take a look at your feature request. I’m pretty busy last days, so as soon as I have some time available I will send you a feedback. Thanks!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Route Guards — Angular. canActivate vs canActivateChild vs…
canLoad ; canActivateChild; canActivate; resolve. I'm going to explain each type and how to build a guard service, and when to use each...
Read more >
How to test Angular AuthGuard - examples for the CanActivate ...
An Angular project with a base guard and authentication service implemented. This example requires the public isLoggedIn() method in the service ...
Read more >
TS2416: Property 'canActivate' in type 'MyGuard' is not ...
The error you are facing is because you copied the code that is for a different version of Angular than what you are...
Read more >
CanActivateChild - Angular
Interface that a class can implement to be a guard deciding if a child route ... The following example implements a CanActivateChild function...
Read more >
The difference between the canActivate and canActivateChild ...
canActivate. Interface that a class can implement to be a guard deciding if a route can be activated. If all guards return true,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found