Initial auth module library

This commit is contained in:
Andras Popovics
2023-01-26 19:31:17 +01:00
parent 763597c6fb
commit a3ce71ac0e
24 changed files with 599 additions and 67 deletions

View File

@@ -15,5 +15,6 @@
* limitations under the License.
*/
export * from './authentication';
export * from './authentication-interceptor/authentication.interceptor';
export * from './lib/authentication';
export * from './lib/authentication-interceptor/authentication.interceptor';
export * from './lib/auth.module';

View File

@@ -0,0 +1,48 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { HttpClientModule } from '@angular/common/http';
import { APP_INITIALIZER, NgModule } from '@angular/core';
import { OAuthModule } from 'angular-oauth2-oidc';
// import { AuthenticationService } from '@alfresco/adf-core';
import { AuthGuard } from './guards/oidc-auth.guard';
import { AuthConfigService, configureAuth } from './services/auth-config.service';
// import { AuthService } from './services/oidc-authentication.service';
@NgModule({
imports: [
HttpClientModule,
OAuthModule.forRoot()
],
providers: [
AuthGuard,
AuthConfigService,
// AuthService,
{
provide: APP_INITIALIZER,
useFactory: configureAuth,
deps: [ AuthConfigService ]
},
// TODO: CANARY: This is temporary, we are reproviding ADF's AuthenticationService with our own implementation to work with the new auth library
// TODO: But we need definitely need a cleaner solution for this. Which means, first we need to make the apis capable of handling multiple http clients
// {
// provide: AuthenticationService,
// useExisting: AuthService
// }
]
})
export class AuthModule {}

View File

@@ -0,0 +1,47 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable } from '@angular/core';
import { CanActivate, CanActivateChild } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';
import { AuthConfigService } from '../services/auth-config.service';
@Injectable()
export class AuthGuard implements CanActivate, CanActivateChild {
constructor(
private authConfigService: AuthConfigService,
private oauthService: OAuthService
) {}
canActivate(): boolean {
if (!this.oauthService.hasValidAccessToken()) {
if (this.authConfigService.isCodeFlow()) {
this.oauthService.initCodeFlow();
} else {
this.oauthService.initLoginFlow();
}
return false;
}
return true;
}
canActivateChild(): boolean {
return this.canActivate();
}
}

View File

@@ -0,0 +1,81 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable } from '@angular/core';
import { AuthConfig, OAuthService } from 'angular-oauth2-oidc';
import { JwksValidationHandler } from 'angular-oauth2-oidc-jwks';
import { take } from 'rxjs/operators';
import { Router } from '@angular/router';
import { StorageService } from '@alfresco/adf-core/common';
import { AppConfigService, AppConfigValues } from '@alfresco/adf-core/config';
export const configureAuth = (oidcAuthentication: AuthConfigService) => () => oidcAuthentication.init();
@Injectable()
export class AuthConfigService {
_authConfig: AuthConfig;
constructor(
private appConfigService: AppConfigService,
private storageService: StorageService,
private oauthService: OAuthService,
private router: Router
) {}
public init() {
debugger;
this.appConfigService.onLoad
.pipe(take(1))
.toPromise()
.then(this.configure.bind(this));
}
private configure() {
this._authConfig = this.appConfigService.get<AuthConfig>(AppConfigValues.AUTH_CONFIG, null);
// TODO: add the authenticaion object's schema to the app.config.schema.json
this.oauthService.configure(this._authConfig);
this.oauthService.tokenValidationHandler = new JwksValidationHandler();
this.oauthService.setStorage(this.storageService);
this.oauthService.setupAutomaticSilentRefresh();
// This is what deald with the responded code and does the magic
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
// initialNavigation: false needs because of the OIDC package!!!
// https://manfredsteyer.github.io/angular-oauth2-oidc/docs/additional-documentation/routing-with-the-hashstrategy.html
this.router.navigate(['/']);
});
}
isCodeFlow(): boolean {
return this._authConfig.responseType === 'code';
}
// private getAuthConfig(codeFlow = false): AuthConfig {
// const oauth2: OauthConfigModel = Object.assign({});
// return {
// issuer: oauth2.host,
// loginUrl: `${oauth2.host}/protocol/openid-connect/auth`,
// silentRefreshRedirectUri: oauth2.redirectSilentIframeUri,
// redirectUri: window.location.origin + oauth2.redirectUri,
// postLogoutRedirectUri: window.location.origin + oauth2.redirectUriLogout,
// clientId: oauth2.clientId,
// scope: oauth2.scope,
// ...(codeFlow ? { responseType: 'code' } : {})
// };
// }
}

View File

@@ -0,0 +1,203 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Injectable } from '@angular/core';
import { Observable, from, throwError, ReplaySubject, of } from 'rxjs';
import { LogService } from '../../../../src/lib/common/services/log.service';
import { RedirectionModel } from '../../models/redirection.model';
import { AppConfigService, AppConfigValues } from '@alfresco/adf-core';
import { PeopleApi, UserProfileApi, UserRepresentation } from '@alfresco/js-api';
import { JwtHelperService } from '../../services/jwt-helper.service';
import { StorageService } from '../../../../src/lib/common/services/storage.service';
import { OauthConfigModel } from '../../models/oauth-config.model';
import { BaseAuthenticationService } from '../base-authentication.service';
import { ADFAuthenticationService } from '../authentication.interface';
import { AlfrescoApiClientFactory } from '../../alfresco-api';
import { OAuthService } from 'angular-oauth2-oidc';
import minimatch from 'minimatch';
@Injectable({
providedIn: 'root'
})
export class AuthService extends BaseAuthenticationService implements ADFAuthenticationService {
onLogin: ReplaySubject<any> = new ReplaySubject<any>(1);
onLogout: ReplaySubject<any> = new ReplaySubject<any>(1);
get peopleApi(): PeopleApi {
return this.alfrescoApiClientFactory.getPeopleApi();
}
get profileApi(): UserProfileApi {
return this.alfrescoApiClientFactory.getProfileApi();
}
constructor(
private alfrescoApiClientFactory: AlfrescoApiClientFactory,
private appConfig: AppConfigService,
private storageService: StorageService,
private oauthService: OAuthService,
private logService: LogService) {
super();
// this.alfrescoApi.alfrescoApiInitialized.subscribe(() => {
// this.alfrescoApi.getInstance().reply('logged-in', () => {
// this.onLogin.next();
// });
// if (this.isKerberosEnabled()) {
// this.loadUserDetails();
// }
// });
}
// private loadUserDetails() {
// const ecmUser$ = from(this.peopleApi.getPerson('-me-'));
// const bpmUser$ = this.getBpmLoggedUser();
// if (this.isALLProvider()) {
// forkJoin([ecmUser$, bpmUser$]).subscribe(() => this.onLogin.next());
// } else if (this.isECMProvider()) {
// ecmUser$.subscribe(() => this.onLogin.next());
// } else {
// bpmUser$.subscribe(() => this.onLogin.next());
// }
// }
isLoggedIn(): boolean {
return this.oauthService.hasValidAccessToken() && this.oauthService.hasValidIdToken();
}
isLoggedInWith(provider?: string): boolean {
console.log(provider);
return this.isLoggedIn();
}
isKerberosEnabled(): boolean {
return this.appConfig.get<boolean>(AppConfigValues.AUTH_WITH_CREDENTIALS, false);
}
isOauth(): boolean {
return this.appConfig.get(AppConfigValues.AUTHTYPE) === 'OAUTH';
}
oidcHandlerEnabled(): boolean {
const oauth2: OauthConfigModel = Object.assign({}, this.appConfig.get<OauthConfigModel>(AppConfigValues.OAUTHCONFIG, null));
return oauth2?.handler === 'oidc';
}
isImplicitFlow() {
const oauth2: OauthConfigModel = Object.assign({}, this.appConfig.get<OauthConfigModel>(AppConfigValues.OAUTHCONFIG, null));
return !!oauth2?.implicitFlow;
}
isAuthCodeFlow() {
const oauth2: OauthConfigModel = Object.assign({}, this.appConfig.get<OauthConfigModel>(AppConfigValues.OAUTHCONFIG, null));
return !!oauth2?.codeFlow;
}
isPublicUrl(): boolean {
const oauth2: OauthConfigModel = Object.assign({}, this.appConfig.get<OauthConfigModel>(AppConfigValues.OAUTHCONFIG, null));
const publicUrls = oauth2.publicUrls || [];
if (Array.isArray(publicUrls)) {
return publicUrls.length > 0 &&
publicUrls.some((urlPattern: string) => minimatch(window.location.href, urlPattern));
}
return false;
}
isECMProvider(): boolean {
return this.appConfig.get<string>(AppConfigValues.PROVIDERS).toUpperCase() === 'ECM';
}
isBPMProvider(): boolean {
return this.appConfig.get<string>(AppConfigValues.PROVIDERS).toUpperCase() === 'BPM';
}
isALLProvider(): boolean {
return this.appConfig.get<string>(AppConfigValues.PROVIDERS).toUpperCase() === 'ALL';
}
login(): Observable<{ type: string; ticket: any }> {
return of();
}
ssoImplicitLogin() {
this.oauthService.initLoginFlow();
}
ssoCodeFlowLogin() {
this.oauthService.initCodeFlow();
}
isRememberMeSet(): boolean {
return true;
}
logout() {
this.oauthService.logOut();
return of();
}
getTicketEcm(): string | null {
return null;
}
getTicketBpm(): string | null {
return null;
}
getTicketEcmBase64(): string | null {
return null;
}
isEcmLoggedIn(): boolean {
return this.isLoggedIn();
}
isBpmLoggedIn(): boolean {
return this.isLoggedIn();
}
getEcmUsername(): string {
return 'To Be Implemented';
}
getBpmUsername(): string {
return 'To Be Implemented';
}
setRedirect(url?: RedirectionModel) {
console.log(url);
// noop
}
getRedirect(): string {
// noop
return 'noop';
}
getBpmLoggedUser(): Observable<UserRepresentation> {
return from(this.profileApi.getProfile());
}
handleError(error: any): Observable<any> {
this.logService.error('Error when logging in', error);
return throwError(error || 'Server error');
}
getToken(): string {
return this.storageService.getItem(JwtHelperService.USER_ACCESS_TOKEN);
}
}

View File

@@ -0,0 +1,25 @@
/*!
* @license
* Copyright 2019 Alfresco Software, Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { StorageService } from '../common';
import { AppConfigService, AppConfigValues } from './app-config.service';
export function loadAppConfig(appConfigService: AppConfigService, storageService: StorageService) {
return () => appConfigService.load().then(() => {
storageService.prefix = appConfigService.get<string>(AppConfigValues.STORAGE_PREFIX, '');
});
}

View File

@@ -16,8 +16,19 @@
*/
import { HttpClientModule } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { APP_INITIALIZER, ModuleWithProviders, NgModule } from '@angular/core';
import { StorageService } from '../common';
import { loadAppConfig } from './app-config.loader';
import { AppConfigPipe } from './app-config.pipe';
import { AppConfigService } from './app-config.service';
interface AppConfigModuleConfig {
loadConfig: boolean;
}
const defaultConfig: AppConfigModuleConfig = {
loadConfig: true
};
@NgModule({
imports: [
@@ -31,4 +42,18 @@ import { AppConfigPipe } from './app-config.pipe';
]
})
export class AppConfigModule {
static forRoot(config: AppConfigModuleConfig = defaultConfig): ModuleWithProviders<AppConfigModule> {
return {
ngModule: AppConfigModule,
providers: [
...(config.loadConfig ?
[{
provide: APP_INITIALIZER,
useFactory: loadAppConfig,
deps: [ AppConfigService, StorageService ], multi: true }
] : []
)
]
};
}
}

View File

@@ -28,6 +28,7 @@ import { OpenidConfiguration } from '../auth/interfaces/openid-configuration.int
export enum AppConfigValues {
APP_CONFIG_LANGUAGES_KEY = 'languages',
PROVIDERS = 'providers',
AUTH_CONFIG = 'authentication',
OAUTHCONFIG = 'oauth2',
ECMHOST = 'ecmHost',
BASESHAREURL = 'baseShareUrl',

View File

@@ -64,6 +64,14 @@ import { HttpClientModule, HttpClientXsrfModule, HTTP_INTERCEPTORS } from '@angu
import { AuthenticationService } from './auth/services/authentication.service';
import { MAT_SNACK_BAR_DEFAULT_OPTIONS } from '@angular/material/snack-bar';
interface LegacyMonolithCoreModuleConfig {
authByJsApi: boolean;
}
const defaultConfig: LegacyMonolithCoreModuleConfig = {
authByJsApi: true
};
@NgModule({
imports: [
TranslateModule,
@@ -142,21 +150,20 @@ import { MAT_SNACK_BAR_DEFAULT_OPTIONS } from '@angular/material/snack-bar';
]
})
export class CoreModule {
static forRoot(): ModuleWithProviders<CoreModule> {
static forRoot(config: LegacyMonolithCoreModuleConfig = defaultConfig): ModuleWithProviders<CoreModule> {
debugger;
return {
ngModule: CoreModule,
providers: [
TranslateStore,
TranslateService,
{ provide: TranslateLoader, useClass: TranslateLoaderService },
{
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [
AlfrescoApiService
],
multi: true
},
...(config.authByJsApi ?
[{
provide: APP_INITIALIZER,
useFactory: startupServiceFactory,
deps: [ AlfrescoApiService ], multi: true
}] : []),
{
provide: APP_INITIALIZER,
useFactory: directionalityConfigFactory,