SpringBoot combined with Filter's login authentication and exit process (introducing what the backend needs to do)

Interaction process

Insert image description here

Brief diagram
Insert image description here
Note:
After clicking to access the application, the front-end needs to obtain the openId in the URL and store it in the request header of all requests. It is used by the back-end in the interceptor to determine whether there is an openId and to call the middle-end interface to determine whether the openId is valid.

rear end

The backend mainly does three things:

  • Create an interceptor to determine whether there is an openId and call the middle-end interface to determine whether the openId is valid, otherwise return 401 (HttpServletResponse.SC_UNAUTHORIZED) to the front end
  • The controller layer writes the interface for obtaining user information and logging out.
  • The controller writes an interface for obtaining user information and logging out.

(1) Get the annotations of the configuration file (whether interception is turned on)

@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) Write an interceptor

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) Register the interceptor into the 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) Obtain user information and log out

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);
}

Guess you like

Origin blog.csdn.net/weixin_42835230/article/details/131573037