Comments (17)
In case anyone else runs into this, I started with disabling 'initialNavigation' per the above comments.
export const routing = RouterModule.forRoot(routes, {
initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});
Then, I found the best approach is to trigger the router navigation immediately after the login attempt using the following (which also implements passing the state parameter).
this.oauthService.loadDiscoveryDocumentAndTryLogin({
onTokenReceived: (info) => {
if (info.state) this.router.navigate([info.state]);
}
}).then(
info => this.router.initialNavigation()
);
from angular-oauth2-oidc.
I think the problem is related to when it is the ''
(root) route being matched (or at least on the first load for the UI) where regular implementations call the asynchronous loadDiscoveryDocumentAndTryLogin()
method in some AppComponent
constructor. The Angular request lifecycle gets at the GuardsCheck*
events before the discovery document is returned and the TryLogin
part can be executed.
Besides bedag-moo's comment (I wasn't able to call execute the TryLogin() method in the
CanActivatemethod) you can return an
Observable` in the guard like so:
canActivate(): Observable<boolean> { return fromPromise(this.auth.loadDiscoveryDocumentAndTryLogin()).map(() => { if(this.auth.hasValidIdToken()) { //or AccessToken console.log('authenticated'); return true; } console.log('not authenticated'); this.auth.initImplicitFlow(); return false; }); }
from angular-oauth2-oidc.
Try to output your routes with
export const routing = RouterModule.forRoot(routes, {
useHash: true,
enableTracing: true, // <- debug the routes
initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});
I have got the same effect to have an own login service that wrappes the oauthservice, but it turned out i got a loop in routes definition wth the canActivate method. Thus, tryLogin() was never executed in app.component.ts.
Double check your _storage (sessionStorage/localStorage) to see if there are tokens stored or exist. If oidc is used and id token shall be provided, also double check that the issuer is provided. If the id token doesn't pass the issuer check, the access token will not be passed either.
@manfredsteyer: this library is the most best third-part angular2 lib i can found. I can confirm it works very well with google open id connect and oauth2 while using angular 2.4.10 and hashLocation strategy.
from angular-oauth2-oidc.
Here's what I've used successfully:
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private oauthService: OAuthService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
if (this.oauthService.hasValidIdToken()) {
return true;
}
this.router.navigate(['/home']);
return false;
}
}
from angular-oauth2-oidc.
I have a very similar issue (#76) as you describe, what ended up being wrong for me what the redirectUrl. For some reason, it didn't work with just using this.oAuthService.redirectUri = window.location.origin;
, I had to concatenate index.html to the end of the location origin: this.oAuthService.redirectUri = window.location.origin + '/index.html';
.
Hope this helps.
from angular-oauth2-oidc.
Had similar issue. Thanks to yingding's answer above, all I needed was export const routing = RouterModule.forRoot(routes, {
initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy
});
from angular-oauth2-oidc.
You are invoking oauthService.tryLogin({})
, aren't you? (see Readme for more info)
from angular-oauth2-oidc.
Same problem. Yes we are calling tryLogin() inside the loadDiscoveryDocument() resolve step.
However guards for the route seem to be invoked before tryLogin gets a chance to capture the auth tokens from the url. forever redirecting back to home.
from angular-oauth2-oidc.
@Gimly: I don't think that's related at all.
from angular-oauth2-oidc.
@CrescentFresh The symptoms were similar, that's why I said that.
from angular-oauth2-oidc.
How does your redirect url look like (including params?)
from angular-oauth2-oidc.
thanks @yingding
from angular-oauth2-oidc.
In case anyone else runs into this, I started with disabling 'initialNavigation' per the above comments.
export const routing = RouterModule.forRoot(routes, { initialNavigation: false // <- turn off the initial redirect, used for redirect or hash routing strategy });
Then, I found the best approach is to trigger the router navigation immediately after the login attempt using the following (which also implements passing the state parameter).
this.oauthService.loadDiscoveryDocumentAndTryLogin({ onTokenReceived: (info) => { if (info.state) this.router.navigate([info.state]); } }).then( info => this.router.initialNavigation() );
This worked for me also, thanks @seandevenish
from angular-oauth2-oidc.
@seandevenish Thanks for the suggestion. you saved my time :)
from angular-oauth2-oidc.
Then, I found the best approach is to trigger the router navigation immediately after the login attempt using the following (which also implements passing the state parameter).
this.oauthService.loadDiscoveryDocumentAndTryLogin({ onTokenReceived: (info) => { if (info.state) this.router.navigate([info.state]); } }).then( info => this.router.initialNavigation() );
@seandevenish can you please tell me where you put this part in your code ?
I have same issue.
this my authgard authentification code :
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
if (this.authService.hasValidIdToken())
//if (this.authService.isUserLoggedIn())
{
return true;
}
return false;
}
And then i put your code in my app.component.ts :
this.oauthService.loadDiscoveryDocumentAndTryLogin({
onTokenReceived: (info) => {
if (info.state) this.router.navigate([info.state]);
}
}).then(
info => this.router.initialNavigation()
);
Could someone please tell me if he was able to get Authguard to work with this package (angular-oauth2-oidc
) while using the hashlocation strategie ({useHash: true, initialNavigation: "disabled"}) ?
from angular-oauth2-oidc.
@NDIAYE-baoussou The code is placed in a service, the method of which is called in the root app.component.ts in the ngOnInit() call.
Auth guard looks like this:
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean {
if (this.authService.loggedIn) {
return true;
}
this.oauthService.initCodeFlow(state.url);
}
I am pretty sure this approach works with and without the hashlocation strategy, though haven't had time to check.
from angular-oauth2-oidc.
@seandevenish thank you for your feedback. I'll test your method. I thought of a problem that could arise: how to redirect the user in not allowed page if he does not have the right to access in my app (invalid id token or access token) ?
from angular-oauth2-oidc.
Related Issues (20)
- Local parsing HTTP request error HOT 5
- Upgrade jsrsasign to v11 HOT 9
- Azure AD B2C implicate flow clientAuthError: Invalid state
- adfs using initLoginFlow() returns auth token but getAccessToken() is null
- issuer must use HTTPS (with TLS), or config value for property requireHttps must be set to false and allow HTTP without TLS HOT 1
- Third party cookie and token refresh HOT 2
- Re Login with new Scope
- Silent refresh iframe multiple injection
- Requests are canceled on logout
- Publish new npm package? HOT 1
- Authentication Library Config Type Only Import
- SSO login happens and after redirection user is not logged in HOT 1
- IDP errors not handled during initLoginFlowInPopup
- checkSession: Uncaught TypeError: e.data.split is not a function
- Add the hability to end session on the server but without redirecting to postLogoutRedirectUri
- What is proper way to preserve/refresh login state, when redirecting back from other app after refresh_token exp time? HOT 2
- ERROR ReferenceError: window is not defined - Support For SSR / prerender
- OAuthService.silentRefreshPostMessageEventListener executes tryLogin() inadvertently in the main frame
- `noRedirectToLogoutUrl` parameter is not checked in `logOut` method
- Browser timer throttling - expired refreshToken does not work to get the new accessToken
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from angular-oauth2-oidc.