创建项目
环境配置
JDK:1.8 MAVEN:3.6.1 IDE:19.3 TOMCAT:8 MYSQL:5.7 swagger-ui2
基本框架搭建
可参考本人博客地址
https://blog.csdn.net/qq_41998978/article/details/103362147
添加TOKEN验证
pom.xml文件加入以下
<!-- jwt -->
<dependency>
<groupId>com.auth0</groupId>
<artifactId>java-jwt</artifactId>
<version>2.2.0</version>
</dependency>
JWT加密解密工具类
/**
* 项目名:AutomobileModelTradingPlatform
* 日 期:2020/2/9
* 包 名:com.item.utile
*
* @author: LiuJia
* Copyright 2019 403
*/
package com.item.utile;
import com.auth0.jwt.JWTSigner;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.internal.com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class JWT {
private static final String SECRET = "XX#$%()(#*!()!KL<><MQLMNQNQJQK sdfkjsdrow32234545fdf>?N<:{LWPW";
private static final String EXP = "exp";
private static final String PAYLOAD = "payload";
//加密,传入一个对象和有效期
public static <T> String sign(T object, long maxAge) {
try {
final JWTSigner signer = new JWTSigner(SECRET);
final Map<String, Object> claims = new HashMap<String, Object>();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(object);
claims.put(PAYLOAD, jsonString);
claims.put(EXP, System.currentTimeMillis() + maxAge);
return signer.sign(claims);
} catch(Exception e) {
return null;
}
}
//解密,传入一个加密后的token字符串和解密后的类型
public static<T> T unsign(String jwt, Class<T> classT) {
final JWTVerifier verifier = new JWTVerifier(SECRET);
try {
final Map<String,Object> claims= verifier.verify(jwt);
if (claims.containsKey(EXP) && claims.containsKey(PAYLOAD)) {
long exp = (Long)claims.get(EXP);
long currentTimeMillis = System.currentTimeMillis();
if (exp > currentTimeMillis) {
String json = (String)claims.get(PAYLOAD);
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, classT);
}
}
return null;
} catch (Exception e) {
return null;
}
}
}
SSM中拦截器判断TOKEN工具类
/**
* 项目名:AutomobileModelTradingPlatform
* 日 期:2020/2/4
* 包 名:com.item.utile
*
* @author: LiuJia
* Copyright 2019 403
*/
package com.item.utile;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.item.entity.Adminuser;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
public class TokenInterceptor implements HandlerInterceptor {
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception arg3)
throws Exception {
}
public void postHandle(HttpServletRequest request, HttpServletResponse response,
Object handler, ModelAndView model) throws Exception {
}
//拦截每个请求
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object handler) throws Exception {
response.setCharacterEncoding("utf-8");
//读取请求头中的Token信息
String token = request.getHeader("token");
//判断token是否存在
if (null != token) {
//获取token中的实体类信息
Adminuser adminuser = JWT.unsign(token, Adminuser.class);
//获取请求头中用户id信息
String userId = request.getHeader("userId");
//判断token是否合法
if (null != userId && null != adminuser) {
//解密token后得到的用户id和请求头中的用户对比
if (Integer.parseInt(userId) == adminuser.getId()) {
return true;
} else {
//这里的ResponseData是包装的json工具类
ResponseData responseData = ResponseData.customerError("token已过期");
responseMessage(response, response.getWriter(), responseData);
return false;
}
} else {
ResponseData responseData = ResponseData.customerError("token无效");
responseMessage(response, response.getWriter(), responseData);
return false;
}
} else {
ResponseData responseData = ResponseData.customerError("无token");
responseMessage(response, response.getWriter(), responseData);
return false;
}
}
//请求不通过,返回错误信息给客户端
private void responseMessage(HttpServletResponse response, PrintWriter out, ResponseData responseData) {
response.setContentType("application/json; charset=utf-8");
String json = JSONObject.toJSONString(responseData);
out.print(json);
out.flush();
out.close();
}
}
spring-mvc.xml配置文件加入拦截器
<mvc:interceptors>
<mvc:interceptor>
<!-- 设置拦截的路径 -->
<mvc:mapping path="/Api/**"/>
<!-- 设置放开拦截的路径,这里是登录 -->
<mvc:exclude-mapping path="/Api/userApi/login"/>
<!-- 指定自己的拦截器工具类路径-->
<bean class="com.item.utile.TokenInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!--这里配置返回json时可能出现乱码。处理乱码-->
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes" value="text/plain;charset=UTF-8"/>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
用于返回给客户端的json包装类
/**
* 项目名:AutomobileModelTradingPlatform
* 日 期:2020/2/9
* 包 名:com.item.utile
*
* @author: LiuJia
* Copyright 2019 xiaojiajia
*/
package com.item.utile;
import java.util.HashMap;
import java.util.Map;
public class ResponseData {
private final String message;
private final int code;
private final Map<String, Object> data = new HashMap<String, Object>();
public String getMessage() {
return message;
}
public int getCode() {
return code;
}
public Map<String, Object> getData() {
return data;
}
public ResponseData putDataValue(String key, Object value) {
data.put(key, value);
return this;
}
private ResponseData(int code, String message) {
this.code = code;
this.message = message;
}
public static ResponseData ok() {
return new ResponseData(200, "访问成功");
}
public static ResponseData notFound() {
return new ResponseData(404, "服务器丢失");
}
public static ResponseData badRequest() {
return new ResponseData(400, "服务器错误");
}
public static ResponseData forbidden() {
return new ResponseData(403, "系统错误");
}
public static ResponseData unauthorized() {
return new ResponseData(401, "未经授权");
}
public static ResponseData serverInternalError() {
return new ResponseData(500, "服务器内部错误");
}
public static ResponseData customerError(String message) {
return new ResponseData(1001, message);
}
}
处理登录
@RequestMapping("/login")
public Object login(String userName, String userPwd) {
//这里采用的是封装工具查询,此处不做说明
AdminuserExample adminuserExample = new AdminuserExample();
AdminuserExample.Criteria criteria = adminuserExample.createCriteria();
criteria.andAdminusercodeEqualTo(userName);
List<Adminuser> adminuserList = adminuserService.selectByExample(adminuserExample);
if (adminuserList.size() > 0) {
if (adminuserList.get(0).getAdminuserpwd().equals(userPwd)) {
//登录成功
//生成加密token
String token = JWT.sign(adminuserList.get(0), 60L * 1000L * 30L);
//返回给客户端的信息
ResponseData responseData = ResponseData.ok();
responseData.putDataValue("userId", adminuserList.get(0).getId());
responseData.putDataValue("token", token);
responseData.putDataValue("user", adminuserList.get(0));
return responseData;
} else {
ResponseData responseData = ResponseData.customerError("密码错误");
return responseData;
}
} else {
ResponseData responseData = ResponseData.customerError("无效用户名");
return responseData;
}
}
验证说明:在之后请求接口时,前端需要在请求头中带上“userId”和“token”两个参数,解密token后和前端传来的用户id对比,以此判断token的合法性。
加入Swagger-ui接口文档
pom.xml文件加入
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
SwaggerConfiguration工具类
/**
* 项目名:eep
* 日 期:2020/2/10
* 包 名:com.item.utile
*
* @author: Liujia
* Copyright 2019 xiaojiajiaK3
*/
package com.item.utile;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
import java.util.List;
import static springfox.documentation.builders.PathSelectors.regex;
@Configuration
@EnableSwagger2
//@Profile({"prod"})
public class SwaggerConfiguration {
@Bean
public Docket platformApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).forCodeGeneration(true)
.select().apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(regex("^.*(?<!error)$"))
.build()
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
.pathMapping("/")
;
}
private List<ApiKey> securitySchemes() {
return Lists.newArrayList(
//这里配置两个全局头请求-跟上面token验证配套
new ApiKey("token", "token", "header"),
new ApiKey("userId", "userId", "header")
);
}
private List<SecurityContext> securityContexts() {
return Lists.newArrayList(
SecurityContext.builder()
.securityReferences(defaultAuth())
.build()
);
}
List<SecurityReference> defaultAuth() {
AuthorizationScope authorizationScope = new AuthorizationScope("global", "认证权限");
return Lists.newArrayList(
//这里配置两个头请求-每个接口-跟上面token验证配套
new SecurityReference("token", new AuthorizationScope[]{authorizationScope}),
new SecurityReference("userId", new AuthorizationScope[]{authorizationScope})
);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder().title("xxx平台接口文档").description("©xiaojiajiaK3")
.termsOfServiceUrl("https://blog.csdn.net/qq_41998978")
.contact(new Contact("xxx交易平台", "", "xiaojiajia981225@outlook.com")).license("Apache License Version 2.0")
.licenseUrl("https://blog.csdn.net/qq_41998978").version("2.0").build();
}
}
spring-mvc.xml配置文件加入
<!-- 加载SwaggerConfig 类名改成自己创建的-->
<bean class="com.item.utile.SwaggerConfiguration"/>
<!-- 将静态资源交由默认的servlet处理--没有这句的加上这句 -->
<mvc:default-servlet-handler/>
使用
//控制器加入
@Api(tags = "xxx接口")
//方法加入
@ApiOperation(value="xxx接口",notes = "这是notes描述",httpMethod = "GET--请求方式")
注意事项
//这些注解用于解决跨域访问的问题
@RestController
@CrossOrigin
//web.xml文件中若没有以下配置要加上
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 匹配所有请求,此处也可以配置成 *.do 形式 -->
<!--/*.do是对所有以.do结尾的请求做处理,/*是对所有请求做处理-->
<url-pattern>/</url-pattern>
</servlet-mapping>
效果图