在微服务中使用JWT进行身份验证和授权

时间:2020-06-07 12:26:44

标签: java spring-security jwt microservices

我有auth-service,它有两个jwt-filters用于身份验证和授权,原理和其他配置,我还有另一个服务-lib-commons,用于所有服务,包括SecurityConfiguration,因此每个服务都使用它,这种配置:

@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

@Autowired
@Qualifier("customAuthenticationProvider")
private AuthenticationProvider authenticationProvider;

@Autowired
private CustomAuthEntryPoint customAuthEntryPoint;

//
// Beans
//

@Bean
public CorsFilter corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("OPTIONS");
config.addAllowedMethod("GET");
config.addAllowedMethod("POST");
config.addAllowedMethod("PUT");
config.addAllowedMethod("DELETE");
source.registerCorsConfiguration("/**", config);
return new CorsFilter(source);
}

//
// Overrides
//

@Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
        .cors()
        .and()
        .exceptionHandling()
        .authenticationEntryPoint(customAuthEntryPoint)
        .and()
        .csrf().disable()
        .httpBasic().and()
        .authorizeRequests()
        .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
        .antMatchers(HttpMethod.POST, "/auth/register").permitAll()
        .antMatchers(HttpMethod.POST, "/auth/login").permitAll()
        .antMatchers(HttpMethod.GET, "/v2/api-docs",
                "/configuration/ui",
                "/swagger-resources/**",
                "/configuration/security",
                "/swagger-ui.html",
                "/webjars/**",
                "/csrf").permitAll()
        .anyRequest().authenticated()
        .and()
        .addFilter(new JWTAuthenticationFilter(authenticationManager()))
        .addFilter(new JWTAuthorizationFilter(authenticationManager()))
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}

在此配置中,我为JWT添加了两个过滤器,但它们都位于auth-service中,并且这在gradle中产生了循环依赖问题,因为我在auth-service中导入了lib-commons,反之亦然。我认为,在lib-commons中移动jwt-filters的想法是错误的。那么,我该如何解决这个问题呢?如何为微服务进行JWT身份验证和授权?

0 个答案:

没有答案