Fegin权限控制Oauth2配置

一、 配置token传递

public class FeignConfiguration {

    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }

    @Bean
    public RequestInterceptor oAuth2RequestInterceptor(OAuth2ProtectedResourceDetails resource,
            OAuth2ClientContext oauth2Context) {
        return new OAuth2FeignRequestInterceptor2(oauth2Context, resource);
    }

}

二、无需权限访问配置

1. 被调用者配置资源访问权限

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().exceptionHandling()
                .authenticationEntryPoint(
                        (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED))
                .and().authorizeRequests()
                .antMatchers("/swagger-resources/**", 
                        "/v2/api-docs/**", 
                        "/certification/auditCallbackFromxy",
                        "/customize/menu/auditCallbackFromxy",
                        "/swagger-ui.html")
                .permitAll().anyRequest().authenticated().and().httpBasic();
    }
}

2. 调用者自定义Fegin拦截器

注意:同名的FeginClient使用不同的配置将被覆盖,所以同名Fegin只会有一份配置。

public class OAuth2FeignRequestInterceptor2 extends OAuth2FeignRequestInterceptor {

    public OAuth2FeignRequestInterceptor2(OAuth2ClientContext oAuth2ClientContext,
            OAuth2ProtectedResourceDetails resource) {
        super(oAuth2ClientContext, resource);
        // TODO Auto-generated constructor stub
    }
    
    @Autowired
    private OAuth2ClientContext context;

    @Override
    public void apply(RequestTemplate template) {

        if (context.getAccessToken() != null && context.getAccessToken().getValue() != null
                && OAuth2AccessToken.BEARER_TYPE.equalsIgnoreCase(context.getAccessToken().getTokenType())) {
            template.header("Authorization",
                    String.format("%s %s", OAuth2AccessToken.BEARER_TYPE, context.getAccessToken().getValue()));
        }

    }

}

你可能感兴趣的:(Fegin权限控制Oauth2配置)