SpringBoot结合Filter的登录认证退出流程(介绍后端要做的事)

交互流程

SpringBoot结合Filter的登录认证退出流程(介绍后端要做的事)_第1张图片

简略图
SpringBoot结合Filter的登录认证退出流程(介绍后端要做的事)_第2张图片
注意:
点击访问进入应用后前端要获取url中的openId存放在所有请求的请求头里,用于后端在拦截器中判断是否有openId和调用中台接口判断openId是否有效

后端

后端主要做三件事:

  • 搞个拦截器用于判断是否有openId和调用中台接口判断openId是否有效,否则返回 401(HttpServletResponse.SC_UNAUTHORIZED)给前端
  • controller层编写获取用户信息和退出登录的接口
  • controller编写获取用户信息和退出登录的接口

(1)获取配置文件的注解(拦截是否开启)

@Component
@EnableAutoConfiguration
@ConfigurationProperties(prefix = "interceptor" ) // yml中的前缀
@Primary
public class Interceptor {
    private String enable;

    public String getEnable() {
        return enable;
    }

    public void setEnable(String enable) {
        this.enable = enable;
    }
}

(2)编写拦截器

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

@Configuration
@WebFilter(value = "/*")
public class OpenIDFilter implements Filter {

    @Autowired
    private AuthServiceApiClient authServiceApiClient;

    @Autowired
    private Interceptor interceptor;

    private static final String OPEN_ID = "openId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        Boolean enable = Boolean.valueOf(interceptor.getEnable());
        if (enable) {
	            // 获取请求地址
	            String openId = req.getHeader("openId");

                JSONObject userInfo = new JSONObject();
                if (!StringUtils.isEmpty(openId)){
                    userInfo = authServiceApiClient.getUserInfo(openId);
                }
                if (StringUtils.isEmpty(openId) || ObjectUtils.isEmpty(userInfo) || !userInfo.get("code").equals(0)) {
                    res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "https://10.151.228.51:30005/");
                }
        }
        chain.doFilter(req, res);
    }
}

(3)注册拦截器到bean中

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

@Configuration
public class MyFilter {

    @Bean
    public FilterRegistrationBean sessionExpireFilter(){
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(this.OpenIDFilter());
        return registrationBean;
    }

    @Bean
    public Filter OpenIDFilter() {
        return new OpenIDFilter();
    }
}

(3)获取用户信息和退出登录

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cspg.snlsct.cs.auth.AuthServiceApiClient;
import com.cspg.snlsct.ms.constant.Constants;
import com.cspg.snlsct.ms.vo.Result;
import com.cspg.snlsct.ms.vo.auth.AuthUserVo;
import com.cspg.snlsct.rs.utils.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;

@RestController
@Api(tags = "数据中台认证")
@RequestMapping("/auth")
@RequiredArgsConstructor
public class AuthController {
    @Autowired
    private AuthServiceApiClient authServiceApiClient;


    @ApiOperation("获取用户信息接口")
    @GetMapping("/getUserInfo")
    public Result<AuthUserVo> getEnergyDistribution(HttpServletRequest request) {
        String token = request.getHeader("openId");
        if (!StringUtils.isEmpty(token)) {
            JSONObject userInfo = authServiceApiClient.getUserInfo(token);
            if (!ObjectUtil.isEmpty(userInfo)) {
                if (userInfo.get("code").equals(0)) {
                    AuthUserVo authUserVo = JSONObject.parseObject(JSON.toJSONString(userInfo.get("data")), AuthUserVo.class);
                    return ResultUtil.data(authUserVo);
                }
            }
        }
        return null;
    }

    @ApiOperation("退出登录API")
    @GetMapping("/logout")
    public Result logout(HttpServletRequest request) {
        String openId = request.getHeader("openId");
        if (!StringUtils.isEmpty(openId)) {
            JSONObject logout = authServiceApiClient.logout(openId);
            System.out.println("logout: " + logout);
        }
        return ResultUtil.success("https://10.151.228.51:30005/");
        // return ResultUtil.error(500,"退出异常");
    }
}
import com.alibaba.fastjson.JSONObject;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestParam;
@FeignClient(name = "auth", url = "${auth.url}")
@Component
public interface AuthServiceApiClient {

    /**
     * 获取用户信息接口
     * @return
     */
    @PostMapping(value = "/user-center/user/getUserInfo")
    //@GetMapping(value = "/api/auth/user")
    JSONObject getUserInfo(@RequestHeader("openId") String openId);


    /**
     * 退出登录接口
     * @return
     */
    @PostMapping(value = "/user-center/user/logout")
    JSONObject logout(@RequestParam("openId") String openId);
}

你可能感兴趣的:(spring,boot,后端,java)