SpringBoot整合Spring Security和Mybatis验证

近来项目后台做安全验证,仔细考虑之后选型Security。

一、引入依赖

   
            org.springframework.security
            spring-security-web
            4.2.3.RELEASE
        
        
            org.springframework.security
            spring-security-config
            4.2.3.RELEASE
        

二、Java Config

继承WebSecurityConfigurerAdapter,并重写相关方法。


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created by baiguantao on 2017/9/15.
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
  //配置URL权限过滤规则,登录页等等
   @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/admin//**").hasRole("ADMIN")
                .antMatchers("/index//**").hasAnyRole("ADMIN")
                .antMatchers("/index").hasAnyRole("ADMIN")
                .antMatchers("/static_rbg*//**").permitAll()
                .antMatchers("/ricky*//**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .loginProcessingUrl("/ricky-login")
                .defaultSuccessUrl("/index")
                .successForwardUrl("/index")
                .usernameParameter("username").passwordParameter("password")
                .permitAll()
                .and().csrf().disable();
    }
    @Autowired
    private CustomUserService myAppUserDetailsService;//mybatis验证类
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        //注入mybatis查询类和密码校验类
        auth.userDetailsService(myAppUserDetailsService)
        .passwordEncoder(passwordEncoder());
    }
    /**
    密码验证规则
    */
    @Bean(name = "passwordEncoder")
    public  PasswordEncoder passwordEncoder(){
        return new MyPasswordEncoder();
    }
}

mybatis验证相关–》


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.Set;

/**
 * Created by baiguantao on 2017/9/15.
 */
@Service
public class CustomUserService implements UserDetailsService {
    @Autowired
    SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser t=new SysUser();
        t.setLoginName(s);
        SysUser user = sysUserMapper.findByModelOne(t);
        if (user == null) {
            throw new UsernameNotFoundException("用户名不存在");
        }
        Set grantedAuthorities = new HashSet<>();
        grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_ADMIN"));//默认是ROLE_开头,对应前边的ADMIN
        System.out.println(user.getPassword());
        return new org.springframework.security.core.userdetails.User(user.getLoginName(), user.getPassword(), grantedAuthorities);

    }
}

密码校验类


import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Created by baiguantao on 2017/9/18.
 */
public class MyPasswordEncoder implements PasswordEncoder {

    @Override
    public String encode(CharSequence charSequence) {
      //进行编码 是来自页面输入的密码明文
        return charSequence.toString();
    }

    @Override
    public boolean matches(CharSequence charSequence, String s) {
        //明文和密文密码对比
        if (validatePassword(charSequence.toString(),s)) {
            return true;
        } else {

        return false;
        }
    }


}

结语

至此,利用数据库来进行安全认证已经完成,特别注意的是角色中ROLE_ADMIN和ADMIN的对应性,以及crsf的关闭。

你可能感兴趣的:(SpringBoot)