OAuth2 - протокол авторизации, который позволяет приложениям получать ограниченный доступ к пользовательским данным без раскрытия паролей.
OpenID Connect (OIDC) - надстройка над OAuth2, добавляющая аутентификацию (подтверждение личности пользователя).
npm install angular-oauth2-oidc
import { AuthModule, OAuthModuleConfig } from 'angular-oauth2-oidc';
@NgModule({
imports: [
AuthModule.forRoot(),
HttpClientModule
],
providers: [
{
provide: OAuthModuleConfig,
useValue: {
resourceServer: {
allowedUrls: ['https://api.example.com'],
sendAccessToken: true
}
}
}
]
})
export class AppModule {}
import { OAuthService } from 'angular-oauth2-oidc';
export class AuthService {
constructor(private oauthService: OAuthService) {
this.configureOAuth();
}
private configureOAuth() {
this.oauthService.configure({
issuer: 'https://auth.example.com',
redirectUri: window.location.origin + '/callback',
clientId: 'your-spa-client-id',
responseType: 'code',
scope: 'openid profile email',
strictDiscoveryDocumentValidation: false,
showDebugInformation: true // Только для разработки
});
this.oauthService.loadDiscoveryDocumentAndTryLogin();
}
}
login() {
this.oauthService.initCodeFlow();
}
logout() {
this.oauthService.logOut();
}
get isLoggedIn(): boolean {
return this.oauthService.hasValidAccessToken();
}
get userName(): string {
const claims = this.oauthService.getIdentityClaims();
return claims?.['name'] || '';
}
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { OAuthService } from 'angular-oauth2-oidc';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private oauthService: OAuthService) {}
intercept(req: HttpRequest<any>, next: HttpHandler) {
if (this.oauthService.hasValidAccessToken()) {
req = req.clone({
setHeaders: {
Authorization: `Bearer ${this.oauthService.getAccessToken()}`
}
});
}
return next.handle(req);
}
}
import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { OAuthService } from 'angular-oauth2-oidc';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private oauthService: OAuthService) {}
canActivate(): boolean {
if (this.oauthService.hasValidAccessToken()) {
return true;
}
this.oauthService.initCodeFlow();
return false;
}
}
Добавьте в роутинг:
{
path: 'callback',
component: CallbackComponent
}
import { Component } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
@Component({
template: '<p>Processing login...</p>'
})
export class CallbackComponent {
constructor(private oauthService: OAuthService) {
this.oauthService.loadDiscoveryDocumentAndTryLogin().then(() => {
if (this.oauthService.hasValidAccessToken()) {
window.location.href = '/';
}
});
}
}
this.oauthService.setupAutomaticSilentRefresh();
getUserProfile() {
return this.oauthService.loadUserProfile();
}
this.oauthService.configure({
issuer: 'http://localhost:8080/auth/realms/your-realm',
clientId: 'spa-client',
dummyClientSecret: 'your-secret', // Для PKCE не нужно
responseType: 'code',
redirectUri: window.location.origin + '/callback',
scope: 'openid profile email',
requireHttps: false, // Только для разработки
showDebugInformation: true
});
Для интеграции OAuth2/OIDC с Angular используйте библиотеку angular-oauth2-oidc, реализуйте Authorization Code Flow с PKCE, настройте HTTP Interceptor и Route Guards. Всегда соблюдайте лучшие практики безопасности для SPA-приложений.