Correcciones ejemplo

This commit is contained in:
Eneko Nieto
2021-01-18 23:59:14 +01:00
parent 3680dd6c2c
commit 9d6bc0dd1b
8 changed files with 35 additions and 120 deletions

View File

@@ -1,6 +1,5 @@
import { authConfig } from './auth.config';
import { Component } from '@angular/core';
import { OAuthService, NullValidationHandler } from 'angular-oauth2-oidc';
import { OAuthService } from 'angular-oauth2-oidc';
import { Router } from '@angular/router';
import { filter } from 'rxjs/operators';
import { authCodeFlowConfig } from './auth-code-flow.config';
@@ -19,14 +18,15 @@ export class AppComponent {
this.oauthService.events
.pipe(filter((e) => e.type === 'token_received'))
.subscribe((_) => {
console.debug('state', this.oauthService.state);
console.log('state', this.oauthService.state);
this.oauthService.loadUserProfile();
});
}
private configureCodeFlow() {
private configureCodeFlow(): void {
this.oauthService.configure(authCodeFlowConfig);
this.oauthService.loadDiscoveryDocumentAndTryLogin().then((_) => {
this.oauthService.loadDiscoveryDocumentAndTryLogin().then((success) => {
console.error('LOGIN success=' + success);
if (useHash) {
this.router.navigate(['/']);
}

View File

@@ -1,7 +1,7 @@
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { OAuthModule, OAuthStorage } from 'angular-oauth2-oidc';
import { OAuthModule } from 'angular-oauth2-oidc';
import { HttpClientModule } from '@angular/common/http';
import { AppComponent } from './app.component';
@@ -29,7 +29,7 @@ const ROUTING_OPTIONS: ExtraOptions = {
SharedModule.forRoot(),
OAuthModule.forRoot({
resourceServer: {
allowedUrls: ['http://www.angular.at/api'],
allowedUrls: ['http://localhost:8080/api'],
sendAccessToken: true
}
})
@@ -44,7 +44,7 @@ const ROUTING_OPTIONS: ExtraOptions = {
// {provide: AuthConfig, useValue: authConfig },
// { provide: OAuthStorage, useValue: localStorage },
// { provide: ValidationHandler, useClass: JwksValidationHandler },
{ provide: BASE_URL, useValue: 'http://www.angular.at' }
{ provide: BASE_URL, useValue: 'http://localhost:8080' }
],
bootstrap: [AppComponent]
})

View File

@@ -1,3 +1,3 @@
import { InjectionToken } from '@angular/core';
export const BASE_URL = new InjectionToken<string>('BASE_URL');
export const BASE_URL = new InjectionToken<string>('http://localhost:8080');

View File

@@ -2,7 +2,7 @@ import { AuthConfig } from 'angular-oauth2-oidc';
import { useSilentRefreshForCodeFlow } from '../flags';
export const authCodeFlowConfig: AuthConfig = {
issuer: 'https://idsvr4.azurewebsites.net',
issuer: 'https://auth.fosil.eu/auth/realms/fosil',
// URL of the SPA to redirect the user to after login
redirectUri:
@@ -13,7 +13,7 @@ export const authCodeFlowConfig: AuthConfig = {
// The SPA's id. The SPA is registerd with this id at the auth-server
// clientId: 'server.code',
clientId: 'spa',
clientId: 'okupamicoche-frontend-angular',
// Just needed if your auth server demands a secret. In general, this
// is a sign that the auth server is not configured with SPAs in mind
@@ -28,8 +28,8 @@ export const authCodeFlowConfig: AuthConfig = {
// Important: Request offline_access to get a refresh token
// The api scope is a usecase specific one
scope: useSilentRefreshForCodeFlow
? 'openid profile email api'
: 'openid profile email offline_access api',
? 'openid profile email'
: 'openid profile email offline_access',
// ^^ Please note that offline_access is not needed for silent refresh
// At least when using idsvr, this even prevents silent refresh

View File

@@ -1,34 +0,0 @@
// This api will come in the next version
import { AuthConfig } from 'angular-oauth2-oidc';
export const authConfig: AuthConfig = {
// Url of the Identity Provider
issuer: 'https://idsvr4.azurewebsites.net',
// URL of the SPA to redirect the user to after login
// redirectUri: window.location.origin
// + ((localStorage.getItem('useHashLocationStrategy') === 'true')
// ? '/#/index.html'
// : '/index.html'),
redirectUri: window.location.origin + '/index.html',
// URL of the SPA to redirect the user after silent refresh
silentRefreshRedirectUri: window.location.origin + '/silent-refresh.html',
// The SPA's id. The SPA is registerd with this id at the auth-server
clientId: 'implicit',
// set the scope for the permissions the client should request
// The first three are defined by OIDC. The 4th is a usecase-specific one
scope: 'openid profile email api',
// silentRefreshShowIFrame: true,
showDebugInformation: true,
sessionChecksEnabled: true
// timeoutFactor: 0.01,
};

View File

@@ -27,34 +27,6 @@
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<h2>Login with Implicit Flow</h2>
<p>
<button class="btn btn-default" (click)="loginImplicit()">Login</button>
<button class="btn btn-default" (click)="logout()">Logout</button>
</p>
<b>Username/Password:</b> max/geheim
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<h2>Login with Implicit Flow in popup</h2>
<p>
<button class="btn btn-default" (click)="loginImplicitInPopup()">
Login
</button>
<button class="btn btn-default" (click)="logout()">Logout</button>
</p>
<p><b>Username/Password:</b> max/geheim</p>
<p>
<b>Note:</b> When using IE, some security settings block the communication
with popups. This prevents that this feature works.
</p>
</div>
</div>
<div class="panel panel-default">
<div class="panel-body">
<h2>Login with Code Flow</h2>

View File

@@ -1,4 +1,3 @@
import { authConfig } from '../auth.config';
import { Component, OnInit } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { authCodeFlowConfig } from '../auth-code-flow.config';
@@ -8,7 +7,7 @@ import { ActivatedRoute } from '@angular/router';
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
loginFailed: boolean = false;
loginFailed = false;
userProfile: object;
usePopup: boolean;
login: false;
@@ -18,9 +17,9 @@ export class HomeComponent implements OnInit {
private oauthService: OAuthService
) {}
ngOnInit() {
ngOnInit(): void {
this.route.params.subscribe(p => {
this.login = p['login'];
this.login = p.login;
});
// This would directly (w/o user interaction) redirect the user to the
@@ -34,29 +33,7 @@ export class HomeComponent implements OnInit {
*/
}
async loginImplicit() {
// Tweak config for implicit flow
this.oauthService.configure(authConfig);
await this.oauthService.loadDiscoveryDocument();
sessionStorage.setItem('flow', 'implicit');
this.oauthService.initLoginFlow('/some-state;p1=1;p2=2?p3=3&p4=4');
// the parameter here is optional. It's passed around and can be used after logging in
}
async loginImplicitInPopup() {
// Tweak config for implicit flow
this.oauthService.configure(authConfig);
await this.oauthService.loadDiscoveryDocument();
sessionStorage.setItem('flow', 'implicit');
this.oauthService.initLoginFlowInPopup().then(() => {
this.loadUserProfile();
});
// the parameter here is optional. It's passed around and can be used after logging in
}
async loginCode() {
async loginCode(): Promise<void> {
// Tweak config for code flow
this.oauthService.configure(authCodeFlowConfig);
await this.oauthService.loadDiscoveryDocument();
@@ -66,7 +43,7 @@ export class HomeComponent implements OnInit {
// the parameter here is optional. It's passed around and can be used after logging in
}
async loginCodeInPopup() {
async loginCodeInPopup(): Promise<void> {
// Tweak config for code flow
this.oauthService.configure(authCodeFlowConfig);
await this.oauthService.loadDiscoveryDocument();
@@ -77,7 +54,7 @@ export class HomeComponent implements OnInit {
});
}
logout() {
logout(): void {
// this.oauthService.logOut();
this.oauthService.revokeTokenAndLogout();
}
@@ -86,19 +63,19 @@ export class HomeComponent implements OnInit {
this.oauthService.loadUserProfile().then(up => (this.userProfile = up));
}
get givenName() {
var claims = this.oauthService.getIdentityClaims();
if (!claims) return null;
get givenName(): any {
const claims = this.oauthService.getIdentityClaims();
if (!claims) { return null; }
return claims['given_name'];
}
get familyName() {
var claims = this.oauthService.getIdentityClaims();
if (!claims) return null;
get familyName(): any {
const claims = this.oauthService.getIdentityClaims();
if (!claims) { return null; }
return claims['family_name'];
}
refresh() {
refresh(): void {
this.oauthService.oidc = true;
if (
@@ -107,12 +84,12 @@ export class HomeComponent implements OnInit {
) {
this.oauthService
.refreshToken()
.then(info => console.debug('refresh ok', info))
.then(info => console.log('refresh ok', info))
.catch(err => console.error('refresh error', err));
} else {
this.oauthService
.silentRefresh()
.then(info => console.debug('silent refresh ok', info))
.then(info => console.log('silent refresh ok', info))
.catch(err => console.error('silent refresh error', err));
}
}
@@ -122,7 +99,7 @@ export class HomeComponent implements OnInit {
localStorage.setItem('requestAccessToken', '' + value);
}
get requestAccessToken() {
get requestAccessToken(): boolean {
return this.oauthService.requestAccessToken;
}
@@ -134,23 +111,23 @@ export class HomeComponent implements OnInit {
}
}
get useHashLocationStrategy() {
get useHashLocationStrategy(): boolean {
return localStorage.getItem('useHashLocationStrategy') === 'true';
}
get id_token() {
get id_token(): string {
return this.oauthService.getIdToken();
}
get access_token() {
get access_token(): string {
return this.oauthService.getAccessToken();
}
get id_token_expiration() {
get id_token_expiration(): number {
return this.oauthService.getIdTokenExpiration();
}
get access_token_expiration() {
get access_token_expiration(): number {
return this.oauthService.getAccessTokenExpiration();
}
}

View File

@@ -6,7 +6,7 @@ import { OAuthService } from 'angular-oauth2-oidc';
export class AuthGuard implements CanActivate {
constructor(private router: Router, private oauthService: OAuthService) {}
canActivate() {
canActivate(): boolean {
if (
this.oauthService.hasValidAccessToken() &&
this.oauthService.hasValidIdToken()