springboot整合springsecurity(详细步骤)

1.表的建立

 权限框架的表结构一般基于 RBAC权限模型,这里我们建立5张表,分别是用户表,角色表  用户角色表,权限表,角色权限表。

 结构如下:

   springboot整合springsecurity(详细步骤)_第1张图片

sql文件链接地址: download.csdn.net/download/qq_34707456/12116065

2.maven依赖

        
            org.springframework.boot
            spring-boot-starter-security
        

 

3.用户实体类需要继承UserDetails

      注意:用户实体类继承UserDetails这个类后,重写其中的isAccountNonExpired,isAccountNonLocked,        isCredentialsNonExpired,isEnabled方法返回值要为true。

4.核心配置类:SecurityConfig

通过数据库查询验证登录密码,以及对页面的权限进行管理

@Configuration
@EnableWebSecurity
@Slf4j
public class SecurityConfig  extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationFailureHandlerMethod authenticationFailureHandlerMethod;

    @Autowired
    private AuthenticationSuccessHandlerMethod authenticationSuccessHandlerMethod;

    @Autowired
    private SysUserServiceImpl sysUserService;

    @Autowired
    private SysPermissionMapper  sysPermissionMapper;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(sysUserService).passwordEncoder(new PasswordEncoder() {

            /**
             * 对表单密码进行加密
             * @param charSequence
             * @return
             */
            @Override
            public String encode(CharSequence charSequence) {
                return MD5Util.encode((String)charSequence);
            }


            /**
             * @param charSequence  表单提交的密码
             * @param s   数据库存的密码
             * @return
             */
            @Override
            public boolean matches(CharSequence charSequence, String s) {
                return encode(charSequence).equals(s);
            }
        });

    }


    /**
     *   配置HttpSecurity 拦截资源
      */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /*httpBasic方式
        http.authorizeRequests().antMatchers("/**").fullyAuthenticated().and().httpBasic();*/


        ExpressionUrlAuthorizationConfigurer.ExpressionInterceptUrlRegistry authorizeRequests = http
                .authorizeRequests();

        //查询权限列表
        List  list=sysPermissionMapper.selectAll();
        list.stream().forEach(sysPermission -> authorizeRequests.antMatchers(sysPermission.getUrl()).hasAuthority(sysPermission.getPermtag()));

        authorizeRequests.antMatchers("/login").permitAll().antMatchers("/**").fullyAuthenticated().and().formLogin()
                .loginPage("/login").successHandler(authenticationSuccessHandlerMethod).failureHandler(authenticationFailureHandlerMethod).and().csrf()
                .disable();


    }

    /**
     * 升级为Security5.0以上密码支持多中加密方式(需要加密),回复以前模式
     */
    @Bean
    public static NoOpPasswordEncoder passwordEncoder() {
        return (NoOpPasswordEncoder) NoOpPasswordEncoder.getInstance();
    }
}

 

 

5.登录验证,用户权限获取service类:SysUserServiceImpl

@Service
@Slf4j
public class SysUserServiceImpl  implements SysUserService,UserDetailsService {

    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        SysUser user=sysUserMapper.selectByUsername(s);
        List listPermission=sysUserMapper.selectPermissionByUsername(s);
        if(listPermission!=null && listPermission.size()>0){
            List authorities = new ArrayList<>();
            //添加用户权限
            listPermission.stream().forEach(map -> authorities.add(new SimpleGrantedAuthority(map.get("permTag").toString())));
            log.info(authorities.toString());
            user.setAuthorities(authorities);
        }
        return user;
    }
}

 

6.通过用户名查询用户权限sql语句

 

你可能感兴趣的:(安全)