angular作为前端,应用openid-client库,集成使用Spring Cloud Gateway 对接 Spring Authorization Server
版权声明:本文内容由阿里云实名注册用户自发贡献,版权归原作者所有,阿里云开发者社区不拥有其著作权,亦不承担相应法律责任。具体规则请查看《阿里云开发者社区用户服务协议》和《阿里云开发者社区知识产权保护指引》。如果您发现本社区中有涉嫌抄袭的内容,填写侵权投诉表单进行举报,一经查实,本社区将立刻删除涉嫌侵权内容。
要实现这个需求,你需要按照以下步骤操作:
npm install openid-client --save
auth.service.ts),并使用openid-client库进行OAuth2认证:import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, map, take } from 'rxjs/operators';
import { OidcClientSettings, OidcInfo, UserManagerSettings } from 'oidc-client';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private userManager: any;
  private userInfo$: BehaviorSubject<OidcInfo> = new BehaviorSubject<OidcInfo>(null);
  constructor() {
    const settings: UserManagerSettings = {
      authority: 'https://your-authorization-server.com',
      client_id: 'your-client-id',
      redirect_uri: 'http://localhost:4200/callback',
      response_type: 'code',
      scope: 'openid profile email',
      post_logout_redirect_uri: 'http://localhost:4200/',
    };
    this.userManager = new UserManager(settings);
    this.userManager.getUser().then((user) => {
      if (user && !user.expired) {
        this.userInfo$.next(user);
      } else {
        this.login();
      }
    });
  }
  login(): void {
    this.userManager.signinRedirect().catch((err) => console.error(err));
  }
  logout(): void {
    this.userManager.signoutRedirect().catch((err) => console.error(err));
  }
  getUserInfo(): Observable<OidcInfo> {
    return this.userInfo$.asObservable();
  }
}
spring:
  cloud:
    gateway:
      routes:
        - id: auth-server
          uri: http://your-authorization-server.com
          predicates:
            - Path=/oauth2/**
          filters:
            - StripPrefix=1
login.component.html)中添加登录按钮,点击后调用AuthService中的login()方法:<button (click)="authService.login()">登录</button>
logout.component.html)中添加注销按钮,点击后调用AuthService中的logout()方法:<button (click)="authService.logout()">注销</button>
AuthService中的getUserInfo()方法获取用户信息。例如,在app.component.ts中:import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userInfo$ = this.authService.getUserInfo();
  constructor(private authService: AuthService) {}
}
async管道订阅userInfo$,根据用户信息显示不同的内容。例如,在app.component.html中:<div *ngIf="userInfo$ | async as userInfo">
  <h1>欢迎,{{ userInfo?.profile.name }}</h1>
</div>
通过以上步骤,你可以实现Angular前端应用使用openid-client库与Spring Cloud Gateway对接Spring Authorization Server进行OAuth2认证。
要实现这个需求,你需要按照以下步骤操作:
npm install openid-client --save
auth.service.ts),并使用openid-client库进行OAuth2认证:import { Injectable } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { filter, map, take } from 'rxjs/operators';
import { OidcClientSettings, OidcInfo, UserManerSettings } from 'oidc-client';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private userManager: any;
  private userInfo$: BehaviorSubject<OidcInfo> = new BehaviorSubject<OidcInfo>(null);
  constructor() {
    const settings: UserManagerSettings = {
      authority: 'https://your-authorization-server.com',
      client_id: 'your-client-id',
      redirect_uri: 'http://localhost:4200/callback',
      response_type: 'code',
      scope: 'openid profile email',
      post_logout_redirect_uri: 'http://localhost:4200/',
    };
    this.userManager = new UserManager(settings);
    this.userManager.getUser().then((user) => {
      if (user && !user.expired) {
        this.userInfo$.next(user);
      } else {
        this.login();
      }
    });
  }
  login(): void {
    this.userManager.signinRedirect().catch((err) => console.error(err));
  }
  logout(): void {
    this.userManager.signoutRedirect().catch((err) => console.error(err));
  }
  getUserInfo(): Observable<OidcInfo> {
    return this.userInfo$.asObservable();
  }
}
app.module.ts中导入AuthService并将其添加到提供者列表中:import { AuthService } from './auth.service';
@NgModule({
  ...
  providers: [AuthService],
  ...
})
export class AppModule { }
AuthService:import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
  selector: 'app-login',
  template: `
    <button (click)="login()">登录</button>
  `,
})
export class LoginComponent {
  constructor(private authService: AuthService) {}
  login(): void {
    this.authService.login();
  }
}
@Component({
  selector: 'app-logout',
  template: `
    <button (click)="logout()">注销</button>
  `,
})
export class LogoutComponent {
  constructor(private authService: AuthService) {}
  logout(): void {
    this.authService.logout();
  }
}
application.yml中添加以下配置:spring:
  cloud:
    gateway:
      routes:
        - id: auth-server
          uri: https://your-authorization-server.com
          predicates:
            - Path=/oauth2/**
          filters:
            - StripPrefix=1
这样,当用户访问/oauth2/**路径时,请求将被代理到Spring Authorization Server。