user20112858
user20112858

Reputation: 89

how microservice use jwt to communicate in springboot

I am using microservice in spring boot and i want to use jwt and oauth2 to access the server.But i just wonder that how microservice other than api gateway get the data in the jwt (id or name) .It seems that it is so tedious to set a decoder in every microservice.

I am thinking that is it possible to decode and add the data at the httprequest and route it the other microservice in apigateway.But it seems that i cant find a setheader method in webflux filter security.

Jwt filter:

 @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        String authorizationheader= exchange.getRequest().getHeaders().get("Authorization").toString();
        String token;
        String Username = null;
        String iss=null;
        //check have tokem
        if(authorizationheader !=null&& authorizationheader.startsWith("Bearer ")){
            token=authorizationheader.substring(7);
            Username=jwtDecoder.decode(token).getSubject();
            iss= String.valueOf(jwtDecoder.decode(token).getIssuer());


        } //verify by check username and iss
        if(Username!=null && iss!=null&& SecurityContextHolder.getContext().getAuthentication()==null){
            if(iss.equals("http://localhost:8080")){
                UserDetails userDetails=new User(Username,null,null);
                UsernamePasswordAuthenticationToken AuthenticationToken=new UsernamePasswordAuthenticationToken(
                        userDetails,null,userDetails.getAuthorities());
                //set username and id to the request

                SecurityContextHolder.getContext().setAuthentication(AuthenticationToken);
            }
        }
        return chain.filter(exchange);

    }

Securityfilter bean:

@Bean
    public SecurityWebFilterChain filterChain(ServerHttpSecurity httpSecurity) throws Exception {
        return httpSecurity
                /*.csrf(csrf -> csrf.ignoringRequestMatchers("/Job/getRegionjobs/**",
                        "/Job/getalljobs","/login/oauth2/code/google"))*/
                .csrf(csrf -> csrf.disable())

                .authorizeExchange(auth->auth.anyExchange().authenticated())
                .addFilterBefore(jwtFilter, SecurityWebFiltersOrder.AUTHENTICATION)
                .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::jwt)
                //.sessionManagement(session-> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .httpBasic(withDefaults())
                .build();



    }

Please help

Upvotes: 0

Views: 96

Answers (1)

ch4mp
ch4mp

Reputation: 12825

It seems that it is so tedious to set a decoder in every microservice.

No, it is not. Configuring a resource-server (OAuth2 REST API) can be as simple as:

<dependency>
    <groupId>com.c4-soft.springaddons</groupId>
    <!-- replace "webmvc" with "weblux" if your micro-service is reactive -->
    <artifactId>spring-addons-webmvc-jwt-resource-server</artifactId>
    <version>6.0.12</version>
</dependency>
@Configuration
@EnableMethodSecurity
public static class WebSecurityConfig { }
com.c4-soft.springaddons.security.issuers[0].location=https://localhost:8443/realms/realm1
com.c4-soft.springaddons.security.issuers[0].authorities.claims=realm_access.roles,ressource_access.some-client.roles,ressource_access.other-client.roles


com.c4-soft.springaddons.security.cors[0].path=/some-api

If you don't want to use my starters, you can still create your own copying from it (it is open source and each is composed of 3 files only).

If you don't implement access-control in each micro-service, then you can't bypass the gateway and it's going to be a hell to implement rules involving the resources itself (like only user who created that kind of resource can modify it).

Upvotes: 0

Related Questions