Spring Boot + Spring Security + Spring Session + Spring Session Hazelcast 整合

Spring Boot + Spring Security + Spring Session + Spring Session Hazelcast 整合随笔

Spring Boot 采用2.0.2.RELEASE版本,Hazelcast 采用同步的3.9.3版本

1.Spring Boot + Spring Security

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/common/**","/login").permitAll().anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").failureUrl("/login-error").defaultSuccessUrl("/index").usernameParameter("username")
                .passwordParameter("password").permitAll()
                .and()
                .logout().permitAll()
                .and()
                .sessionManagement().maximumSessions(1).expiredUrl("/login");
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(getUserDetailsServiceImpl()).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return Tools.getMD5((String)charSequence);
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(Tools.getMD5((String)charSequence));
            }
        });//.passwordEncoder(new Md5PasswordEncoder());
    }
    @Bean
    public CustomUserDetailsServiceImpl getUserDetailsServiceImpl() {
        return new CustomUserDetailsServiceImpl();
    }
}

1.1 CustomUserDetailsServiceImpl实现类,省略Mybatis配置

public class CustomUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger LOGGER = LoggerFactory.getLogger(CustomUserDetailsServiceImpl.class);
    @Autowired
    private LoginMapper lMapper;
    @Autowired
    private HttpSession session;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        LOGGER.error(session.getId());
        UserSession userSession = lMapper.getUserSessionInfoByUser(s);
        ProUser user = new ProUser(userSession.getGuid(), userSession.getUser(), userSession.getPassword(), "1".equals(userSession.getEnable()) ? true : false);
        session.setAttribute("user", user);
        return user;
    }
}

2.Hazelcast配置

@Configuration
@EnableHazelcastHttpSession(maxInactiveIntervalInSeconds = 60)
public class HazelcastHttpSessionConfig {
    @Bean
    public HazelcastInstance hazelcastInstance() {
        MapAttributeConfig attributeConfig = new MapAttributeConfig()
                .setName(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
                .setExtractor(PrincipalNameExtractor.class.getName());
        Config config = new Config();
        config.getMapConfig(HazelcastSessionRepository.DEFAULT_SESSION_MAP_NAME)
                .addMapAttributeConfig(attributeConfig)
                .addMapIndexConfig(new MapIndexConfig(
                        HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false));
        return Hazelcast.newHazelcastInstance(config);
    }
}

3.增加Hazelcast+Security配置

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private HazelcastSessionRepository sessionRepository;
    @Bean
    SpringSessionBackedSessionRegistry sessionRegistry() {
        return new SpringSessionBackedSessionRegistry<>(sessionRepository);
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests().antMatchers("/common/**","/login").permitAll().anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").failureUrl("/login-error").defaultSuccessUrl("/index").usernameParameter("username")
                .passwordParameter("password").permitAll()
                .and()
                .logout().permitAll()
                .and()
                .sessionManagement().maximumSessions(1).expiredUrl("/login").sessionRegistry(sessionRegistry());
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(getUserDetailsServiceImpl()).passwordEncoder(new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return Tools.getMD5((String)charSequence);
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return s.equals(Tools.getMD5((String)charSequence));
            }
        });//.passwordEncoder(new Md5PasswordEncoder());
    }
    @Bean
    public CustomUserDetailsServiceImpl getUserDetailsServiceImpl() {
        return new CustomUserDetailsServiceImpl();
    }
}

注意,Spring Session官网,

HazelcastSessionRepository是FindByIndexNameSessionRepository的实现类
@Autowired
    private HazelcastSessionRepository sessionRepository;
    @Bean
    SpringSessionBackedSessionRegistry sessionRegistry() {
        return new SpringSessionBackedSessionRegistry<>(sessionRepository);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值