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

该文描述了一个使用SpringBoot构建的后端系统,它通过拦截器检查请求头中的OpenId,验证其有效性。无效时返回401错误。系统还包括获取用户信息和退出登录的接口,以及利用FeignClient调用中台API进行操作。
摘要由CSDN通过智能技术生成

交互流程

在这里插入图片描述

简略图
在这里插入图片描述
注意:
点击访问进入应用后前端要获取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);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值