Search code examples
angularauthenticationoauth-2.0auth-guard

Grabbing the OAuth Token From URL After Redirect URI Callback Using Angular


I redirect my Angular application to the Spotify Login (https://accounts.spotify.com/authorize) Once they login they are redirected back to http://localhost:4200/callback. This URL has a token attached to it. But it immediately redirects to (I want it to redirect here):

const appRoutes: Routes = [{ path: 'callback', redirectTo: '/host', pathMatch: 'full' }]

How/where can I preserve the auth token without having it sit in the users URL?

I realize I will eventually need AuthGuards as well, but first I want to retrieve the token.


Solution

  • I suggest you don't directly set "redirectTo" in the routing configuration. Instead, add a callbackComponent to handle the token and redirection. Like following:

    const appRoutes: Routes = [
        { path: 'callback', component: CallbackComponent }
    ]
    

    In CallbackComponent

    export class CallbackComponent implements OnInit {
        constructor(private route: ActivatedRoute, private router: Router) {}
    
        public ngOnInit():void {
            const token = this.route.snapshot.queryParamMap.get('token');
            // Handle token
            // ...
            this.router.navigate(['./host']);
        }
    }