У меня есть пом common-security
, который имеет:
<artifactId>common-security</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.security.oauth</groupId>
<artifactId>spring-security-oauth2</artifactId>
<version>${spring-security-oauth2.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>${spring-security-jwt.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
У меня есть другие poms (причина микроуслуг), которые имеют это общее:
<dependencies>
<dependency>
<groupId>somePackages</groupId>
<artifactId>common-security</artifactId>
<version>${project.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
<version>${spring-security-jwt.version}</version>
</dependency>
Я хочу иметь возможность полностью удалить эту зависимость spring-security-jwt
со всех poms и перейти к spring-security-oauth2-jose
.
Когда я изменил все spring-security-jwt
вхождения зависимости на:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-jose</artifactId>
<version>5.0.6.RELEASE</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-oauth2-client</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
Похоже, этого недостаточно - я получаю сообщение об ошибке пропуска JWT
:
nested exception is java.lang.NoClassDefFoundError: org/springframework/security/jwt/crypto/sign/Signer
Вот кто-то упомянул, что JWT отсутствует, и это причина:
https://github.com/spring-projects/spring-security-oauth/issues/1372
Я подумал, что также должен удалить зависимость spring-security-oauth2
.
Когда я это делаю, чего-то не хватает.
Рассмотрим следующие классы. Можете ли вы дать мне подсказки, как успешно перейти на новую систему безопасности?
1) OAuth2ResourceServerConfig
:
package somePackages.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServices());
}
@Bean
public TokenStore tokenStore() {
JwtAccessTokenConverter converter = JwtAccessTokenConverterProvider.addKeyPair(new JwtAccessTokenConverter());
DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
defaultAccessTokenConverter.setUserTokenConverter(new UserTokenConverter());
converter.setAccessTokenConverter(defaultAccessTokenConverter);
return new JwtTokenStore(converter);
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
}
2) WebConfig
:
@Configuration
@EnableSwagger2
@CrossOrigin
@SessionAttributes("authorizationRequest")
@PropertySource(value = {"classpath:common.properties"}, ignoreResourceNotFound = true)
@EnableJpaRepositories(basePackages = {"somePackages.cas", "somePackages.common"})
@EntityScan(basePackages = {"somePackages.cas", "somePackages.model"})
public class WebConfig extends WebMvcConfigurerAdapter {
@Value("${date.pattern}")
private String datePattern;
@Autowired
private JwtAccessTokenConverter jwtAccessTokenConverter;
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JSR310Module());
objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+1:00"));
objectMapper.setDateFormat(new SimpleDateFormat(datePattern)); // ISO8601DateFormat()
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
@Bean
public MessageConverter jsonMessageConverter(ObjectMapper objectMapper) {
Jackson2JsonMessageConverter mapper = new Jackson2JsonMessageConverter(objectMapper);
return mapper;
}
@Bean
public MessageListenerContainerFactory messageListenerContainerFactory(MessageConverter jsonMessageConverter) {
return new MessageListenerContainerFactory(jsonMessageConverter);
}
@Autowired
private MessageLogRepository messageLogRepository;
@Bean
public MessageLogService messageLogService() {
return new MessageLogService(messageLogRepository);
}
@Bean
public MessageSecurityHandlerService messageSecurityHandlerService() {
return new MessageSecurityHandlerService();
}
@Bean
TopicExchange exchange(@Value("${rabbitmq.exchange.name}") String exchangeName) {
return new TopicExchange(exchangeName);
}
@Bean
RabbitTemplate template(ConnectionFactory connectionFactory, TopicExchange topicExchange, MessageConverter jsonMessageConverter) {
RabbitTemplate template = new RabbitTemplate(connectionFactory);
template.setExchange(topicExchange.getName());
template.setMessageConverter(jsonMessageConverter);
return template;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public TokenStore tokenStore() {
return new JwtTokenStore(jwtAccessTokenConverter);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
}
@Configuration
protected static class LoginConfig extends WebSecurityConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private UserDetailsServiceImpl userDetailsService;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/api")
.authenticated()
.and()
.csrf().disable();
http.userDetailsService(userDetailsService);
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager);
auth.userDetailsService(userDetailsService);
}
}
@Configuration
@EnableAuthorizationServer
protected static class OAuth2Config extends AuthorizationServerConfigurerAdapter {
@Autowired
private AuthenticationManager authenticationManager;
@Autowired
private ClientDetailsServiceImpl clientDetailsServiceImpl;
@Autowired
private JwtTokenStoreHolder jwtTokenStoreHolder;
@Bean
public JwtAccessTokenConverter jwtAccessTokenConverter() {
return JwtAccessTokenConverterProvider.addKeyPair(jwtTokenStoreHolder.getEnhancer());
}
@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.withClientDetails(clientDetailsServiceImpl).build();
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)
throws Exception {
endpoints.authenticationManager(authenticationManager).accessTokenConverter(
jwtAccessTokenConverter()).tokenStore(jwtTokenStoreHolder.getTokenStore());
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
"isAuthenticated()");
}
}
}
3) OAuth2ResourceServerConfig
:
пакет somePackages.security;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.JwtTokenStore;
@Configuration
@EnableResourceServer
public class OAuth2ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Override
public void configure(ResourceServerSecurityConfigurer config) {
config.tokenServices(tokenServices());
}
@Bean
public TokenStore tokenStore() {
JwtAccessTokenConverter converter = JwtAccessTokenConverterProvider.addKeyPair(new JwtAccessTokenConverter());
DefaultAccessTokenConverter defaultAccessTokenConverter = new DefaultAccessTokenConverter();
defaultAccessTokenConverter.setUserTokenConverter(new UserTokenConverter());
converter.setAccessTokenConverter(defaultAccessTokenConverter);
return new JwtTokenStore(converter);
}
@Bean
@Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore());
return defaultTokenServices;
}
}