Ali Behzadian Nejad
Ali Behzadian Nejad

Reputation: 9044

How to get current logged in user in Spring Cloud microservices?

I have a Spring Cloud application with Gateway microservice powered with Zuul. Gateway main responsibility is to authenticate and authorize users with Spring Security and JWT. Now in other microservices that are behind the Gateway, I want to get current logged in user. Any idea?

Upvotes: 0

Views: 2028

Answers (1)

Sridhar Patnaik
Sridhar Patnaik

Reputation: 1118

I implemented a similar architecture. I achieved this in below way

Step 1 - Configure Zuul to pass headers to downstream systems by configuring sensitive headers in application properties.

zuul.sensitiveHeaders=Cookie,Set-Cookie

Step 2 - Expose an endpoint in gateway that returns currently logged in user details

public UserReturnData fetchUserDetails() 
    {
        UserReturnData userReturnData = new UserReturnData();
        List<String> roles = new ArrayList<String>();

        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        userReturnData.setUsername(auth.getName());
        Long id=uRepo.findId(auth.getName());
        userReturnData.setId(id);
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder
                .getContext().getAuthentication().getAuthorities();
        for (SimpleGrantedAuthority authority : authorities) {
            roles.add(authority.getAuthority());
        }
        userReturnData.setRoles(roles);
        return userReturnData;
    }

Step 3 - From your micro-service, make API call (using resttemplate or web-client) to this exposed endpoint with bearer string in header.

@Service
public class UserDetailsService 
{
    @Autowired
    WebClient.Builder webClientBuilder;
    
    @Autowired
    HttpServletRequest request;
    
    @Value("${common.serverurl}")
    private String reqUrl;
    
    public UserReturnData getCurrentUser()
    {
        UserReturnData userDetails = webClientBuilder.build()
                            .get()
                            .uri(reqUrl+"user/me")
                            .header("Authorization", request.getHeader("Authorization"))
                            .retrieve()
                            .bodyToMono(UserReturnData.class)
                            .block();
        return userDetails;
    }
}

This is if you want to keep it simple. If you have more complex requirements, you can use zuul filters.

Upvotes: 1

Related Questions