Bhavik Chavda
Bhavik Chavda

Reputation: 37

How to add Jwt Token based security In Microservices

In my microservices, I will try to implement Jwt spring-security, But I don't know how to apply it.

In my microservices, I have used the 2020.0.3 spring cloud version. In user services, I have connected the department service using the Rest template. I need help with how to add Jwt security in these microservices.

This is 4 microservices

Server = Eureka Server

service-API-gateway = Spring cloud Apigateway

service-department & services-user = These two microservices connect with Rest template

Microservices Project Structure : https://i.sstatic.net/ajTiX.png

Upvotes: 2

Views: 710

Answers (1)

Juliyanage Silva
Juliyanage Silva

Reputation: 2699

So at a higher level, Spring Security is applied on controller level when using jwt as authentication. First you need to add a Security config that will extend WebSecurityConfigurerAdapter (this is common for http based security) and in that class you need to define configure method like:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .httpBasic().disable()
            .csrf().disable()  // IF your clients connect without a cookie based, this will be fine
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            .authorizeRequests()
            .antMatchers("/register", "/login","/your_open_endpoints_etc").permitAll()
            .and()
            .addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class);
}

Then in the filter class which extends OncePerRequestFilter, you can define the do filter like this, you have to set the UsernamePasswordAuthenticationFilter instance inside the Spring authentication context:

@Override
protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
    logger.info("do filter...");
    String token = jwtProvider.getTokenFromRequest((HttpServletRequest) httpServletRequest);
    try{
        if (token != null && jwtProvider.validateToken(token)) {
            String username = jwtProvider.getUsernameFromToken(token);
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, null, jwtProvider.getAuthorities(token));
            SecurityContextHolder.getContext().setAuthentication(auth);
        }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
    catch (RuntimeException e)
    {
        // Some general Exception handling that will wrap and send as HTTP Response
    }

}

Check on the extending filters further, they might change as per your requirement

finally in rest endpoints you can safe guard like:

@PreAuthorize("hasRole('ROLE_YOURROLE')")
@GetMapping(path = "/your_secured_endpoint", consumes = "application/json", 
  produces = "application/json")
public ResponseEntity<List<SomePOJOObject>> getAllAppointmentsForPatient()
{
   
    return new ResponseEntity<>(thatSomePOJOObjectListYouWant, HttpStatus.OK);
}

Upvotes: 0

Related Questions