SpringBoot+Vue豆宝社区前后端分离项目手把手实战系列教程09---登录后用户信息获取

286 阅读2分钟

豆宝社区项目实战教程简介

本项目实战教程配有免费视频教程,配套代码完全开源。手把手从零开始搭建一个目前应用最广泛的Springboot+Vue前后端分离多用户社区项目。本项目难度适中,为便于大家学习,每一集视频教程对应在Github上的每一次提交。

项目首页截图

image

代码开源地址

前端 后端

视频教程地址

视频教程

前端技术栈

Vue Vuex Vue Router Axios Bulma Buefy Element Vditor DarkReader

后端技术栈

Spring Boot Mysql Mybatis MyBatis-Plus Spring Security JWT Lombok

获取用户信息前端

1.在viwes/login.vue

this.$store.dispatch("user/getInfo")

image-20210212132928210

2.API配置

在src/api/auth/auth.js

// 获取用户信息
export function getUserInfo() {
  return request({
    url: '/auth/user/info',
    method: 'get'
  })
}

3.src\store\modules\user.js

已添加,看看就行

image-20210212133241834

4.src\utils\request.js

引入,不引入报错信息(store is not defined)

import store from '@/store'
import { getToken } from '@/utils/auth'

添加拦截器

// 2.请求拦截器request interceptor
service.interceptors.request.use(
  config => {
    // 发请求前做的一些处理,数据转化,配置请求头,设置token,设置loading等,根据需求去添加
    // 注意使用token的时候需要引入cookie方法或者用本地localStorage等方法,推荐js-cookie
    if (store.getters.token) {
      // config.params = {'token': token}    // 如果要求携带在参数中
      // config.headers.token = token;       // 如果要求携带在请求头中
      // bearer:w3c规范
      config.headers['Authorization'] = 'Bearer ' + getToken()
    }
    return config
  },
  error => {
    // do something with request error
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

5.页面效果

在登录后回去请求info,(我用户谷歌没有请求地址,换成火狐浏览器看的)

image-20210212134757947

拦截器token

isProtectedUrl方法中添加请求路径,只有登录后(有token才能访问,否则就不能访问)

1.JwtAuthenticationFilter过滤器

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Configuration
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private static final PathMatcher pathMatcher = new AntPathMatcher();

    /**
     * 拦截方法
     *
     * @param request
     * @param response
     * @param filterChain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        try {
            if (isProtectedUrl(request)) {
//                System.out.println(request.getMethod());
                if (!request.getMethod().equals("OPTIONS")) {
                    // 解析token,如果是我们生成的,则可以解析
                    request = JwtUtil.validateTokenAndAddUserIdToHeader(request);
                }
            }
        } catch (Exception e) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
            return;
        }
        filterChain.doFilter(request, response);
    }

    /**
     * 受保护的请求(后期我们替换这些地址)
     *
     * @param request
     * @return
     */
    private boolean isProtectedUrl(HttpServletRequest request) {
        List<String> protectedPaths = new ArrayList<String>();
        protectedPaths.add("/auth/user/info");
        protectedPaths.add("/auth/user/update");
        protectedPaths.add("/post/create");
        protectedPaths.add("/post/update");
        protectedPaths.add("/post/delete/*");
        protectedPaths.add("/comment/add_comment");
        protectedPaths.add("/relationship/subscribe/*");
        protectedPaths.add("/relationship/unsubscribe/*");
        protectedPaths.add("/relationship/validate/*");

        boolean bFind = false;
        for (String passedPath : protectedPaths) {
            bFind = pathMatcher.match(passedPath, request.getServletPath());
            if (bFind) {
                break;
            }
        }
        return bFind;
    }

    @Bean
    public FilterRegistrationBean jwtFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
        registrationBean.setFilter(filter);
        return registrationBean;
    }

}

修改引导类

image-20210212140816102

获取用户信息后端

@RequestHeader(value = "userName")这一块比较绕,看视频吧

www.bilibili.com/video/BV1Wz…

1.UmsUserController

@GetMapping("/info")
public ApiResult loginUserInfo(@RequestHeader(value = "userName") String userName) {
    UmsUser umsUser = umsUserService.getOne(
            new LambdaQueryWrapper<UmsUser>().eq(UmsUser::getUsername,userName)
    );
    return ApiResult.success(umsUser);
}

2.测试页面

image-20210212143145460