Hi,
this is my firts time using Okta
my problem is 'isAuthenticated ’ is always false after succes login of user . I think that callback service is not called.
the base url of my application is : http://localhost:4200/#/
In okta site, the ‘#’ is not accepted but after login i have this:
http://localhost:4200/callback?code=83NZbmgEQu4sNEagXcqzQxh-g2K75C9-BT5ZP9k_25o&state=wbCkk9N8kot2xn0VFd5fh5GsGFuy4H1y6657KSFO9bioazDF2L2uDNGkv39dh5R0
after that 'isAuthenticated ’ is also false:
Code :
app.component.html
<a class="item" *ngIf="!isAuthenticated" (click)="oktaAuth.login('/')">Login</a>
{{isAuthenticated}}
<div *ngIf="isAuthenticated" >
<router-outlet></router-outlet>
</div>
app.component.ts
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
isAuthenticated: boolean ;
constructor(public oktaAuth: OktaAuthService,private authService: AuthService,private socleService: SocleService,private accesService:AccessService,private commonService: CommonService,public router: Router) {}
ngOnInit(): void {
this.oktaAuth.$isAuthenticated.subscribe(val => {
this.isAuthenticated = val
console.log('xxx', this.isAuthenticated );
});
}
OktaAuthService.ts
import { BehaviorSubject, Observable, Observer } from 'rxjs';
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { OktaAuth, IDToken, AccessToken, OktaAuthOptions } from '@okta/okta-auth-js';
import store from 'store2';
@Injectable({providedIn: 'root'})
export class OktaAuthService {
CLIENT_ID = '***********************************************';
ISSUER = 'https://dev-***********.okta.com/oauth2/default'
LOGIN_REDIRECT_URI = 'http://localhost:4200/callback';
config: OktaAuthOptions = {
issuer: this.ISSUER,
clientId: this.CLIENT_ID,
redirectUri: this.LOGIN_REDIRECT_URI,
pkce: true,
storageManager: {
token: {
storageTypes: ['localStorage', 'sessionStorage', 'cookie']
},
cache: {
storageTypes: ['localStorage', 'sessionStorage', 'cookie']
},
transaction: {
storageTypes: ['cookie']
}
}
};
oktaAuth = new OktaAuth(this.config);
$isAuthenticated: Observable<boolean>;
private observer?: Observer<boolean>;
constructor(private router: Router) {
this.$isAuthenticated = new Observable((observer: Observer<boolean>) => {
this.observer = observer;
this.isAuthenticated().then(val => {
observer.next(val);
});
});
}
async isAuthenticated() {
// Checks if there is a current accessToken in the TokenManger.
return !!(await this.oktaAuth.tokenManager.get('accessToken'));
}
login(originalUrl: string) {
store('okta-config', this.config);
// Save current URL before redirect
sessionStorage.setItem('okta-app-url', originalUrl || this.router.url);
console.log(' this.oktaAuth.token', this.oktaAuth.token);
// Launches the login redirect.
this.oktaAuth.token.getWithRedirect({
scopes: ['openid', 'profile', 'email'],
responseType: ['token', 'id_token'],
prompt: 'consent login',
});
}
async handleAuthentication() {
const tokenContainer = await this.oktaAuth.token.parseFromUrl();
this.oktaAuth.tokenManager.add('idToken', tokenContainer.tokens.idToken as IDToken);
this.oktaAuth.tokenManager.add('accessToken', tokenContainer.tokens.accessToken as AccessToken);
if (await this.isAuthenticated()) {
this.observer?.next(true);
}
// Retrieve the saved URL and navigate back
const url = sessionStorage.getItem('okta-app-url') as string;
this.router.navigateByUrl(url);
}
async logout() {
await this.oktaAuth.signOut({
postLogoutRedirectUri: this.LOGOUT_REDIRECT_URI
});
}
}
callback.component.ts
@Component({ template: `
{{error}}
`, })
export class CallbackComponent implements OnInit {
error?: string;
constructor(private okta: OktaAuthService) {}
ngOnInit(): void {
// Handles the response from Okta and parses tokens
this.okta.handleAuthentication();
}
}
app.module.ts
const config: OktaAuthOptions = {
issuer: 'https://dev-************.okta.com',
clientId: '**********************',
redirectUri: window.location.origin +'/callback'
};
export const authClient = new OktaAuth(config);
@NgModule({
declarations: [
AppComponent, NotfoundComponent,
CallbackComponent,
ProtectedComponent
],
imports: [
AppRoutingModule,
GeneralModule,
BrowserModule,
OktaAuthModule
],
providers: [
OktaAuthGuard ,
{
provide: OKTA_CONFIG,
useValue: { authClient }
},
{ provide: LocationStrategy, useClass: HashLocationStrategy },
],
bootstrap: [AppComponent]
})
export class AppModule { }
app-routin-module.ts
@NgModule({
imports: [
RouterModule.forRoot([
{
path: window.location.origin +'callback',
component: CallbackComponent
},
{
path: 'protected',
component: ProtectedComponent,
canActivate: [OktaAuthGuard]
},
......................
],
exports: [RouterModule]
})
export class AppRoutingModule {
}
Can you help me please , how to correct my code to obtain isAuthenticated =true after succes login and to get token user
Ps. Sign-in redirect URIs on okta site is: http://localhost:4200/callback
Thank you