springboot JWT密钥 调用filter或Interceptor拦截
LoginController
(图片来源网络,侵删)
package com.itheima.controller; import com.itheima.pojo.Emp; import com.itheima.pojo.Result; import com.itheima.service.EService; import com.itheima.utils.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @Slf4j @RestController public class LoginController { @Autowired private EService eService; @PostMapping("/login") public Result login(@RequestBody Emp emp){ log.info("员工登录: {}", emp); //调用Service层和Mapper层查看是否存在该员工 Emp e = eService.Login(emp); //登录成功,生成令牌,下发令牌 if (e != null){ Map claims = new HashMap(); claims.put("id", e.getId()); claims.put("name", e.getName()); claims.put("username", e.getUsername()); String jwt = JwtUtils.generateJwt(claims); //jwt包含了当前登录的员工信息 return Result.success(jwt); } //登录失败, 返回错误信息 return Result.error("失败"); } }
导入JWT工具类
package com.itheima.utils; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; public class JwtUtils { private static String signKey = "itheima"; private static Long expire = 43200000L; /** * 生成JWT令牌 * @param claims JWT第二部分负载 payload 中存储的内容 * @return */ public static String generateJwt(Map claims){ String jwt = Jwts.builder() .addClaims(claims) .signWith(SignatureAlgorithm.HS256, signKey) .setExpiration(new Date(System.currentTimeMillis() + expire)) .compact(); return jwt; } /** * 解析JWT令牌 * @param jwt JWT令牌 * @return JWT第二部分负载 payload 中存储的内容 */ public static Claims parseJWT(String jwt){ Claims claims = Jwts.parser() .setSigningKey(signKey) .parseClaimsJws(jwt) .getBody(); return claims; } }
使用Interceptor拦截
package com.itheima.interceptor; import com.alibaba.fastjson.JSONObject; import com.itheima.pojo.Result; import com.itheima.utils.JwtUtils; import lombok.extern.slf4j.Slf4j; import org.apache.http.HeaderIterator; import org.springframework.context.annotation.Configuration; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Slf4j @Component public class LoginCheckInterceptor implements HandlerInterceptor { @Override//目标方法运行前运行,true: 放行 false:不放行 public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception { System.out.println("preHandle"); String url = req.getRequestURL().toString(); //判定url中是否包含login if (url.contains("login")){ log.info("登录操作,,,放行"); return true; } //获取请求头的令牌(token) String token = req.getHeader("token"); //检测令牌是否存在 if(!StringUtils.hasLength(token)){ log.info("令牌不存在"); Result error = Result.error("NOT_LOGIN"); String notLogin = JSONObject.toJSONString(error); res.getWriter().write(notLogin); return false; } //解析令牌 try { JwtUtils.parseJWT(token); } catch (Exception e) { log.info("令牌解析失败"); Result error = Result.error("NOT_LOGIN"); String notLogin = JSONObject.toJSONString(error); res.getWriter().write(notLogin); return false; } log.info("解析成功"); return true; } @Override//目标资源方法后运行 public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { System.out.println("postHandle"); } @Override//最后运行 public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { System.out.println("afterCompletion"); } }
该拦截器的配置类
package com.itheima.config; import com.itheima.interceptor.LoginCheckInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration //配置类 public class WebConfig implements WebMvcConfigurer { @Autowired private LoginCheckInterceptor loginCheckInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(loginCheckInterceptor).addPathPatterns("/**").excludePathPatterns("/login"); } }
使用Filter过滤
package com.itheima.filter; import com.alibaba.fastjson.JSONObject; import com.alibaba.fastjson.support.spring.annotation.FastJsonFilter; import com.itheima.pojo.Result; import com.itheima.utils.JwtUtils; import io.jsonwebtoken.Claims; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Component; import org.springframework.util.StringUtils; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.net.http.HttpResponse; @Slf4j //@WebFilter("/*") public class LoginCheckFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //获取url HttpServletRequest req=(HttpServletRequest) request; HttpServletResponse res=(HttpServletResponse) response; String url = req.getRequestURL().toString(); //判定url中是否包含login if (url.contains("login")){ log.info("登录操作,,,放行"); chain.doFilter(request,response); return; } //获取请求头的令牌(token) String token = req.getHeader("token"); //检测令牌是否存在 if(!StringUtils.hasLength(token)){ log.info("令牌不存在"); Result error = Result.error("NOT_LOGIN"); String notLogin = JSONObject.toJSONString(error); res.getWriter().write(notLogin); return; } //解析令牌 try { JwtUtils.parseJWT(token); } catch (Exception e) { log.info("令牌解析失败"); } log.info("解析成功"); chain.doFilter(request,response); } }
文章版权声明:除非注明,否则均为主机测评原创文章,转载或复制请以超链接形式并注明出处。