Module for the frontend using Angular for OAuth and OpenID Connect (OIDC) authentication. This module utilizes the angular-oauth2-oidc
library to handle the authentication flow.
First, install the angular-oauth2-oidc
library by running npm install angular-oauth2-oidc
in your project directory.
import { Injectable } from '@angular/core';
import { AuthConfig, OAuthService } from 'angular-oauth2-oidc';
@Injectable({
providedIn: 'root'
})
export class AuthService {
private authConfig: AuthConfig = {
issuer: 'https://your-issuer-url.com', // Identity provider's OIDC issuer URL
clientId: 'your-client-id', // Client ID registered with the identity provider
redirectUri: window.location.origin + '/callback', // Callback URL after authentication
scope: 'openid profile email', // Requested scopes
};
constructor(private oauthService: OAuthService) {
this.configure();
}
private configure(): void {
this.oauthService.configure(this.authConfig);
this.oauthService.setupAutomaticSilentRefresh();
this.oauthService.loadDiscoveryDocumentAndLogin();
}
login(): void {
this.oauthService.initCodeFlow();
}
logout(): void {
this.oauthService.logOut();
}
isAuthenticated(): boolean {
return this.oauthService.hasValidAccessToken();
}
}
To use this module in your Angular components, you’ll need to import and inject the AuthService
and use its functions. Here’s an example:
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-login',
template: `
You are logged in
`
})
export class LoginComponent {
constructor(private authService: AuthService) { }
login(): void {
this.authService.login();
}
logout(): void {
this.authService.logout();
}
isAuthenticated(): boolean {
return this.authService.isAuthenticated();
}
}
In your Angular component, you can use authService.isAuthenticated()
to check if the user is authenticated, and authService.login()
and authService.logout()
to initiate the authentication flow and log out the user, respectively.
Make sure to replace 'https://your-issuer-url.com'
and 'your-client-id'
with the appropriate values for your specific identity provider and client.
Please note that this is a basic example, and in a real-world application, you would typically handle error handling, routing, and additional logic based on your specific requirements. Additionally, you may need to configure additional options and implement additional logic depending on your use case.