Search code examples
angularhashfragmenttokenopenid

How to preserve my hash fragment in Angular 2 for openid token


I am using oauth for authentication in my Angular 2 application. After authentication I get all info in the return url after a hash. After routing inside my angular 2 program, the hash part is totally deleted, but I need it. This questions has been asked and answered before, but the answer did not solve my problem, my fragment is still "null". I think as mentioned in one of the answers. This solution is only for pathlocationstrategy, but I am using hashlocationstrategy

Retrieve hash fragment from url with Angular2

So, this is why the answer there does not solve my issue. Did anybody solve that issue while using "hashlocationstrategy"?


Solution

  • Thanks to a suggestion somewhere on the internet, but cannot find it anymore to give it credit, I used "window.location.hash". In the app.module.ts you have to put similar code:

    constructor(public routerName: Router) {
    console.log("Appmodule is starting")
    routerName.events.subscribe(s => {
      if (s instanceof NavigationStart&&
               (s.toString().indexOf("/scope")>0) )
      { let tokenReceived=window.location.hash;
        this.decodeToken(tokenReceived);
      }
    });
    

    You are essentially to looking for a navigation to start and subscribe to it and as soon as your application is identifying /scope and navigating to it, the decoding of the received token starts. "decodeToken" is just my own method for decoding. This entails having a path for routing in your guard in the same file, namely:

    { path: 'scope', component: LoginComponent},
    

    Hope this helps!