0

Hello so i have this method in JwtUtill

public Boolean validateToken(String token, UserDetails userDetails) {
    final String username = extractEmail(token);
    return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
}

But how can i request UserDetails in controller?

@GetMapping("/validateToken")
public String validateToken(@RequestHeader(value="token") String token) {
    if(jwtUtil.validateToken(token,???)) {

    }
}

Angular side

  public isTokenExpired(): Observable<string> {
    const headers = new HttpHeaders().set('token', localStorage.getItem('token'));
    return this.httpClient.get<string>('http://localhost:8080/api/validateToken', {headers, responseType: 'text' as 'json'});
  }

Also as frontend im using angular

angnewb
  • 115
  • 2
  • 8
  • Does this answer your question? [How to get active user's UserDetails](https://stackoverflow.com/questions/8764545/how-to-get-active-users-userdetails) – jannis May 12 '20 at 10:35
  • It return null for me.. – angnewb May 12 '20 at 10:52
  • @angnewb It should be class which extends userdetails rather userdetails itself. You need to have user class which extends userdetails then you can pass. – Kramer May 12 '20 at 10:56

3 Answers3

1

You can simply inject it using @AuthenticationPrincipal. Eg:

@GetMapping("/validateToken")
public String validateToken(@AuthenticationPrincipal UserDetails userDetails, ...
Aniket Sahrawat
  • 12,410
  • 3
  • 41
  • 67
0

UserDetails comes in the security context in the principal

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
possum
  • 1,837
  • 3
  • 9
  • 18
0

It seems like you are using jwt, you don't need UserDetails to compare it with.

change methods as :

public Boolean validateToken(String token) {
    final String username = extractEmail(token);
    return (!StringUtils.isEmpty(username) && !isTokenExpired(token));
}
@GetMapping("/validateToken")
public String validateToken(@RequestHeader(value="token") String token) {
    if(jwtUtil.validateToken(token)) {

    }
}

If your token is invalid you will not get exception in extractEmail method and if it is expired then method isTokenExpired will return false.

Hemant
  • 1,403
  • 2
  • 11
  • 21