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

痴心易碎 提交于 2020-06-01 07:43:06

问题


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.

How can I achieve it?


回答1:


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;
    });
  }
}

The User class is:

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

The AuthService is used in app.component.ts as follows:

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
    );
  }
}

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;
}

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



来源:https://stackoverflow.com/questions/61818975/keep-user-logged-in-on-angular-screen-if-user-was-already-authenticated-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!