Suvonkar
Suvonkar

Reputation: 2460

Fetch #access_token from URL

My landing url after SSO login is:

http://localhost:4200/login#access_token=f1946707a99f5be17cd639c49ed46e22af778a473aa1d93220d157d1a9b9ff83&token_type=bearer&expires_in=7200

Now, how I can fetch the #access_token value from this url?

Upvotes: 1

Views: 1113

Answers (1)

Use the function provided below to get the token value

//Get the Token value from URL
//You can use window.location.href or pass the value as you please
let token: string = getParameterByName("access_token", location.href);
    
public getParameterByName(name: string, url: string): string {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    let regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
}

If you want the value in a routing event

In a component that imports router

this.router.events
    .filter(event => event instanceof NavigationEnd)
    .map(() => this.activatedRoute)
    .map(route => {
        while (route.firstChild) route = route.firstChild;
        return route;
    }).filter(route => route.outlet === 'primary')
      .mergeMap(route => route.data)
      .subscribe((event) => {
          //Use the code here to get the value
       }
);

Upvotes: 1

Related Questions