Commit 6d6c617a authored by Javi Corvi's avatar Javi Corvi
Browse files

oauth2.0 keyclock spring

parent 7c9aaf1b
Pipeline #26590 failed with stage
in 22 seconds
<a *ngIf="!getIsLogged()" (click)="login()">Login</a>
<span *ngIf="getIsLogged()" class="navbar-brand"> Welcome {{userName}} </span>
<a *ngIf="getIsLogged()" (click)="logout()">Logout</a>
<router-outlet *ngIf="getIsLogged()"></router-outlet>
<!--The content below is only a placeholder and can be replaced.-->
<!-- <div style="text-align:center">
<h1>
......@@ -32,7 +39,7 @@
[active]="rla.isActive" > {{link.label}}
</a>
</nav> -->
<router-outlet></router-outlet>
<!-- <router-outlet></router-outlet> -->
<!-- <app-messages></app-messages> -->
<!-- <app-footer></app-footer> -->
<!--<router-outlet></router-outlet>-->
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { LoginService } from './login.service';
import { Subscription } from 'rxjs';
import { DocumentService } from './document.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
......@@ -9,7 +13,15 @@ export class AppComponent {
title = 'angular-material-tab-router';
navLinks: any[];
activeLinkIndex = -1;
constructor(private router: Router) {
userName = '';
text = '';
helloSubs : Subscription;
constructor(private authService: LoginService, private router: Router, private documentService: DocumentService) {
this.configure();
/*this.helloSubs=this.documentService.hello().subscribe(response => {
this.text = response
})*/
this.navLinks = [
{
label: 'First',
......@@ -25,10 +37,42 @@ export class AppComponent {
index: 2
},
];
// alert('app');
// alert(this.authService.getIsLogged());
// if(!this.authService.getIsLogged()){
// this.login();
// }else{
// alert(this.authService.getUsername());
// }
}
ngOnInit(): void {
this.router.events.subscribe((res) => {
this.activeLinkIndex = this.navLinks.indexOf(this.navLinks.find(tab => tab.link === '.' + this.router.url));
});
}
login() {
this.authService.login();
}
private configure() {
this.authService.configure();
}
logout() {
this.authService.logout();
}
getIsLogged(){
if (this.authService.getIsLogged()){
this.userName=this.authService.getUsername();
}
return this.authService.getIsLogged();
}
}
......@@ -25,7 +25,7 @@ import { SrdomainLevelComponent } from './srdomain-level/srdomain-level.componen
import { LogoutComponent } from './logout/logout.component';
import { HistoryTrackingComponent } from './history-tracking/history-tracking.component';
import {MatProgressSpinnerModule, MatProgressBarModule} from '@angular/material'
import {OAuthModule} from "angular-oauth2-oidc";
@NgModule({
......@@ -55,15 +55,20 @@ import {MatProgressSpinnerModule, MatProgressBarModule} from '@angular/material'
MatTabsModule,
BrowserAnimationsModule,
MatToolbarModule,
MatProgressSpinnerModule,
MatProgressBarModule
MatProgressBarModule,
OAuthModule.forRoot({
resourceServer: {
allowedUrls: ['http://localhost:8090/pretoxapi'],
sendAccessToken: true
}
}),
],
providers: [LoginService, CookieService, {
providers: [LoginService, CookieService, /*{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorService,
multi: true
}],
}*/],
bootstrap: [AppComponent],
exports: [HeaderComponent, FooterComponent, DocumentsComponent, DocumentDetailComponent, MessagesComponent]
})
......
import {AuthConfig} from 'angular-oauth2-oidc';
export const authConfig: AuthConfig = {
issuer: 'http://localhost:8050/auth/realms/oauth2-pretox-local',
redirectUri: window.location.origin,
clientId: 'pretoxtm-app',
responseType: 'code',
strictDiscoveryDocumentValidation: false,
scope: 'openid profile email offline_access',
showDebugInformation: true,
}
\ No newline at end of file
......@@ -10,15 +10,23 @@ import { LoginService } from './login.service';
constructor(private authService: LoginService, private router: Router) {}
canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
let loged_in = this.authService.isUserLoggedIn();
//alert(loged_in);
if (!loged_in) {
//alert(1);
this.router.navigateByUrl('/login');
return false;
} else {
//alert(2);
if (!this.authService.getIsLogged()) {
//this.authService.login();
return true;
}
}
return true;
// let loged_in = this.authService.getIsLogged();
// //alert(loged_in);
// if (!loged_in) {
// alert('no logeado');
// this.authService.login();
// return false;
// } else {
// alert('logeado');
// return true;
// }
}
}
\ No newline at end of file
......@@ -229,5 +229,9 @@ export class DocumentService {
return of(result as T);
};
}
hello(): Observable<string> {
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.get("http://localhost:8090/pretoxapi/hello",
{headers, responseType: 'text'});
}
}
......@@ -9,17 +9,19 @@ export class HttpInterceptorService implements HttpInterceptor {
constructor(private authenticationService: LoginService) { }
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
if (this.authenticationService.isUserLoggedIn() && req.url.indexOf('basicauth') === -1) {
const authReq = req.clone({
headers: new HttpHeaders({
'Content-Type': 'application/json',
'Authorization': sessionStorage.getItem('tokenUser')
//'Authorization': `Basic ${window.btoa(this.authenticationService.username + ":" + this.authenticationService.password)}`
})
});
return next.handle(authReq);
} else {
return next.handle(req);
}
alert('interceptor para agregarle el token viejo');
return next.handle(req);
// if (this.authenticationService.isUserLoggedIn() && req.url.indexOf('basicauth') === -1) {
// const authReq = req.clone({
// headers: new HttpHeaders({
// 'Content-Type': 'application/json',
// 'Authorization': sessionStorage.getItem('tokenUser')
// //'Authorization': `Basic ${window.btoa(this.authenticationService.username + ":" + this.authenticationService.password)}`
// })
// });
// return next.handle(authReq);
// } else {
// return next.handle(req);
// }
}
}
\ No newline at end of file
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { map } from 'rxjs/operators';
import {OAuthService, NullValidationHandler} from "angular-oauth2-oidc";
import { environment } from './../environments/environment';
import {authConfig} from "./auth.config";
@Injectable({
providedIn: 'root'
})
......@@ -13,9 +15,21 @@ export class LoginService {
public username: String;
public password: String;
public isLogged: boolean;
constructor(private http: HttpClient,private oauthService: OAuthService) {
constructor(private http: HttpClient) {
}
authenticationService2(username: String, password: String) {
const url = `http://localhost:8050/auth/realms/oauth2-pretox-local/protocol/openid-connect/token`;
return this.http.get(url,
{ headers: { authorization: this.createBasicAuthToken(username, password) } }).pipe(map((res) => {
this.username = username;
this.password = password;
this.registerSuccessfulLogin(username, password);
}));
}
authenticationService(username: String, password: String) {
......@@ -26,7 +40,8 @@ export class LoginService {
this.password = password;
this.registerSuccessfulLogin(username, password);
}));
}
}
createBasicAuthToken(username: String, password: String) {
return 'Basic ' + window.btoa(username + ":" + password)
......@@ -37,7 +52,7 @@ export class LoginService {
sessionStorage.setItem(this.USER_BASIC_TOKEN_ATTRIBUTE_NAME, this.createBasicAuthToken(username, password));
}
logout() {
logout_old() {
sessionStorage.removeItem(this.USER_NAME_SESSION_ATTRIBUTE_NAME);
this.username = null;
this.password = null;
......@@ -54,4 +69,58 @@ export class LoginService {
if (user === null) return '';
return user;
}
public logout() { this.oauthService.logOut(); }
public refresh() { this.oauthService.silentRefresh(); }
public hasValidToken() { return this.oauthService.hasValidAccessToken(); }
// These normally won't be exposed from a service like this, but
// for debugging it makes sense.
public get accessToken() { return this.oauthService.getAccessToken(); }
public get refreshToken() { return this.oauthService.getRefreshToken(); }
public get identityClaims() { return this.oauthService.getIdentityClaims(); }
public get idToken() { return this.oauthService.getIdToken(); }
public get logoutUrl() { return this.oauthService.logoutUrl; }
public getUsername(): string {
return this.oauthService.getIdentityClaims()[`name`];
}
configure(): void {
this.oauthService.configure(authConfig);
this.oauthService.tokenValidationHandler = new NullValidationHandler();
this.oauthService.setupAutomaticSilentRefresh();
this.oauthService.loadDiscoveryDocumentAndTryLogin();
// this.oauthService.loadDiscoveryDocument().then(() => this.oauthService.tryLogin())
// .then(() => {
// if (this.oauthService.getIdentityClaims()) {
// this.isLogged = this.getIsLogged();
// //this.isAdmin = this.loginService.getIsAdmin();
// this.username = this.getUsername();
// //this.messageService.sendMessage(this.loginService.getUsername());
// }
// });
}
login() {
this.oauthService.initLoginFlow();
// this.oauthService.initImplicitFlowInternal();
}
/*public configure() {
this.oauthService.configure(authConfig);
this.oauthService.loadDiscoveryDocumentAndTryLogin();
}*/
public getIsLogged(): boolean {
//alert(this.oauthService.hasValidIdToken());
//alert(this.oauthService.hasValidAccessToken());
return (this.oauthService.hasValidIdToken() && this.oauthService.hasValidAccessToken());
}
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment