如果用户已经通过Java进行身份验证,是否可以在角度屏幕上保持用户登录状态? [英] Keep user logged In on angular screen if user was already authenticated in Java?

查看:88
本文介绍了如果用户已经通过Java进行身份验证,是否可以在角度屏幕上保持用户登录状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am working on a JavaEE web application which uses OKTA for authentication. Now I have created an angular 8 application and want to link the angular app from the Java portal. My requirement is that I should be logged in at redirected angular app.

如何实现?

推荐答案

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

You could create an AuthService in your Angular app that talks to your backend Java app for authentication information. This example talks to a Spring Boot app that uses Spring Security, but hopefully it conveys the idea.

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编写.它看起来如下:

My /user endpoint allows anonymous access and is written in Kotlin. It looks as follows:

@GetMapping("/user")
fun user(@AuthenticationPrincipal user: OidcUser?): OidcUser? {
    return user;
}

当用户通过身份验证时,Spring Security会注入

OidcUser.当用户未通过身份验证时,将返回一个空响应.

OidcUser is injected by Spring Security when the user is authenticated. When the user is not authenticated, an empty response is returned.

这篇关于如果用户已经通过Java进行身份验证,是否可以在角度屏幕上保持用户登录状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆