SpringSecurityOAuth2(9) feign calls token authentication between microservices

GitHub address

Code cloud address

Feign can call the api interface of other microservices. When other services do not have permission verification, they can be called directly, but if the calling service has permission interception, it cannot be called normally. This article is about a way for Feign to call the authentication api.

First, create a new fp-resouce-feign module for call testing. This module does not add OAuth2 interception.

pom.xml adds regular dependencies and Feign dependencies

 	<!--Feign依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

Add the @EnableFeignClients annotation to the startup file to enable Feign; create a new simple Feign call, here we call the manager service, which adds the permission interception of Spring Security OAuth2

@FeignClient(value = "manager")
public interface ResourceManagerFeignClient {
    @GetMapping(value = "/auth/hello")
    String hello();
}

A direct call to a service interface that has permission to process will result in an HTTP 401 unauthorized error during the call, which in turn will result in an HTTP 500 internal server error request for the final service. An example is shown in the figure:

The most convenient solution is to add authentication token information to the request header. Feign has an interface RequestInterceptor, which can call the service interface by simply adding token processing:

@Configuration
public class FeignConfig implements RequestInterceptor {

    public static String TOKEN_HEADER = "authorization";

    @Override
    public void apply(RequestTemplate template) {
        template.header(TOKEN_HEADER, getHeaders(getHttpServletRequest()).get(TOKEN_HEADER));
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}

Result example:

So far, the simple implementation of Feign calling the authorized service interface is completed.

{{o.name}}
{{m.name}}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=324133130&siteId=291194637