SpringBoot2.0整合SpringSecurity并实现验证码和权限控制

使用SpringBoot2.0 整合SpringSecurity加入kaptcha验证码,使用redis实现session共享,请看源码,附上数据库脚本,绝对可以跑起来,源码地址为https://github.com/xueqinggit/SpringCloudLearn

SpringBoot2.0整合SpringSecurity并实现验证码和权限控制_第1张图片

1、pom文件



    4.0.0

    com.xueqing.demo
    spring-boot-security
    0.0.1-SNAPSHOT
    jar

    spring-boot-security
    Demo project for Spring Boot

    
        org.springframework.boot
        spring-boot-starter-parent
        2.0.3.RELEASE
         
    

    
        UTF-8
        UTF-8
        1.8
        -Dfile.encoding=UTF-8
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
        

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        


        
            org.springframework.boot
            spring-boot-starter-test
            test
        


        
        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        

        
        
            org.springframework.boot
            spring-boot-starter-cache
        

        
        
            org.springframework.boot
            spring-boot-starter-data-redis
        

        
        
            org.springframework.session
            spring-session-data-redis
        

        
            mysql
            mysql-connector-java
            8.0.11
        

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

        
        
            org.springframework.boot
            spring-boot-starter-thymeleaf
        

        
            org.mybatis.spring.boot
            mybatis-spring-boot-starter
            1.3.1
        


        
        
            com.github.axet
            kaptcha
            0.0.9
        

    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



2、配置SecurityConfig

package com.xueqing.demo.springbootsecurity.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.BeanIds;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true) //开启方法权限控制
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder  auth) throws  Exception{
        auth.userDetailsService(customUserDetailsService())
                .passwordEncoder(passwordEncoder());
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                // 所有用户均可访问的资源
                .antMatchers( "/favicon.ico","/css/**","/common/**","/js/**","/images/**","/captcha.jpg","/login","/userLogin","/login-error").permitAll()
                // 任何尚未匹配的URL只需要验证用户即可访问
                .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").successForwardUrl("/index").failureForwardUrl("/login?error=1")
                .and()
                //权限拒绝的页面
                .exceptionHandling().accessDeniedPage("/403");

        http.logout().logoutSuccessUrl("/login");
    }


    /**
     * 设置用户密码的加密方式
     * @return
     */
    @Bean
    public Md5PasswordEncoder passwordEncoder() {
        return new Md5PasswordEncoder();

    }

    /**
     * 自定义UserDetailsService,授权
     * @return
     */
    @Bean
    public CustomUserDetailsService customUserDetailsService(){
        return new CustomUserDetailsService();
    }

    /**
     * AuthenticationManager
     * @return
     * @throws Exception
     */
    @Bean(name = BeanIds.AUTHENTICATION_MANAGER)
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}

3.、自定义UserDetailsService实现用户的认证和授权

package com.xueqing.demo.springbootsecurity.security;

import com.xueqing.demo.springbootsecurity.bean.Menu;
import com.xueqing.demo.springbootsecurity.bean.User;
import com.xueqing.demo.springbootsecurity.service.MenuService;
import com.xueqing.demo.springbootsecurity.service.UserService;
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.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 认证和授权
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        //--------------------认证账号
        User user = userService.loadUserByUsername(s);
        if (user == null) {
            throw new UsernameNotFoundException("账号不存在");
        }


        //-------------------开始授权
        List menus = menuService.getMenusByUserId(user.getId());
        List grantedAuthorities = new ArrayList<>();
        for (Menu menu : menus) {
            GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(menu.getUrl());
            //此处将权限信息添加到 GrantedAuthority 对象中,在后面进行全权限验证时会使用GrantedAuthority 对象。
            grantedAuthorities.add(grantedAuthority);
        }
        user.setAuthorities(grantedAuthorities);
        return user;
    }


}

4、自定义密码比较器

package com.xueqing.demo.springbootsecurity.security;

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

/**
 * 自定义密码比较器 3
 * 在此 密码我就不加密了
 */
public class Md5PasswordEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence charSequence) {
        return charSequence.toString();
    }


    @Override
    public boolean matches(CharSequence charSequence, String s) {
        return s.equals(charSequence);
    }
}

5、自定义SpringSecurityUtils工具类

package com.xueqing.demo.springbootsecurity.security;

import com.xueqing.demo.springbootsecurity.bean.User;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.StringUtils;

import java.util.Collection;

public class SecurityUtils {

    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }


    public static Collection getAllPermission(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection authorities = authentication.getAuthorities();
        return authorities;
    }

    public static boolean hasPermission(String permission){
        if(StringUtils.isEmpty(permission)){
            return false;
        }
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Collection authorities = authentication.getAuthorities();
        boolean hasPermission = false;
        for(GrantedAuthority grantedAuthority : authorities){
            String authority = grantedAuthority.getAuthority();
            if(authority.equals(permission)){
                hasPermission =true;
            }
        }
        return hasPermission;
    }


    public static User getUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (User) authentication.getPrincipal();
    }


    public static void logout(){
        SecurityContextHolder.clearContext();
    }
}

6、在登陆方法中,使用AuthenticationManager拦截登陆请求

package com.xueqing.demo.springbootsecurity.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.xueqing.demo.springbootsecurity.bean.R;
import com.xueqing.demo.springbootsecurity.bean.User;
import com.xueqing.demo.springbootsecurity.service.UserService;
import com.xueqing.demo.springbootsecurity.util.ConstantVal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@Controller
public class LoginController {

    @Autowired
    private AuthenticationManager myAuthenticationManager;

    @Autowired
    DefaultKaptcha defaultKaptcha;

    @RequestMapping(value = "/userLogin")
    public String userLogin(HttpServletRequest request) {

        User userInfo = new User();
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String kaptcha = request.getParameter("kaptcha");

        userInfo.setUsername(username);
        userInfo.setPassword(password);
        String s = request.getSession().getAttribute(ConstantVal.CHECK_CODE).toString();
        if (StringUtils.isEmpty(kaptcha) || !s.equals(kaptcha)) {
            return "redirect:login-error?error=1";
        }

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(username, password);


        try{
            //使用SpringSecurity拦截登陆请求 进行认证和授权
            Authentication authenticate = myAuthenticationManager.authenticate(usernamePasswordAuthenticationToken);

            SecurityContextHolder.getContext().setAuthentication(authenticate);
            //使用redis session共享
            HttpSession session = request.getSession();
            session.setAttribute("SPRING_SECURITY_CONTEXT", SecurityContextHolder.getContext()); // 这个非常重要,否则验证后将无法登陆
        }catch (Exception e){
            e.printStackTrace();
            return "redirect:login-error?error=2";
        }


        return "redirect:index";
    }


    @RequestMapping("/captcha.jpg")
    @ResponseBody
    public R applyCheckCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        R r = new R();

        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = defaultKaptcha.createText();
        //生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        //保存到session
        request.getSession().setAttribute(ConstantVal.CHECK_CODE, text);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        return r;
    }
}

7、我的user表中有两个用户一个admin,一个user,admin具有所有权限,而user不具有操作权限

user登陆的界面为

SpringBoot2.0整合SpringSecurity并实现验证码和权限控制_第2张图片

 

admin登陆的界面为

SpringBoot2.0整合SpringSecurity并实现验证码和权限控制_第3张图片

user用户操作用户新增、删除、修改、都改显示没权限,而admin可以

SpringBoot2.0整合SpringSecurity并实现验证码和权限控制_第4张图片

你可能感兴趣的:(SpringSecurity)