Я использую "oidc-client": "^1.10.1"
с приложением angular 8 для входа в OKTA и перенаправления на страницу ввода URL-адреса.
Когда я ввожу приведенную ниже ссылку в URL, OID C выходит в okta и перенаправляет обратно на приведенную ниже ссылку, которая является правильной.
{ path: 'yubikey-activation', component: YubikeyActivationComponent, canActivate: [AuthenticatedUserGuard]}
Однако через 1 секунду он снова выполняет вход в систему okta и перенаправляет на страницу по умолчанию.
{path: '',pathMatch: 'full',component: HomeComponent,canActivate: [AuthenticatedUserGuard]}
Auth Guard
@Injectable()
export class AuthenticatedUserGuard implements CanActivate {
constructor(private authService: AuthenticationService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot)
: boolean | Observable<boolean> | Promise<boolean> {
return new Promise<boolean>(resolve => {
this.authService.serviceIsReady().then(() => {
if (this.authService.isLoggedIn()) {
resolve(true);
} else {
this.authService.startAuthentication(state.url);
resolve(false);
}
})
});
}
}
Authentication.service.ts
@Injectable({
providedIn: 'root'
})
export class AuthenticationService {
@Output() initialized: boolean = false;
static USER_LOADED_EVENT = "USER_LOADED";
static USER_UNLOADED_EVENT = "USER_UNLOADED";
//static USER_SIGNED_OUT_EVENT = "USER_SIGNED_OUT";
//static USER_EXPIRED_EVENT = "USER_EXPIRED";
static USER_RESET_EVENT = "USER_RESET";
private manager: UserManager;
private user: User = null;
private accessToken: Object = null;
private signingOut: boolean = false;
private listeners: Object;
private eventsSubject: Subject<any>;
private events: Observable<any>;
public settings: UserManagerSettings;
constructor(
private $log: Logger,
private tokenHelper: TokenHelperService,
private ngZone: NgZone) {
//Hook up some event notifications
this.listeners = {};
this.eventsSubject = new Subject<any>();
this.events = from(this.eventsSubject);
this.events.subscribe(
({ name, args }) => {
if (this.listeners[name]) {
for (let listener of this.listeners[name]) {
listener(...args);
}
}
});
}
async serviceIsReady(): Promise<void> {
await new Promise((resolve, reject) => {
const source = timer(0, 100).subscribe(t => {
if (this.initialized) {
source.unsubscribe();
resolve(true);
}
else if (t > 5000) {
source.unsubscribe();
reject(false);
}
}, error => {
reject(error);
});
});
}
/**
* Initializes the OIDC Client ready for use by the application.
*/
async initialize(openIdSettings: IOpenIdOptions): Promise<void> {
if (this.initialized) return;
this.ngZone.runOutsideAngular(() => {
this.settings = this.getClientSettings(openIdSettings);
this.manager = new UserManager(this.settings);
//Persist settings for easy access by the silent-renew iframe
window["oidc"] = {
settings: this.settings
};
});
var self = this;
this.manager.events.addAccessTokenExpiring(() => {
this.$log.info("IdSvr token expiring", new Date());
});
this.manager.events.addAccessTokenExpired(() => {
this.$log.info("IdSvr token expired", new Date());
this.logout(false);
//this.broadcast(AuthenticationService.USER_EXPIRED_EVENT);
this.broadcast(AuthenticationService.USER_RESET_EVENT);
});
this.manager.events.addSilentRenewError(e => {
this.$log.warn("IdSvr silent renew error", e.message, new Date());
this.logout(false);
});
this.manager.events.addUserLoaded(user => {
this.$log.info("IdSvr user session is ready", new Date());
this.accessToken = self.tokenHelper.getPayloadFromToken(user.access_token, false);
this.user = user;
this.broadcast(AuthenticationService.USER_LOADED_EVENT, user);
});
this.manager.events.addUserUnloaded(() => {
this.$log.info("IdSvr user session has ended", new Date());
this.broadcast(AuthenticationService.USER_UNLOADED_EVENT);
if (!this.signingOut) {
this.startAuthentication(window.location.pathname + window.location.search);
}
});
this.manager.events.addUserSignedOut(() => {
this.$log.info("IdSvr user signed out", new Date());
this.logout(false);
//this.broadcast(AuthenticationService.USER_SIGNED_OUT_EVENT);
this.broadcast(AuthenticationService.USER_RESET_EVENT);
});
this.user = await this.manager.getUser();
this.initialized = true;
}
/**
* Gets the Authorization header, to be added to any outgoing requests, that needs to be authenticated.
*/
getAuthorizationHeaders(): HttpHeaders {
return new HttpHeaders({ 'Authorization': this.getAuthorizationHeaderValue() });
}
/**
* Checks to see if a user is currently logged on.
*/
isLoggedIn(): boolean {
return this.user != null && !this.user.expired;
}
/**
* Gets all the claims assigned to the current logged on user.
*/
getProfile(): any {
return this.user.profile;
}
/**
* Gets all the claims assigned to the current logged on user.
*/
getAccessToken(): any {
return this.accessToken || this.tokenHelper.getPayloadFromToken(this.user.access_token, false);;
}
/**
* Checks to see if the current logged on user has the specified claim
* @param claimType The type of the claim the user must be assigned
* @param value The value of the claim, uses the wildcard "*", if no value provided.
*/
hasClaim(claimType: string, value?: string): boolean {
var upperValue = value === undefined || value === null
? "*"
: value.toUpperCase();
if (this.isLoggedIn()) {
const claims = this.getAccessToken()[claimType];
if (!claims)
return false;
if (typeof claims === "string")
return claims.toUpperCase() === upperValue;
else if (Object.prototype.toString.call(claims) === "[object Array]")
if (claims.filter((c) => {
return c.toUpperCase() === upperValue;
})
.length >
0)
return true;
}
return false;
}
/**
* Checks to see if the current logged on user has any of the specified claims
* @param claimTypes The type of the claim
* @param value The value of the claim, uses the wildcard "*", if no value provided.
*/
hasAnyClaim(claimTypes: string[], value?: string) {
if (this.isLoggedIn())
return false;
for (let i = 0; i < claimTypes.length; i++) {
if (this.hasClaim(claimTypes[i], value))
return true;
}
return false;
}
/**
* Gets the access token of the current logged on user.
*/
getAuthorizationHeaderValue(): string {
return `${this.user.token_type} ${this.user.access_token}`;
}
/**
* Initiates the logon process, to authenticate the user using Identity Server.
* @param returnUrl The route to load, post authentication.
*/
async startAuthentication(returnUrl: string): Promise<void> {
await this.manager.clearStaleState();
await this.manager.signinRedirect({
data: {
returnUrl: returnUrl
}
}).catch(err => {
this.$log.debug("IdSvr sign in failed", err);
return err;
});
}
/**
* Processes the callback from Identity Server, post authentication.
*/
async completeAuthentication(): Promise<Oidc.User> {
let user = await new Promise<Oidc.User>((resolve, reject) => {
this.ngZone.runOutsideAngular(() => {
this.manager.signinRedirectCallback().then(user => {
resolve(user);
}).catch(error => {
reject(error);
});
});
});
this.$log.debug("IdSvr user signed in");
this.user = user;
return user;
}
// private delay(ms: number): Promise<void> {
// return new Promise<void>(resolve =>
// setTimeout(resolve, ms));
// }
/**
* Logs out the current logged in user.
*/
logout(signoutRedirect?: boolean) {
if (signoutRedirect === undefined || signoutRedirect !== false) {
this.signingOut = true;
signoutRedirect = true;
}
this.manager.stopSilentRenew();
this.manager.removeUser().then(() => {
this.manager.clearStaleState();
this.$log.debug("user removed");
if (signoutRedirect) {
this.manager.signoutRedirect();
}
}).catch(err => {
this.$log.error(err);
});
}
/**
* Gets the current logged in user.
*/
async getUser(): Promise<Oidc.User> {
return await this.manager.getUser();
}
/**
* Gets the Identity Server settings for this client application.
*/
getClientSettings(configuration: IOpenIdOptions): UserManagerSettings {
return {
authority: configuration.authority + '/',
client_id: configuration.clientId,
redirect_uri: configuration.redirectUri,
post_logout_redirect_uri: configuration.redirectUri,
response_type: configuration.responseType, // "id_token token",
scope: "openid profile email offline_access",
filterProtocolClaims: true,
loadUserInfo: false,
automaticSilentRenew: true,
monitorSession: true,
silent_redirect_uri: configuration.silentRedirectUri,
accessTokenExpiringNotificationTime: 20, //default 60
checkSessionInterval: 5000, //default 2000
silentRequestTimeout: 20000, //default: 10000
// When CORS is disabled, token signing keys cannot be retrieved
// Manual the metadata and singinKeys for okta auth
metadata: {
jwks_uri: configuration.jwksUri,
authorization_endpoint: `${configuration.authority}/v1/authorize`,
issuer: configuration.authority,
token_endpoint: `${configuration.authority}/v1/token`
},
};
}
on(name, listener) {
if (!this.listeners[name]) {
this.listeners[name] = [];
}
this.listeners[name].push(listener);
}
broadcast(name, ...args) {
this.eventsSubject.next({
name,
args
});
}
}
export function authenticationServiceFactory(authService: AuthenticationService, appSettings: AppSettingsService) {
return async () => {
await appSettings.serviceIsReady();
await authService.initialize(appSettings.getOpenIdOptions());
}
};
Я использую поток кода авторизации, а не неявный поток
При отладке я обнаружил, что в приведенном ниже коде пользователь не имеет значения при первом перенаправлении, но при втором перенаправлении пользователь не равен нулю
isLoggedIn(): boolean {
return this.user != null && !this.user.expired;
}
На приведенном выше изображении показан первый URL-адрес обратного вызова перенаправления из имени пользователя okta, который является правильным, а на приведенном ниже изображении показан второй перенаправление, в котором нет необходимости.