-1

I have angular 8 application and I am using identity server. And I have a home component and a navbar component. And on a navbar component you have a login button what the user will directed to the login page.

But what I want now is that if you go to home: http://localhost:4200/home. That the use will directly go to the login page.

So this is the home component:

export class HomeComponent implements OnInit {
  constructor(public oidSecurityService: OidcSecurityService) {}
  ngOnInit() {
    this.login();
    console.log(this.oidSecurityService.getState);
  }

   login() {
    this.oidSecurityService.authorize();
  }
}

And this is the navbar component:

export class NavBarComponent implements OnInit, OnDestroy {
  currentUser$: Observable<any> ;
  userData: any;
  isAuthenticated$: Observable<boolean> ;
  isAuthenticated: boolean;

  constructor(
    public oidSecurityService: OidcSecurityService,
    private _oidcConfigService: OidcConfigService,
    public platform: Platform
  ) {}

  ngOnInit(): void {
    this.isAuthenticated$ = this.oidSecurityService.isAuthenticated$;
    this.oidSecurityService.checkAuth().subscribe(auth => {
      console.log('is authenticated', auth);
    });

    this.oidSecurityService.userData$.subscribe(userData => {
      console.log(this.userData = userData);
    });

    this.isAuthenticated$.subscribe((data) => {});
  }

  ngOnDestroy(): void {}
  
  login() {
    this.oidSecurityService.authorize();
    console.log(this.oidSecurityService.getState);
  }

  logout() {
    this.oidSecurityService.logoff();
  }

  get token() {
    const claims: any = this.oidSecurityService.getToken();
    return claims ? claims : null;
  }
}

So when you trigger the login button the user sees the login page.

But so how to trigger directly the login page from home? So if you go to: http://localhost:4200/home user sees directly the login page

So what I have to change?

I don't have login component. I am using Identity server. So this: this.oidSecurityService.authorize(); will go to this page, where user can login:

http://localhost:4430/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dcrowd-dashboard%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A4200%26response_type%3Dcode%26scope%3Dopenid%2520profile%2520dashboard-api%26nonce%3Ddde8a3159556f497f4d3cf223540b26a1dYah1g3W%26state%3D90d1eb8c5acbe26ededcbf0a61c4e4da70sjjLw1b%26code_challenge%3DEJ1nAdtWM45Z3IoNnwVZWzAzKTz2xDC1y1c1qi1bwTU%26code_challenge_method%3DS256

You mean like this in ngOninit:

 window.location.replace('http://localhost:4430/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dcrowd-dashboard%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A4200%26response_type%3Dcode%26scope%3Dopenid%2520profile%2520dashboard-api%26nonce%3D3daf0245322085adfada4bb19abb7da0c8YW1v4iG%26state%3D90d1eb8c5acbe26ededcbf0a61c4e4da70sjjLw1b%26code_challenge%3DQ-R9LMcBmSyrUCS4ZK0WljuA__z2p7S3WMXsFOjMyY0%26code_challenge_method%3DS256');

so this is my guard:

@Injectable({ providedIn: 'root' })
export class AuthorizationGuard implements CanActivate {
    constructor(private oidcSecurityService: OidcSecurityService, private router: Router) {}

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        return this.oidcSecurityService.isAuthenticated$.pipe(
            map((isAuthorized: boolean) => {
                console.log('AuthorizationGuard, canActivate isAuthorized: ' + isAuthorized);

                if (!isAuthorized) {
                    this.router.navigate(['/unauthorized']);
                    return false;
                }

                return true;
            })
        );
    }
}

and this is my app.routing.module.ts:

const routes: Routes = [
   { path: 'home', component: HomeComponent, canActivate: [AuthorizationGuard] },
  { path: '**', redirectTo: 'home' }
  
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {}
mightycode Newton
  • 3,229
  • 3
  • 28
  • 54
  • you can try redirecting the user with `this.router.navigateByUrl('/login', { skipLocationChange: true });` from home page (if he is not logged in) [without changing the URL](https://stackoverflow.com/questions/37054731/angular-2-routing-without-changing-url) – Aleksey Solovey Oct 11 '20 at 21:41
  • Thank you. But I dont have login component. I am using Identity server. So this: this.oidSecurityService.authorize(); wil go to this page, where user can login: http://localhost:4430/Account/Login?ReturnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Dcrowd-dashboard%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A4200%26response_type%3Dcode%26scope%3Dopenid%2520profile%2520dashboard-api%26nonce%3Ddde8a3159556f497f4d3cf223540b26a1dYah1g3W%26state%3D90d1eb8c5acbe26ededcbf0a61c4e4da70sjjLw1b%26code_challenge%3DEJ1nAdtWM45Z3IoNnwVZWzAzKTz2xDC1y1c1qi1bwTU%26code_challenge_method%3DS256 – mightycode Newton Oct 11 '20 at 21:46
  • Simply do a redirect to your identity server using plain Javascript: for example, see https://stackoverflow.com/questions/503093/how-do-i-redirect-to-another-webpage – B Thuy Oct 11 '20 at 21:50

1 Answers1

0

Use routers and guards as described in

https://itnext.io/handle-restricted-routes-in-angular-with-route-guards-95c93be9d05e

The Guards will instruct the routers when user can access to specific routes.

Also take a look at:

How to check: is the User logged in with angular-6-social-login npm package?

Pablo Gutierrez
  • 112
  • 1
  • 4