目录
Java学习之Mybatis-plus与Security的简单整合

Mybatis-plus与Security的简单整合(基于Session)


1.文件目录

文件目录


(1)导入依赖

  • pom.xml
xml
复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.oldbai</groupId>
    <artifactId>my-mp-security</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>my-mp-security</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>

        <!--        security-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!--添加MyBatis Plus依赖-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.3.2</version>
        </dependency>
        <!--        逆向工程-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.3.1.tmp</version>
        </dependency>
        <!--        逆向工程的模板  默认的velocity-->
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-engine-core</artifactId>
            <version>2.0</version>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

(2)Mybatis-Plus的简单配制

  • MyBatisPlusConfig
java
复制代码
package com.oldbai.config;

import com.baomidou.mybatisplus.extension.plugins.OptimisticLockerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

//Version配置类
@Configuration
@EnableTransactionManagement
@MapperScan("com.oldbai.mapper")
public class MyBatisPlusConfig {
//    Version配置类 乐观锁
    @Bean
    public OptimisticLockerInterceptor optimisticLockerInterceptor(){
        return new OptimisticLockerInterceptor();
    }
//    分页查询配制
    @Bean
    public PaginationInterceptor paginationInterceptor(){
        return new PaginationInterceptor();
    }
}
  • 其他生成类使用逆向工程生成即可
  • 下面放出主要代码
  • User(注意,实现了UserDetails接口)
java
复制代码
package com.oldbai.entity;

import java.time.LocalDateTime;
import com.baomidou.mybatisplus.annotation.TableField;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class User implements Serializable , UserDetails {

    private static final long serialVersionUID=1L;

      private Integer id;

    private String username;

    private String password;

    private String nickname;

    private Integer enabled;

    private String email;

    private String userface;

    @TableField("regTime")
    private LocalDateTime regTime;

    private String role;


    @Override
    //返回用户的角色信息
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<SimpleGrantedAuthority> authorities =new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(role));
        return authorities;
    }

    /**
     *
     * 如果用户未锁定,则返回<code>true</code>,否则返回false
     *
     */
    @Override
    //账号没有过期
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    //没有被锁定
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    //密码没有过期
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    //是否可用
    public boolean isEnabled() {
        return true;
    }
}
  • UserService(也就是UserServiceImpl)
  • 注意实现了UserDetailsService接口
java
复制代码
package com.oldbai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.oldbai.entity.User;
import com.oldbai.mapper.UserMapper;
import com.oldbai.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author oldbai
 * @since 2020-08-07
 */
@Service
public class UserService extends ServiceImpl<UserMapper, User> implements IUserService ,UserDetailsService {

    @Autowired
    UserMapper userMapper;

    /**
     * <p>
     *     我们自己定义的 UserService 需要实现 UserDetailsService 接口,
     *     实现该接口,就要实现接口中的方法,也就是 loadUserByUsername ,
     *     这个方法的参数就是用户在登录的时候传入的用户名,
     *     根据用户名去查询用户信息(查出来之后,系统会自动进行密码比对)
     * </p>
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //根据前端传过来的username找到对应的user
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("username",username));
        if (user==null){
            throw new UsernameNotFoundException("用户不存在");
        }
        /**
         * 设置密码编码格式
         */
        String password = user.getPassword();
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        user.setPassword(bCryptPasswordEncoder.encode(password));
        return user;
    }
}

(3)Security的简单配制

  • SecurityConfig
  • @EnableTransactionManagement(proxyTargetClass = true)这个注解强行开启某个代理
java
复制代码
package com.oldbai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oldbai.entity.User;
import com.oldbai.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.PrintWriter;

/**
 * 跟着松哥的笔记
 */
@EnableWebSecurity
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * mybatis-plus 联手 Security 数据库认证
         */
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());

    }

    /**
     * 角色继承
     */
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_admin > ROLE_user");
        return hierarchy;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/swagger-ui.html").permitAll()
                .anyRequest().authenticated();//任何请求登录后即可访问;
        http
                .formLogin()
                .loginProcessingUrl("/doLogin")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler((httpServletRequest, httpServletResponse, authentication) -> { //Authentication 参数保存了我们刚刚登录成功的用户信息。登陆成功
                    Object principal = authentication.getPrincipal();
                    User user = (User) principal;
                    user.setPassword(null);
                    //以上三行是手动删除密码
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(user));
                    out.flush();
                    out.close();
                })
                .failureHandler((httpServletRequest, httpServletResponse, exception) -> {//exception 异常错误。登陆失败
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(exception.getMessage()));
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .exceptionHandling()//无状态(未认证)访问
                .authenticationEntryPoint((httpServletRequest, httpServletResponse, exception) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("尚未登陆,请登陆!"));//返回JSON数据
                    out.flush();
                    out.close();
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("注销登陆成功"));//注销成功
                    out.flush();
                    out.close();
                });
    }


}
  • 自定义验证类UserDetailsService 实现Security框架UserDetailsService的接口,参考实现代码
java
复制代码
// 自定义验证类UserDetailsService 实现Security框架UserDetailsService的接口
public class UserDetailServiceImpl implements UserDetailsService {
//修改UserDetailsServiceImpl.java ,添加属性和setter方法 ,修改loadUserByUsername方法
private SellerService sellerService;
public void setSellerService(SellerService sellerService){
this.sellerService=sellerService;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

/**
*构建角色列表
*/
// 权限集合
List<GrantedAuthority> authList = new ArrayList<>();
// 具体具有什么的权限
authList.add(new SimpleGrantedAuthority("ROLE_SELLER"));
//1 判断用户名是否为null 如果为null 直接返回null
if(username==null){
return null;
}

//得到商家对象

//2 根据用户名到数据库查询 用户对象
Seller seller = sellerService.findOne(username);
//3 如果用户查不到 返回null
if(seller!=null){
//4 如果用户对象查到了 判断用户审核 是否通过 如果未通过返回null
if("1".equals(seller.getStatus())){
//5 返回user 对象 将用户名 密码 返回权限集合
return new User(username,seller.getPassword(),authList);
}

}
return null;
//6 框架帮助比对用户名和密码是否匹配
}
}

(4)SQL测试语句

sql
复制代码
/*
Navicat MySQL Data Transfer

Source Server         : MyOld
Source Server Version : 50728
Source Host           : 
Source Database       : security0

Target Server Type    : MYSQL
Target Server Version : 50728
File Encoding         : 65001

Date: 2020-08-07 20:32:37
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `username` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `password` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `nickname` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `enabled` tinyint(4) DEFAULT NULL,
  `email` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `userface` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  `regTime` datetime DEFAULT NULL,
  `role` varchar(255) CHARACTER SET utf8 DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'zhangsan', '123456', '张三', '1', 'zhangsan@qq.com', null, '2020-08-07 19:13:38', 'ROLE_admin');
INSERT INTO `user` VALUES ('2', 'lisi', '123456', '李四', '1', 'lisi@qq.com', '', '2020-08-07 19:13:38', 'ROLE_user');
INSERT INTO `user` VALUES ('3', 'wangwu', '123456', '王五', '1', 'wangwu@qq.com', '', '2020-08-07 19:13:38', 'ROLE_peo');

(5)实验截图

登陆李四
在这里插入图片描述
在这里插入图片描述

  • 只截一部分实验截图

2.自定义验证码

(1)自定义验证码生成工具和接口

  • 生成工具
  • VerifyCode
java
复制代码
package com.oldbai.Util;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * 生成验证码的工具类
 */
public class VerifyCode {
    private int width = 100;// 生成验证码图片的宽度
    private int height = 50;// 生成验证码图片的高度
    private String[] fontNames = { "宋体", "楷体", "隶书", "微软雅黑" };
    private Color bgColor = new Color(255, 255, 255);// 定义验证码图片的背景颜色为白色
    private Random random = new Random();
    private String codes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private String text;// 记录随机字符串

    /**
     * 获取一个随意颜色
     *
     * @return
     */
    private Color randomColor() {
        int red = random.nextInt(150);
        int green = random.nextInt(150);
        int blue = random.nextInt(150);
        return new Color(red, green, blue);
    }

    /**
     * 获取一个随机字体
     *
     * @return
     */
    private Font randomFont() {
        String name = fontNames[random.nextInt(fontNames.length)];
        int style = random.nextInt(4);
        int size = random.nextInt(5) + 24;
        return new Font(name, style, size);
    }

    /**
     * 获取一个随机字符
     *
     * @return
     */
    private char randomChar() {
        return codes.charAt(random.nextInt(codes.length()));
    }

    /**
     * 创建一个空白的BufferedImage对象
     *
     * @return
     */
    private BufferedImage createImage() {
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        g2.setColor(bgColor);// 设置验证码图片的背景颜色
        g2.fillRect(0, 0, width, height);
        return image;
    }

    public BufferedImage getImage() {
        BufferedImage image = createImage();
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < 4; i++) {
            String s = randomChar() + "";
            sb.append(s);
            g2.setColor(randomColor());
            g2.setFont(randomFont());
            float x = i * width * 1.0f / 4;
            g2.drawString(s, x, height - 15);
        }
        this.text = sb.toString();
        drawLine(image);
        return image;
    }

    /**
     * 绘制干扰线
     *
     * @param image
     */
    private void drawLine(BufferedImage image) {
        Graphics2D g2 = (Graphics2D) image.getGraphics();
        int num = 5;
        for (int i = 0; i < num; i++) {
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g2.setColor(randomColor());
            g2.setStroke(new BasicStroke(1.5f));
            g2.drawLine(x1, y1, x2, y2);
        }
    }

    public String getText() {
        return text;
    }

    public static void output(BufferedImage image, OutputStream out) throws IOException {
        ImageIO.write(image, "JPEG", out);
    }
}
  • 实装接口
  • LoginController
java
复制代码
package com.oldbai.controller;

import com.oldbai.Util.VerifyCode;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class LoginController {

    //提供生成图片的接口
    @GetMapping("/verifyCode")
    public void verifyCode(HttpSession session, HttpServletResponse response) throws IOException {
        VerifyCode code = new VerifyCode();
        BufferedImage image = code.getImage();
//        检查是否生成图片
        ImageIO.write(image,"JPEG",new FileOutputStream("F:/a.jpg"));
        String text = code.getText();
        session.setAttribute("verify_code",text);
        VerifyCode.output(image,response.getOutputStream());
    }
}

(2)自定义验证码过滤器

  • 自定义过滤器 LoginFilter
java
复制代码
package com.oldbai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 自定义拦截器
 * 拦截验证码验证
 * 它是要在用户验证之前验证
 */
@Component
public class VerificationCodeFilter extends GenericFilter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        /**
         * 校验验证码
         */
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        /**
         * 如果是登陆请求 则走这个过滤器
         * 否则不走
         */
        if("POST".equals(request.getMethod())&&"/doLogin".equals(request.getServletPath())){
            String code = request.getParameter("code");//传过来的验证码
            String verify_code = (String) request.getSession().getAttribute("verify_code");//Session里面存的验证码
            if (code == null || "".equals(code) || !verify_code.toLowerCase().equals(code.toLowerCase())){
                //验证码不正确
                //向前端返回json数据
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString("验证码填写错误"));//这里需要定义一个封装统一返回结果
                out.flush();
                out.close();
            }else {
                filterChain.doFilter(request,response);
            }
        }else {
            filterChain.doFilter(request,response);
        }
    }
}
  • 实装进入 securityConfing
java
复制代码
package com.oldbai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oldbai.entity.User;
import com.oldbai.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
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.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import java.io.PrintWriter;

/**
 * 跟着松哥的笔记
 */
@EnableWebSecurity
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;

    /**
     * 添加验证码过滤器
     */
    @Autowired
    VerificationCodeFilter verificationCodeFilter;

    

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * mybatis-plus 联手 Security 数据库认证
         */
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());

    }

    /**
     * 角色继承
     */
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_admin > ROLE_user > ROLE_peo");
        hierarchy.setHierarchy("ROLE_user > ROLE_peo");
        return hierarchy;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 实装添加过滤器
         * 添加在用户验证之前
         */
        http.addFilterBefore(verificationCodeFilter, UsernamePasswordAuthenticationFilter.class);



        http.csrf().disable();
        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/verifyCode").permitAll()
                .anyRequest().authenticated();//任何请求登录后即可访问;
        http.formLogin()
                .loginProcessingUrl("/doLogin")
                .usernameParameter("username")
                .passwordParameter("password")
                .successHandler((httpServletRequest, httpServletResponse, authentication) -> { //Authentication 参数保存了我们刚刚登录成功的用户信息。登陆成功
                    Object principal = authentication.getPrincipal();
                    User user = (User) principal;
                    user.setPassword(null);
                    //以上三行是手动删除密码
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(user));
                    out.flush();
                    out.close();
                })
                .failureHandler((httpServletRequest, httpServletResponse, exception) -> {//exception 异常错误。登陆失败
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString(exception.getMessage()));
                    out.flush();
                    out.close();
                })
                .permitAll()
                .and()
                .exceptionHandling()//无状态(未认证)访问
                .authenticationEntryPoint((httpServletRequest, httpServletResponse, exception) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("尚未登陆,请登陆!"));//返回JSON数据
                    out.flush();
                    out.close();
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("注销登陆成功"));//注销成功
                    out.flush();
                    out.close();
                });
    }


}

3.前后端登陆JSON交互

(1)先创建一个过滤器

  • LoginFilter
java
复制代码
package com.oldbai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 在登陆时进行过滤 把它变成 json格式
 * 顺便进行验证码的核对
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        /**
         * 是否为POST请求
         */
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException(
                    "Authentication method not supported: " + request.getMethod());
        }
        /**
         * 既支持Key - value
         * 又支持 json
         */
        String verify_code = (String) request.getSession().getAttribute("verify_code");//Session里面存的验证码
        if (request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().equals(MediaType.APPLICATION_JSON_UTF8_VALUE)) {
            /**
             * 符合任意一个就认为是 json 格式
             * 否则就是 key - value 格式
             */

            /**
             * 可以用一个实体类接收,也可以用一个Map来接收
             */
            Map<String, String> loginData = null;
            try {
                loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                String code = loginData.get("code");
                //定义一个验证码验证的方法
                checlCode(code, verify_code);
            }
            String username = loginData.get(getUsernameParameter());
            String password = loginData.get(getPasswordParameter());

            if (username == null) {
                username = "";
            }

            if (password == null) {
                password = "";
            }

            username = username.trim();

            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
                    username, password);

            // Allow subclasses to set the "details" property
            setDetails(request, authRequest);

            return this.getAuthenticationManager().authenticate(authRequest);
        } else {
            //非json格式登陆也要进行验证验证码
            checlCode(request.getParameter("code"), verify_code);
            return super.attemptAuthentication(request, response);
        }
    }

    private void checlCode(String code, String verify_code) {
        if (code == null || "".equals(code) || !verify_code.toLowerCase().equals(code.toLowerCase())){
            //验证码不正确
            //抛出一个异常即可
            throw new AuthenticationServiceException("验证码输入错误");
        }
    }
}

(2)添加配制(改动较大)

  • SecurityConfig
java
复制代码
package com.oldbai.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.oldbai.entity.User;
import com.oldbai.service.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.hierarchicalroles.RoleHierarchy;
import org.springframework.security.access.hierarchicalroles.RoleHierarchyImpl;
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.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 跟着松哥的笔记
 */
@EnableWebSecurity
@Configuration
@EnableTransactionManagement(proxyTargetClass = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;
    /**
     * 登陆过滤器 JSON交互
     */
    @Bean
    LoginFilter loginFilter() throws Exception{
        LoginFilter loginFilter = new LoginFilter();
//        登陆成功回调
        loginFilter.setAuthenticationSuccessHandler(new AuthenticationSuccessHandler() {
            @Override
            public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException, IOException {
                Object principal = authentication.getPrincipal();
                User user = (User) principal;
                user.setPassword(null);
                //以上三行是手动删除密码
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(user));
                out.flush();
                out.close();
            }
        });
//        登陆失败回调
        loginFilter.setAuthenticationFailureHandler(new AuthenticationFailureHandler() {
            @Override
            public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
                response.setContentType("application/json;charset=utf-8");
                PrintWriter out = response.getWriter();
                out.write(new ObjectMapper().writeValueAsString(exception.getMessage()));
                out.flush();
                out.close();
            }
        });
        loginFilter.setAuthenticationManager(authenticationManagerBean());
        loginFilter.setFilterProcessesUrl("/doLogin");
        return loginFilter;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        /**
         * mybatis-plus 联手 Security 数据库认证
         */
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());

    }

    /**
     * 角色继承
     */
    @Bean
    RoleHierarchy roleHierarchy() {
        RoleHierarchyImpl hierarchy = new RoleHierarchyImpl();
        hierarchy.setHierarchy("ROLE_admin > ROLE_user > ROLE_peo");
        hierarchy.setHierarchy("ROLE_user > ROLE_peo");
        return hierarchy;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        /**
         * 替换之前登陆过滤器
         */
        http.addFilterAfter(loginFilter(),UsernamePasswordAuthenticationFilter.class);


        http.csrf().disable();

        http.authorizeRequests()
                .antMatchers("/admin/**").hasRole("admin")
                .antMatchers("/user/**").hasRole("user")
                .antMatchers("/verifyCode").permitAll()
                .anyRequest().authenticated();//任何请求登录后即可访问;
        http.exceptionHandling()//无状态(未认证)访问
                .authenticationEntryPoint((httpServletRequest, httpServletResponse, exception) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("尚未登陆,请登陆!"));//返回JSON数据
                    out.flush();
                    out.close();
                })
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessHandler((httpServletRequest, httpServletResponse, authentication) -> {
                    httpServletResponse.setContentType("application/json;charset=utf-8");
                    PrintWriter out = httpServletResponse.getWriter();
                    out.write(new ObjectMapper().writeValueAsString("注销登陆成功"));//注销成功
                    out.flush();
                    out.close();
                });
    }


}

在这里插入图片描述
在这里插入图片描述


4.写在最后

  • 这是MyBatis-plus 与 security 的整合,还有JPA 还有MyBatis等,自定义的整合就是这样,非自定义的上一篇博客也有。作为自己的笔记,需要的时候直接拿。
  • 总结:
  • 1.先创建项目,导入MyBatis-plus 与 Security 的依赖
  • 2.添加MyBatis-plus的配制文件并进行单元测试是否成功连接数据库
  • 3.添加Security 的配置文件并启用,由于是基于数据库的认证,所以需要对User类和UserServiceImpl进行实现接口,重写方法等,最后再配置文件中启用 ==auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());==,接着进行测试是否能认证成功正确登陆
  • 4.要进行前后端分离,使用JSON交互登陆,实现LoginFilter 过滤器。最后进行测试是否登陆拦截成功,是否能通过JSON或者key/value形式登陆。

5.最后的目录总图

目录总图

本文由 oldbai 原创发布于 阳光沙滩 , 未经作者授权,禁止转载
评论
0 / 1024
用户头像
厉害
2021-08-18 08:58回复
推荐文章
167年数学难题迎来历史性突破!AI真的证明了黎曼猜想吗?
困扰人类167年的数学圣杯——黎曼猜想,或许正迎来历史性转折。2026年,数学家与AI Claude合作完成形式化证明,Lean社区确认其正确性。这不仅是基础科学的重大突破,更标志着“人机协作”科研新纪元的开启。本文深入解析这一震撼事件,厘清其对密码学的真实影响,并探讨AI如何重塑数学探索的边界。见证历史,理解未知背后的秩序之美。
RocketMQ搭建-base on docker-compose
想快速搭建 RocketMQ 5.3.1 集群?本文提供基于 Docker Compose 的一站式部署指南。从目录结构规划到 Broker 配置详解,重点解析 NameServer、Broker、Proxy 及 Dashboard 的协同工作机制,并特别强调消息存储的数据持久化策略与权限设置。跟随步骤,轻松完成容器化环境构建,实现高效的消息队列服务部署与管理。
一篇文章讲清楚雅思、托福、GRE、SAT、GMAT:它们是什么?有什么区别?应该考哪个?
面对IELTS、TOEFL、GRE、SAT和GMAT,你是否感到困惑?本文深度解析五大考试的核心区别:从语言证明到学术能力评估,明确各自适用人群与场景。特别更新2026年托福改革及最新评分体系,通过对比表格与真实申请案例,助你精准定位目标考试,避免无效备考,高效规划海外升学之路。
一篇文章讲清楚 Android 签名:PK8、X509.PEM、JKS 是什么?它们有什么关系?
深入解析Android应用与系统签名的核心文件:PK8、X509.PEM与JKS。本文从非对称加密原理出发,厘清私钥、证书与密钥库的本质区别及相互转换方法,涵盖AOSP平台签名与普通应用发布的实际场景。通过对比V1-V4签名方案及解答常见疑难,助你掌握保障APK完整性与身份认证的关键技术,规避签名丢失或冲突风险。
系统监控运维系统
你是否也深受证书过期、磁盘满载等运维痛点的折磨?排查耗时,影响线上体验。本文分享一款自研运维系统面板,集成证书统一监测、资源预警及WebSSH等功能,实现问题快速定位与处理。附代码共享链接,欢迎参考或二次开发,提升运维效率。
断点说搞个万年历,怎么搞?
想快速拥有一个专属的程序员日历?只需一篇清晰的设计文档,剩下的交给AI!本文带你从零搭建“sob-calendar”项目,集成农历、节气及独特的程序员运势功能。通过实际案例展示如何利用AI高效生成代码并部署上线,让繁琐的开发工作变得轻松有趣,快来体验科技与传统历法的奇妙碰撞吧!
linux服务器的日志、容器清理
本手册提供了一套全面的Linux服务器磁盘清理与排查方法,帮助用户高效管理磁盘空间。通过查看磁盘使用情况、分析Docker占用、清理无用容器和日志,确保系统运行流畅。适合需要优化服务器性能的运维人员参考。
记给网站接入图形验证码
本文分享了如何为个人站点添加图形验证码以提升安全性,详细介绍了使用第三方接口实现验证码功能的过程,并通过代码示例展示了具体实现方式。对于关注网站安全的开发者来说,这篇文章提供了实用的参考价值。
Java开发环境搭建
本文是一份详细的Java开发环境搭建指南,涵盖了Java的发展历史、版本选择及安装配置过程。无论你是初学者还是有经验的开发者,都能从中找到实用的信息和步骤,帮助你快速上手Java开发。
Vue3.js项目的创建
本文详细介绍了如何使用Vue3创建项目,包括Node.js的安装和配置,以及项目的初始化过程。适合初学者学习如何快速搭建Vue3开发环境,并推荐了相关课程供进一步学习。
Network Tools : 您的运维“助手”升级了
Network Tools是一款专为解决运维难题而设计的软件,集设备管理、配置备份、性能监控和告警处理于一体。通过统一的工作台,帮助运维人员更高效地管理资产、定位故障并提升团队协作效率。无论是设备在线状态还是具体问题排查,都能得到全面支持。
Ubuntu 软件安装与彻底卸载指南
本文详细介绍了在 Ubuntu 系统中如何规范安装和彻底卸载 .deb 格式软件,包括依赖修复、残留清理以及图形化工具推荐,适合需要维护系统环境的用户。
JavaWeb开发客户程序更新特殊环境下的骚操作
本文分享了在无外网环境下,如何利用Docker和docker-compose实现高效部署的实战经验。通过基础镜像和本地jar包挂载的方式,解决了内网环境下的依赖问题,适合需要灵活部署方案的技术人员参考。
Linux 防火墙完全指南:从原理到多发行版实战
本文全面解析Linux防火墙的底层原理与主流工具配置,涵盖UFW、firewalld、iptables、nftables等方案,适合不同发行版用户。从基础概念到生产环境加固建议,助你掌握核心安全策略,确保服务器与网络的安全运行。
水上派对英语单词篇
探索FLOATOPIA水上派对的完整指南,涵盖签到流程、场地指引、安全须知、活动安排及夜场舞会等实用英语词汇与对话。无论是初学者还是老手,都能轻松掌握关键术语,享受完美水上体验。
麒麟操作系统下使用 virt-customize 重置虚拟机 root 密码实战
本文详细介绍了在麒麟操作系统环境下使用 virt-customize 工具重置 KVM 虚拟机 root 密码的完整流程,包含安装步骤、常见问题及解决方案,帮助运维人员高效处理密码遗忘或批量初始化场景,避免数据丢失。
浅析JS预编译-函数篇
本文详细讲解了JavaScript中函数的预编译过程,包括AO对象的创建、变量和函数声明的提升,以及执行阶段的变化。适合初学者了解JS执行机制,帮助深入理解代码运行逻辑。
访问Github的另一种姿势
本文介绍了如何通过Watt ToolKit等工具加速访问Github,适合对网络技术感兴趣的读者。内容涵盖工具介绍、下载和使用方法,以及一些实用技巧,值得一看。
使用Gulp压缩JS
本文详细介绍了如何使用Gulp压缩JavaScript文件,特别是支持ES6语法的处理方法。通过实际操作和效果对比,帮助开发者提升代码性能,适合对前端自动化工具感兴趣的读者。
使用Gulp压缩CSS
本文详细介绍了如何使用Gulp工具对CSS文件进行压缩,提升网页加载速度。适合需要优化静态资源的开发者,提供清晰的步骤和示例,帮助快速上手。
从0部署Nuxtjs项目
本文详细介绍了如何将Nuxt.js项目部署到公网,涵盖Node.js安装、环境配置、源码上传及使用PM2启动服务的全过程,适合开发者学习和实践。
Linux 命令行美化利器:tree 命令完全指南(安装 + 全部参数详解)
掌握 Linux 下的 `tree` 命令,快速直观地查看目录结构。本文详细讲解安装方法、参数含义及实战场景,适合开发者和系统管理员提升工作效率。
Linux常用命令(一)
本文详细介绍了Linux基础命令,包括文件操作、系统显示、网络状态、软件包管理等,适合初学者学习和查阅,是掌握Linux系统的实用指南。
大模型推理参数解码:温度、Top-p 与核采样如何塑造生成文本的灵魂
探索大语言模型的采样参数如何塑造生成内容,从温度到Top-p,从惩罚机制到熵控制,揭示背后的信息论原理与实践策略。了解如何通过参数调优,让AI既保持知识的严谨,又拥有创造力的自由。
记从0使用Claude code写代码
本文介绍了如何使用Claude Code搭配DeepSeek进行编程,详细讲解了安装Node.js、全局安装Claude、配置模型以及使用方法。对于开发者来说,这是一份实用的技术教程,尤其适合对AI编程工具感兴趣的读者。
Android-Studio-Gradle同步失败-Library为null的通用排查指南
遇到 Android Studio Gradle Sync 失败时,不要轻易删除全局缓存。本文详细解析了错误原因,并提供了一系列精准的排查步骤和解决方案,帮助开发者快速定位并解决问题,提升开发效率。
PHP实现密码加密
本文详细介绍了Bcrypt密码加密技术及其在PHP中的应用,帮助开发者提升用户密码的安全性。通过实际代码示例,展示了如何使用password_hash和password_verify函数进行密码加密与验证,是学习网络安全知识的实用指南。
WordCloud效果,滚动标签
本文详细介绍了如何在Vue项目中集成WordCloud组件,包括依赖安装、属性配置和使用方法。适合开发者学习如何实现数据可视化功能,提升项目交互体验。
从0使用WordPress搭建一个优美的网站
本文详细介绍了如何使用WordPress搭建一个美观的网站,从安装到主题配置和功能拓展,为读者提供了实用的操作指南。无论是初学者还是有一定经验的开发者,都能从中获得有价值的参考。
JS实现在网站底部添加运行时间
想知道如何在网站底部显示运行时间?本文详细讲解了通过JavaScript实现这一功能的方法,包括时间计算逻辑和代码实现。适合前端开发者学习参考,轻松为网站添加实用功能。