以下是使用Angular、Spring Boot 2和OAuth2客户端的解决方法,包括代码示例:
ng new angular-oauth2-client
cd angular-oauth2-client
npm install --save @auth0/angular-jwt
npm install --save angular-oauth2-oidc
auth.config.ts
的文件,并添加以下代码:import { AuthConfig } from 'angular-oauth2-oidc';
export const authConfig: AuthConfig = {
issuer: 'http://localhost:8080/auth/realms/your-realm', // 替换为实际的Realm URL
redirectUri: window.location.origin + '/callback',
clientId: 'your-client-id', // 替换为实际的Client ID
scope: 'openid profile email',
requireHttps: false // 在开发环境中,可以禁用HTTPS
};
确保替换issuer
和clientId
为实际的Realm URL和Client ID。
oauth.service.ts
的文件,并添加以下代码:import { Injectable } from '@angular/core';
import { OAuthService } from 'angular-oauth2-oidc';
import { authConfig } from './auth.config';
@Injectable()
export class OAuthService {
constructor(private oauthService: OAuthService) {
this.configure();
}
private configure() {
this.oauthService.configure(authConfig);
this.oauthService.loadDiscoveryDocumentAndTryLogin();
}
login() {
this.oauthService.initImplicitFlow();
}
logout() {
this.oauthService.logOut();
}
getAccessToken() {
return this.oauthService.getAccessToken();
}
}
login.component.ts
的文件,并添加以下代码:import { Component, OnInit } from '@angular/core';
import { OAuthService } from '../oauth.service';
@Component({
selector: 'app-login',
template: `
`
})
export class LoginComponent implements OnInit {
constructor(private oauthService: OAuthService) { }
ngOnInit() {
}
login() {
this.oauthService.login();
}
logout() {
this.oauthService.logout();
}
}
app.component.ts
文件,并添加以下代码:import { Component } from '@angular/core';
import { OAuthService } from './oauth.service';
@Component({
selector: 'app-root',
template: `
Welcome to Angular OAuth2 Client
Access Token: {{ accessToken }}
`,
providers: [OAuthService]
})
export class AppComponent {
accessToken: string;
constructor(private oauthService: OAuthService) {
this.accessToken = this.oauthService.getAccessToken();
}
}
app.component.ts
文件,并添加以下代码:import { Component } from '@angular/core';
import { JwtHelperService } from '@auth0/angular-jwt';
import { OAuthService } from './oauth.service';
@Component({
selector: 'app-root',
template: `
Welcome to Angular OAuth2 Client
Access Token: {{ accessToken }}
User Name: {{ userName }}
`,
providers: [OAuthService]
})
export class AppComponent {
accessToken: string;
userName: string;
constructor(private oauthService: OAuthService, private jwtHelperService: JwtHelperService) {
this.accessToken = this.oauthService.getAccessToken();
this.userName = this.getUserNameFromToken();
}
private getUserNameFromToken(): string {
const decodedToken = this.jwtHelperService.decodeToken(this.accessToken);
return decodedToken ? decodedToken.preferred_username : '';
}
}
确保在app.module.ts
中导入和配置JwtHelperService
:
import { JwtHelperService, JwtModule } from '@auth0/angular-jwt';
@NgModule({
imports: [