删除用户功能
需求:删除用户,必须拥有管理员权限,否则不能删除。
前后端约定:前端请求微服务时需要添加头信息Authorization ,内容为Bearer+空格 +token

jwtutil工具类

package util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created by Administrator on 2018/4/11.
 */
@ConfigurationProperties("jwt.config")
public class JwtUtil {

    private String key ;

    private long ttl ;//一个小时

    public String getKey() {
        return key;
    }

    public void setKey(String key) {
        this.key = key;
    }

    public long getTtl() {
        return ttl;
    }

    public void setTtl(long ttl) {
        this.ttl = ttl;
    }

    /**
     * 生成JWT
     *
     * @param id
     * @param subject
     * @return
     */
    public String createJWT(String id, String subject, String roles) {
        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);
        JwtBuilder builder = Jwts.builder().setId(id)
                .setSubject(subject)
                .setIssuedAt(now)
                .signWith(SignatureAlgorithm.HS256, key).claim("roles", roles);
        if (ttl > 0) {
            builder.setExpiration( new Date( nowMillis + ttl));
        }
        return builder.compact();
    }

    /**
     * 解析JWT
     * @param jwtStr
     * @return
     */
    public Claims parseJWT(String jwtStr){
        return  Jwts.parser()
                .setSigningKey(key)
                .parseClaimsJws(jwtStr)
                .getBody();
    }

}

(1)修改UserService的deleteById方法 ,判断请求中的头信息,提取token并验证权限。

@Autowired
private HttpServletRequest request;
@Autowired
private JwtUtil jwtUtil;
/**
 * 删除  必须有admin角色才能删除
 * @param id
 */
public void deleteById(String id) {
   String header = request.getHeader("Authorization");//获取头信 息 
    if(header==null || "".equals(header)){
           throw new  RuntimeException("权限不足");
   }
   if(!header.startsWith("Bearer ")){
      throw new  RuntimeException("权限不足");
   }
//得到token
   String token = header.substring(7);
   try{
      Claims claims = jwtUtil.parseJWT(token);
      String roles = (String) claims.get("roles");
      if(roles==null || !roles.equals("admin")){
         throw new  RuntimeException("权限不足");
      }
   }catch(Exception e){
      throw new  RuntimeException("权限不足");
   }
 userDao.deleteById(id);
}

使用拦截器方式实现token鉴权
添加拦截器
创建拦截器类

(1)@Component //放入容器中
public class JwtInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtUtil jwtUtil;
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("经过了拦截器");
        //无论如何都放行.具体能不能操作还是在具体的操作去判断
        //拦截器只是负责把头请求头中包含token的令牌进行一个解析验证
        String header = request.getHeader("Authorization");
        if(header!=null && !"".equals(header)){
            //如果包含有Authorization头信息,就对其进行解析
            if(header.startsWith("Bearer ")){
                //得到token
                String token = header.substring(7);
                //对token进行验证
                try{
Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");
                    if(roles!=null || roles.equals("admin")){
                        request.setAttribute("claims_admin",token);
                    }
                    if(roles!=null || roles.equals("user")){
                        request.setAttribute("claims_user",token);
                    }
                }catch(Exception e){
                    throw new  RuntimeException("令牌不正确");
                }
   }
        }
        return true;
    }
}

2)配置拦截器类

@Configuration
@Component
public class InterceptorConfig extends WebMvcConfigurationSupport{
    @Autowired
    private JwtInterceptor jwtInterceptor;
    protected void addInterceptors(InterceptorRegistry registry){
         //注册拦截器要声明拦截器对象和要拦截的请求
        registry.addInterceptor(jwtInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/**/login/**");
    }
}

拦截器验证token
2)修改UserService的delete方法

/**
 * 删除  必须有admin角色才能删除
 * @param id
 */
public void deleteById(String id) {
   String token = (String) request.getAttribute("claims_admin");
   if(token==null || "".equals(token)){
      throw new RuntimeException("权限不足!");
   }
   userDao.deleteById(id);
}
Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐