springcloud服务网关--权限校验

1.实现如下三个功能:
springcloud服务网关--权限校验_第1张图片
2.买家登陆api
springcloud服务网关--权限校验_第2张图片
3.卖家登陆
springcloud服务网关--权限校验_第3张图片
4.构建user服务 模拟买家登陆和卖家登陆

package com.zhu.user.controller;


import com.zhu.user.entity.UserInfo;
import com.zhu.user.service.IUserInfoService;
import com.zhu.user.utill.CookieUtil;
import com.zhu.user.utill.Result;
import com.zhu.user.utill.ResultEnum;
import com.zhu.user.utill.ResultUtil;
import lombok.extern.log4j.Log4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 

* 前端控制器 *

* * @author pacey * @since 2019-02-11 */ @Log4j @RestController @RequestMapping("/userInfo") public class UserInfoController { @Autowired private IUserInfoService iUserInfoService; // 操作redis @Autowired private StringRedisTemplate stringRedisTemplate; /** * 买家登陆 * @param openid * @param response * @return */ @GetMapping("/buyer") public Result LoginByBuyer(@RequestParam("openid") String openid, HttpServletResponse response) { log.info("buyer openid"+openid); //1.openid和数据库的匹配 UserInfo userInfo= iUserInfoService.selectByOpenId(openid); System.out.println("1:"+userInfo); if (userInfo==null) { return ResultUtil.error(99,ResultEnum.OPENID_IS_NOT_EXISTS.getMsg()); } //判断角色 1是买家 2是卖家 if(userInfo.getRole()!=1) { return ResultUtil.error(100,ResultEnum.ROLE_ERROR.getMsg()); } //设置cookie (name value 过期时间单位是s) CookieUtil.set(response,"openid",openid,7200); log.info("设置cookie成功"); return ResultUtil.success(); } /** * 卖家登陆 * @param openid * @param response * @return */ @GetMapping("/seller") public Result LoginBySeller(@RequestParam("openid") String openid,HttpServletRequest request, HttpServletResponse response) { log.info("seller openid"+openid); //生成UUID String token = UUID.randomUUID().toString(); //判断是否登陆 cookie不为null redis不为null Cookie cookie= CookieUtil.get(request,"token_UUID"); if (cookie!=null && !StringUtils.isEmpty(stringRedisTemplate.opsForValue().get(String.format("token_UUID",cookie.getValue())))) { //这样就会防止不停的往redis里面set数据 ResultUtil.success(); } //1.openid和数据库的匹配 UserInfo userInfo= iUserInfoService.selectByOpenId(openid); System.out.println("2:"+userInfo); if (userInfo==null) { return ResultUtil.error(99,ResultEnum.OPENID_IS_NOT_EXISTS.getMsg()); } //2判断角色 1是买家 2是卖家 if(userInfo.getRole()!=2) { return ResultUtil.error(100,ResultEnum.ROLE_ERROR.getMsg()); } //设置redis key =uuid value =xzy expire 过期时间 stringRedisTemplate.opsForValue().set(String.format("token_UUID",token),openid,7200, TimeUnit.SECONDS); log.info("设置redis成功"); //设置cookie (token=UUID 过期时间单位是s) CookieUtil.set(response,"token_UUID",token,7200); log.info("设置cookie成功"); return ResultUtil.success(); } }

5.cookie util 获取和设置cookie

package com.zhu.user.utill;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CookieUtil {

    /**
     * 设置cookie
     * @param response
     * @param name
     * @param value
     * @param maxAge
     */
    public static void set(HttpServletResponse response,String name,String value,int maxAge)
    {
        Cookie cookie =new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);


    }

    /**
     * 获取cookie
     * @param request
     * @param name
     * @return
     */
    public static Cookie get(HttpServletRequest request,String name)
    {
        Cookie[] cookies = request.getCookies();
        if(cookies!=null)
        {
          for (Cookie cookie:cookies)
          {
              if (name.equals(cookie.getName()))
              {
                  return cookie;
              }
          }
        }
        return null;
    }
}

6.服务网关 鉴权

package com.zhu.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhu.apigateway.util.CookieUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpStatus;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * 权限拦截 区分买家和卖家
 */
@Component
public class AuthFilter extends ZuulFilter {

    /*FilterConstants*/
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER-1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 前置逻辑写在run方法内
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {
         RequestContext requestContext= RequestContext.getCurrentContext();
             HttpServletRequest request= requestContext.getRequest();
        //create 只能买家访问
        //finish 只能卖家访问
        //list 都可访问
        if("/product/productInfo".equals(request.getRequestURI()))
        {
            //cookie为空认为没有权限
            Cookie cookie = CookieUtil.get(request,"openid");
            if (cookie==null || StringUtils.isEmpty(cookie.getValue()))
            {
                requestContext.setSendZuulResponse(false);
                requestContext.setResponseStatusCode(HttpStatus.SC_UNAUTHORIZED);
            }
        }

        return null;
    }
}

7.如果cookie为null 则权限不足 --买家
如果cookie为null 并且 redis为空 权限不足 --卖家

你可能感兴趣的:(springcloud)