gpt4 book ai didi

java - 如果用户已经在 J​​ava 中进行了身份验证,请在 Angular 屏幕上保持用户登录状态?

转载 作者:行者123 更新时间:2023-12-01 16:43:26 26 4
gpt4 key购买 nike

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

我怎样才能实现它?

最佳答案

您可以在 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 注入(inject)。当用户未通过身份验证时,将返回空响应。

关于java - 如果用户已经在 J​​ava 中进行了身份验证,请在 Angular 屏幕上保持用户登录状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61818975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com