angnewb
angnewb

Reputation: 115

Spring boot controller retrieve UserDetails

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

Upvotes: 0

Views: 229

Answers (3)

Hemant
Hemant

Reputation: 1438

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.

Upvotes: 0

possum
possum

Reputation: 2925

UserDetails comes in the security context in the principal

UserDetails userDetails =
 (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();

Upvotes: 0

Aniket Sahrawat
Aniket Sahrawat

Reputation: 12937

You can simply inject it using @AuthenticationPrincipal. Eg:

@GetMapping("/validateToken")
public String validateToken(@AuthenticationPrincipal UserDetails userDetails, ...

Upvotes: 1

Related Questions