SpringBootSession接口验证实现流程详解

2022-11-13 17:11:31 接口 验证 详解

需求:只有用户登录成功后,才能访问其它接口,否则提示需要进行登录

项目仓库地址:https://gitee.com/aiw-nine/SpringBoot_session_verify

添加pom.xml

新建Spring Boot(2.7.2)项目,添加如下依赖:

<?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.7.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.aiw</groupId>
    <artifactId>waimai</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>waimai</name>
    <description>waimai</description>
    <properties>
        <java.version>17</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-WEB</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastJSON</artifactId>
            <version>1.2.76</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

创建简单的测试接口

package com.aiw.springboot_session_verify.controller;
import com.aiw.springboot_session_verify.entity.User;
import com.aiw.springboot_session_verify.response.R;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
@RestController
@RequestMapping("/user")
public class UserController {
    
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public R<User> login(@RequestBody User user, HttpServletRequest request) {
    	// 此处应该和数据库进行交互判断,为做测试,简单写死
        if (Objects.equals(user.getId(), 1) && Objects.equals(user.getName(), "Aiw")) {
            // 登录成功,将id存入session并返回登录成功结果
            request.getSession().setAttribute("user", user.getId());
            request.getSession().setMaxInactiveInterval(1800);  // 设置session失效时间为30分钟
            return R.success("登录成功", user);
        }
        return R.fail("登录失败");
    }
    
    @RequestMapping(value = "/loGout", method = RequestMethod.POST)
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }
    
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public R<String> index() {
        return R.success("首页,访问成功");
    }
}

使用过滤器实现

创建LoginCheckFilter.java类,实现Filter接口

package com.aiw.springboot_session_verify.filter;
import com.aiw.springboot_session_verify.response.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@WebFilter
public class LoginCheckFilter implements Filter {
    // 路径匹配器,支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        log.info("拦截到的请求:{}", request.getRequestURI());
        // 1、获取本次请求的URI
        String requestURI = request.getRequestURI();
        // 定义不需要处理的请求路径
        String[] urls = new String[]{"/user/login", "/user/logout"};
        // 2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        // 3、如果不需要处理,则直接放行
        if (check) {
            log.info("本次请求{}不需要处理", requestURI);
            filterChain.doFilter(request, response);
            return;
        }
        // 4、判断登录状态,如果已登录,则直接放行
        if (Objects.nonNull(request.getSession().getAttribute("user"))) {
            log.info("用户已登录,用户id为:{}", request.getSession().getAttribute("user"));
            filterChain.doFilter(request, response);
            return;
        }
        // 5、如果未登录则返回未登录结果,通过输出流方式向客户端页面响应数据
        log.info("用户未登录");
        response.setContentType("application/json; charset=utf-8");
        // 1、使用Fastjson(默认过滤null值)
        response.getWriter().write(JSON.toJSONString(R.error("未登录")));
        // 2、使用默认的Jackson,此处关于Jackson配置的相关属性会失效(即若在配置文件中配置过滤null值,这里返回时不会过滤)
        // response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("未登录")));
        return;
    }
    
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if (match) return true;
        }
        return false;
    }
}

修改启动类

package com.aiw.springboot_session_verify;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
@ServletComponentScan
@SpringBootApplication
public class SpringbootSessionVerifyApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootSessionVerifyApplication.class, args);
    }
}

启动项目,使用apiPost进行接口测试。首先在未登录状态下,访问/user/index接口

可以看到在未登录时,访问其它接口会失败

此时先进行登录,访问/user/login接口

再次访问/user/index接口

即登录成功后,可以成功访问该接口;为保证后续操作,此处再访问/user/logout接口,删除后端的session

使用拦截器实现

创建LoginCheckInterceptor.java类,实现HandlerInterceptor接口

package com.aiw.springboot_session_verify.interceptor;
import com.aiw.springboot_session_verify.response.R;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

@Slf4j
public class LoginCheckInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取请求
        log.info("拦截的请求:{}", request.getRequestURI());
        //2.判断用户是否登录
        HttpSession session = request.getSession();
        // 若存在,则放行
        if (Objects.nonNull(session.getAttribute("user"))) return true;
        //拦截住,并给前端页面返回未登录信息,以输出流的方式,json格式返回
        response.setContentType("application/json; charset=utf-8");
        // 1、使用Fastjson(默认过滤null值)
        response.getWriter().write(JSON.toJSONString(R.error("未登录")));
        // 2、使用默认的Jackson,在配置文件中关于Jackson配置的相关属性会失效
        //response.getWriter().write(new ObjectMapper().writeValueAsString(R.error("未登录")));
        return false;
    }
}

注册拦截器,新建配置类WebConfig.java,实现WebmvcConfigurer接口

package com.aiw.springboot_session_verify.config;
import com.aiw.springboot_session_verify.interceptor.LoginCheckInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorReGIStry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginCheckInterceptor())
                .addPathPatterns("/**")
                // 排除的请求路径
                .excludePathPatterns("/user/login", "/user/logout");
    }
}

注释掉LoginCheckFilter.java类,再注释掉启动类上的@ServletComponentScan注解,防止过滤器的干扰,启动项目。首先在未登录状态下,访问/user/index接口

进行登录,访问/user/login接口

再次访问/user/index接口

至此,全部完成,当然后期可以使用Spring Boot+Jwt实现接口验证

到此这篇关于SpringBoot Session接口验证实现流程详解的文章就介绍到这了,更多相关SpringBoot Session接口验证内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

相关文章