从spring-security-jwt迁移到OAuth 2.0 JOSE

时间:2018-10-29 13:45:33

标签: java spring spring-boot spring-security spring-security-oauth2

我的pom 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>

我还有另一个共同点(由于微服务):

<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>

我希望能够从所有pom中删除此spring-security-jwt依赖项并移至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;
    }
}

0 个答案:

没有答案