如果用户已在 Java 中通过身份验证,是否让用户在 angular 屏幕上保持登录状态?

Keep user logged In on angular screen if user was already authenticated in Java?

我正在开发一个使用 OKTA 进行身份验证的 JavaEE Web 应用程序。现在我已经创建了一个 angular 8 应用程序,并想从 Java 门户 link angular 应用程序。我的要求是我应该在重定向的 angular 应用程序中登录。

如何实现?

您可以在您的 Angular 应用程序中创建一个 AuthService 来与您的后端 Java 应用程序对话以获取身份验证信息。此示例与使用 Spring 安全性的 Spring 启动应用程序对话,但希望它传达了这个想法。

import { Injectable } from '@angular/core';
import { Location } from '@angular/common';
import { BehaviorSubject, Observable } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { environment } from '../../environments/environment';
import { User } from './user';
import { map } from 'rxjs/operators';

const headers = new HttpHeaders().set('Accept', 'application/json');

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  $authenticationState = new BehaviorSubject<boolean>(false);

  constructor(private http: HttpClient, private location: Location) {
  }

  getUser(): Observable<User> {
    return this.http.get<User>(`${environment.apiUrl}/user`, {headers}).pipe(
      map((response: User) => {
        if (response !== null) {
          this.$authenticationState.next(true);
          return response;
        }
      })
    );
  }

  isAuthenticated(): Promise<boolean> {
    return this.getUser().toPromise().then((user: User) => { 
      return user !== undefined;
    }).catch(() => {
      return false;
    })
  }

  login(): void {
    location.href =
      `${location.origin}${this.location.prepareExternalUrl('oauth2/authorization/okta')}`; 
  }

  logout(): void {
    const redirectUri = `${location.origin}${this.location.prepareExternalUrl('/')}`;

    this.http.post(`${environment.apiUrl}/api/logout`, {}).subscribe((response: any) => { 
      location.href = response.logoutUrl + '?id_token_hint=' + response.idToken
        + '&post_logout_redirect_uri=' + redirectUri;
    });
  }
}

User class 是:

export class User {
  sub: number;
  fullName: string;
}

AuthServiceapp.component.ts中的用法如下:

import { Component, OnInit } from '@angular/core';
import { AuthService } from './shared/auth.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit {
  isAuthenticated: boolean;

  constructor(public auth: AuthService) {
  }

  async ngOnInit() {
    this.isAuthenticated = await this.auth.isAuthenticated();
    this.auth.$authenticationState.subscribe(
      (isAuthenticated: boolean)  => this.isAuthenticated = isAuthenticated
    );
  }
}

我的 /user 端点允许匿名访问并且是用 Kotlin 编写的。它看起来如下:

@GetMapping("/user")
fun user(@AuthenticationPrincipal user: OidcUser?): OidcUser? {
    return user;
}
当用户通过身份验证时,

OidcUser 由 Spring 安全注入。当用户未通过身份验证时,返回空响应。