filter 过滤器 token 校验

 Filter 过滤器方法:

import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * web 端token 校验
 * @author wanght
 * @date 09:27 2019/04/25
 * @return
 */
@Configuration
@WebFilter
public class TokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if (request.getRequestURI().indexOf("/login/") >= 0) {
            filterChain.doFilter(request, response);
        } else {
            //如果请求的url 中包含 /web/,则进行token校验 
            if (request.getRequestURI().indexOf("/web/") != -1) {
                Map result = new HashMap();
                String accessToken = request.getHeader("webToken");
                // Header 中没有 token , 就看看参数中是否有
                if (StringUtils.isEmpty(accessToken)) {
                    accessToken = request.getParameter("webToken");
                }
                // 获取缓存中的token 及 用户信息
                String webTokenStr = redisTemplate.boundValueOps("webUsers:" + accessToken).get();
                if (null == accessToken) {
                    result.put("status",0);
                    result.put("message","token 不存在,请登录!");
                }else if (null == webTokenStr || webTokenStr.indexOf(accessToken) == -1){
                    result.put("status",0);
                    result.put("message","token 错误,请登录!");
                }else{
                    if (webTokenStr != null) {
                        filterChain.doFilter(request, response);
                    } else {
                        result.put("status",1);
                        result.put("message","token已过期,请重新登录!");
                    }
                }
                try {
                    responseOutWithJson(response, result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else{
                filterChain.doFilter(request, response);
            }
        }
    }

    protected void responseOutWithJson(HttpServletResponse response, Object responseObject) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writeValueAsString(responseObject);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(jsonStr);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }
}

 登录方法:

@RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result login(@RequestBody User user) {
        User users = userService.selectByNameOrPwd(user);
        if (users != null) {
            if (null != users.getStatus() && "0".equals(users.getStatus())){
                String token = fm.utils.number.UUIDTool.getUUID();
                RedisUserDto redisUserDto = new RedisUserDto(token, users);
                BoundValueOperations operations = redisTemplate.boundValueOps("webUsers:" + users.getId());
                sendOfflineNotifyMessage(operations);
                //operations.set(JSONObject.toJSONString(redisUserDto), 2, TimeUnit.HOURS);
                operations.set(JSONObject.toJSONString(redisUserDto), 30, TimeUnit.MINUTES);
                users.setToken(users.getId()+":"+token);
                return Result.success(users);
            }else{
                return Result.fail("15005", "该账号已禁用!");
            }
        } else {
            return Result.fail(ResultCode.ERRORMSG, "登录失败!");
        }
    }

保存redis信息实体:

/**
 * @Author: wanght
 * @Description:
 * @Date: 2019/1/10 14:20
 */
public class RedisUserDto {
    private String token;
    // user 实体类
    private User user;

    public RedisUserDto(String token, User user) {
        this.token = token;
        this.user = user;
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

 

你可能感兴趣的:(编程技术,java)