开发者社区 > 云效DevOps > 通义灵码 > 正文

angular作为前端 应用openid-client库 使用Spring Gateway

angular作为前端,应用openid-client库,集成使用Spring Cloud Gateway 对接 Spring Authorization Server

展开
收起
zmhhxl 2024-03-25 10:33:32 34 0
2 条回答
写回答
取消 提交回答
  • 要实现这个需求,你需要按照以下步骤操作:

    1. 在Angular项目中安装openid-client库:
    npm install openid-client --save
    
    1. 在Angular项目中创建一个服务(例如: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();
      }
    }
    
    1. 在Spring Cloud Gateway中配置路由规则,将请求转发到Spring Authorization Server:
    spring:
      cloud:
        gateway:
          routes:
            - id: auth-server
              uri: http://your-authorization-server.com
              predicates:
                - Path=/oauth2/**
              filters:
                - StripPrefix=1
    
    1. 在Angular项目中的登录组件(例如:login.component.html)中添加登录按钮,点击后调用AuthService中的login()方法:
    <button (click)="authService.login()">登录</button>
    
    1. 在Angular项目中的注销组件(例如:logout.component.html)中添加注销按钮,点击后调用AuthService中的logout()方法:
    <button (click)="authService.logout()">注销</button>
    
    1. 在Angular项目中的其他组件中,可以通过订阅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) {}
    }
    
    1. 在Angular项目的模板中,可以使用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认证。

    2024-03-31 17:08:55
    赞同 展开评论 打赏
  • 要实现这个需求,你需要按照以下步骤操作:

    1. 在Angular项目中安装openid-client库:
    npm install openid-client --save
    
    1. 在Angular项目中创建一个服务(例如: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();
      }
    }
    
    1. 在Angular项目的app.module.ts中导入AuthService并将其添加到提供者列表中:
    import { AuthService } from './auth.service';
    
    @NgModule({
      ...
      providers: [AuthService],
      ...
    })
    export class AppModule { }
    
    1. 在Angular项目中的登录和注销组件中使用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();
      }
    }
    
    1. 配置Spring Cloud Gateway以将请求代理到Spring Authorization Server。在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。

    2024-03-31 15:54:50
    赞同 展开评论 打赏

通义灵码智能编码助手

相关电子书

更多
Vue.js 在前端服务化上的探索与实践 立即下载
阿里文娱大前端技术实践 立即下载
前端代码是怎样智能生成的 立即下载