Springboot JWT 集成认证
1.引入maven依赖:
<!-- JWT依赖 --> <dependency> <groupId>com.auth0</groupId> <artifactId>java-jwt</artifactId> <version>3.4.0</version> </dependency>
2. 创建JWT工具类:
public class Jwtutil { // 加密 TOKEN 密匙 private static final String SING = "QRDFQDdsf#dsfgsdffsd"; // 加密 TOKEN public static String getToken (Map<String,String> map) { Calendar instance = Calendar.getInstance(); instance.add(Calendar.SECOND, 2000); // 创建JWT builder JWTCreator.Builder builder = JWT.create(); // payload map.forEach((k, v)->{ builder.withClaim(k, v); }); String token = builder.withExpiresAt(instance.getTime()) .sign(Algorithm.HMAC256(SING)); return token; } // 验证 TOKEN public static void verifyToken(String token) { DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token); } // 获取 TOKEN 信息 public static DecodedJWT getTokeninfo(String token) { DecodedJWT verify = JWT.require(Algorithm.HMAC256(SING)).build().verify(token); return verify; } }
3. 创建 JWTinterceptors 拦截器:
public class JWTinterceptors implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { HashMap<String, Object> map = new HashMap<>(); // 获取请求头中token令牌 String token = request.getHeader("token"); try { // 验证令牌 Jwtutil.verifyToken(token); // 放行请求 return true; } catch (SignatureVerificationException e) { // e.printStackTrace(); map.put("msg", "无效签名"); } catch (TokenExpiredException e) { // e.printStackTrace(); map.put("msg", "token过期"); } catch (AlgorithmMismatchException e) { // e.printStackTrace(); map.put("msg", "token算法不一致"); } catch (Exception e) { // e.printStackTrace(); map.put("msg", "token无效"); } // 失败状态 map.put("state", false); // 将 map 转JSON String json = new ObjectMapper().writeValueAsString(map); response.setContentType("application/json;charset=UTF-8"); response.getWriter().println(json); return false; } }
4.创建 interceptorsConfig 拦截器配置:
@Configuration public class interceptorsConfig implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new JWTinterceptors()) .addPathPatterns("/**") .excludePathPatterns("/user/**") // 静态资源 .excludePathPatterns("/js/**", "/css/**", "/images/**", "/lib/**", "/fonts/**") // swagger-ui .excludePathPatterns("/swagger-resources/**", "/webjars/**", "/v2/**", "/swagger-ui.html/**", "/resources/**"); } // 必须添加 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("swagger-ui.html") .addResourceLocations("classpath:/META-INF/resources/"); registry.addResourceHandler("/webjars/**") .addResourceLocations("classpath:/META-INF/resources/webjars/") .addResourceLocations("/resources/**"); } }
5.创建测试 controller:
@RestController @ResponseBody @Api(value = "User", description = "User api") public class Usercontroller { @Autowired Userservice userservice; // 登录用户 @PostMapping("/user/login") @ResponseBody public Map<String, Object> Loginuser(@Param("name") String name, @Param("password") String password) { HashMap<String, Object> map = new HashMap<>(); try { HashMap<String, String> getToken = new HashMap<>(); User loginuser = userservice.Loginuser(name, password); getToken.put("name", loginuser.getName()); getToken.put("id", loginuser.getMailbox()); String token = Jwtutil.getToken(getToken); map.put("token", token); map.put("state", true); map.put("msg", "认证成功"); }catch (Exception e) { map.put("state", false); map.put("msg", e.getMessage()); } return map; } }
6.创建 service:
public interface Userservice { User Loginuser(String name, String password); }
7. 创建 serviceimpl:
@Service public class Userserviceimpl implements Userservice { @Autowired private Usermapper usermapper; @Override public User Loginuser(String name, String password) { User loginuser = usermapper.Loginuser(name, password); if (loginuser!=null) { return loginuser; } throw new RuntimeException("认证失败--"); } }
8. 创建 mapper:
public interface Usermapper { User Loginuser(@Param("name") String name, @Param("password") String password); }
9. 创建实体类:
public class User { private long id; private String name; private String password; private String mailbox; private String website; private long goldconis; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getMailbox() { return mailbox; } public void setMailbox(String mailbox) { this.mailbox = mailbox; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public long getGoldconis() { return goldconis; } public void setGoldconis(long goldconis) { this.goldconis = goldconis; } @Override public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", password='" + password + '\'' + ", mailbox='" + mailbox + '\'' + ", website='" + website + '\'' + ", goldconis=" + goldconis + '}'; } }
10. Mybatis XML 文件:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" > <mapper namespace="com.example.demo.mapper.Usermapper"> <select id="Loginuser" resultType="com.example.demo.entity.model.User"> select * from user where name = #{name} AND password = #{password} </select> </mapper>
11. 测试:
只是热爱开发的小渣渣!!