1
votes

I built 3 microservices using Spring Boot:

1) Auth service - creates JWT.

2 and 3 - microservices (REST API) that do something.

Theoretically the user can access microservices 2 and 3 without the token created by microservice 1.

Lets say I'm passing the token to microservices 2 and 3 - How can I verify the token's integrity? Is microservices 2 and 3 needs to communicate with microservice 1?

If someone has a good example it will be great.

1
you will need to have the following scenario a user wants to access to 2 and 3 then from 2 and 3 needs to communicate against auth, to check JWT token then if it is OK, continue on 2 and 3. that is.Jonathan JOhx
A typical pattern which might be used here is the gateway/facade pattern. All incoming requests for any microservice would first hit the gateway API, which would then check the JWT to see if it still be valid. If not, then the request would be immediately rejected. Otherwise, the request would be allowed to continue to the microservice.Tim Biegeleisen
Hello Avi, have a look at my answer, I have also given a working exampleRomil Patel

1 Answers

0
votes

JWT Example

1. /authenticate --> Auth Service - Creates JWT.
2. /public/profile --> can be accessed without JWT Token
3. /public/resource --> can be accessed without JWT Token
4. /private/users --> can be accessed with JWT Token

Consider the above endPoints of your application. Here,

  • /**/public/** will be accessible to everyone doesn't matter JWT Token is present or not
  • /**/private/** will be accessible to the clients which have JWT Token. if a token is not present it will response with 401/403 (Unauthorized/Forbidden)

Now coming to the coding part. You have to create one WebSecurityConfig class which extends WebSecurityConfigurerAdapter which override the configure(HttpSecurity http)

public class WebSecurityConfig extends WebSecurityConfigurerAdapter
{ 
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http
    .csrf().disable()
    .cors().disable()
    .authorizeRequests()
        .antMatchers("/authenticate").permitAll()
        .antMatchers("/**/private/**").authenticated()
        .anyRequest().permitAll() 
        .and()
    .addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class)
    .exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint);
   }
}

Change .anyRequest().permitAll() to .anyRequest().authenticated() if you want authenticated all the request.

You can also add endPoints to configure(WebSecurity web) for which you don't want to apply Spring Security Filter Chain.

@Override
    public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
            .antMatchers("**/public/**")
    }

What is the difference between HttpSecurity and WebSecurity?