我已经设置了一个spring web应用程序,它使用keycloak作为授权服务器。该应用程序配置为使用oauth2Login,要求用户使用keycloak登录。web应用程序也被配置为oauth2Resourceserver,这样它的URL就可以通过在keycloak中定义的角色来保护,这些角色可以从JWT自定义转换为JwtAuthenticationToken。配置如下所示:
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests(authorizeRequests -> authorizeRequests.antMatchers("/test*").hasAnyRole("Dev", "QA") .anyRequest().authenticated()) .oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> jwt.jwtAuthenticationConverter(this.keycloakJwtAuthenticationConverter()))) .oauth2Login(oauth2 -> oauth2.userInfoEndpoint(userInfo -> userInfo.userAuthoritiesMapper(this.userAuthoritiesMapper()))) .oauth2Client(); ...
该应用程序还充当一个oauth2Client,使用open Feign调用设置为资源服务器的其他应用程序。我使用了一个feign请求拦截器,它尝试将一个JWT令牌放入HTTP Bearer标头中,如下所示:
@Autowired private OAuth2AuthorizedClientManager authorizedClientManager; @Bean public RequestInterceptor requestInterceptor() { return requestTemplate -> { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); OAuth2AuthorizeRequest authorizeRequest = OAuth2AuthorizeRequest.withClientRegistrationId("keycloak") .principal(authentication) .build();