如果用户已经使用Java进行身份验证,是否可以让用户登录到角度屏幕?

问题描述 投票:0回答:1

我正在使用OKTA进行身份验证的JavaEE Web应用程序上工作。现在,我创建了一个angular 8应用程序,并希望从Java门户链接angular应用程序。我的要求是我应该在重定向的角度应用程序上登录。

我该如何实现?

java angular authentication okta
1个回答
0
投票

您可以在Angular应用中创建一个AuthService,与后端Java应用进行对话以获取身份验证信息。该示例与使用Spring Security的Spring Boot应用程序进行了交谈,但希望它能够传达出这一想法。

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类是:

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 Security注入。当用户未通过身份验证时,将返回空响应。

© www.soinside.com 2019 - 2024. All rights reserved.