Designing an Open API Interface with Token Generation and Interceptor in Spring Boot
This article describes how to design an open API interface that issues time‑limited access tokens, defines the supporting database schema, implements token generation utilities, creates a token‑issuing endpoint, and secures all open‑API calls with a Spring MVC interceptor.
First, the article explains the design of an open API interface where each partner organization receives an appid , app_secret , and a generated access_token valid for two hours, which must be passed with API calls.
It then presents the core database table m_app with fields such as app_name , app_id , app_secret , is_flag , and access_token , and provides the full CREATE TABLE statement.
CREATE TABLE `m_app` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`app_name` varchar(255) DEFAULT NULL,
`app_id` varchar(255) DEFAULT NULL,
`app_secret` varchar(255) DEFAULT NULL,
`is_flag` varchar(255) DEFAULT NULL,
`access_token` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;Next, a utility class TokenUtils is shown, offering a static method getAccessToken() that returns a UUID‑based token without hyphens.
public class TokenUtils {
@RequestMapping("/getToken")
public static String getAccessToken() {
return UUID.randomUUID().toString().replace("-", "");
}
}The AuthController defines the /getAccessToken endpoint. It validates the supplied appid / appSecret , checks the merchant’s permission flag, removes any previous token from Redis, generates a new token via TokenUtils , stores it in Redis with a two‑hour TTL, updates the database, and returns the token as JSON.
@RestController
@RequestMapping(value = "/auth")
public class AuthController extends BaseApiService {
@Autowired
private BaseRedisService baseRedisService;
@Autowired
private AppMapper appMapper;
private long timeToken = 60 * 60 * 2;
@RequestMapping("/getAccessToken")
public ResponseBase getAccessToken(AppEntity appEntity) {
AppEntity appResult = appMapper.findApp(appEntity);
if (appResult == null) {
return setResultError("没有对应机构的认证信息");
}
int isFlag = appResult.getIsFlag();
if (isFlag == 1) {
return setResultError("您现在没有权限生成对应的AccessToken");
}
baseRedisService.delKey(appResult.getAccessToken());
String newAccessToken = newAccessToken(appResult.getAppId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("accessToken", newAccessToken);
return setResultSuccessData(jsonObject);
}
private String newAccessToken(String appId) {
String accessToken = TokenUtils.getAccessToken();
baseRedisService.setString(accessToken, appId, timeToken);
appMapper.updateAccessToken(accessToken, appId);
return accessToken;
}
}An AccessTokenInterceptor is introduced to intercept all requests under /openApi/* . It extracts the accessToken parameter, verifies its existence in Redis, and rejects the request with an error message if the token is missing or invalid.
@Component
public class AccessTokenInterceptor extends BaseApiService implements HandlerInterceptor {
@Autowired
private BaseRedisService baseRedisService;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String accessToken = request.getParameter("accessToken");
if (StringUtils.isEmpty(accessToken)) {
resultError(" this is parameter accessToken null ", response);
return false;
}
String appId = (String) baseRedisService.getString(accessToken);
if (StringUtils.isEmpty(appId)) {
resultError(" this is accessToken Invalid ", response);
return false;
}
return true;
}
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}
public void resultError(String errorMsg, HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
writer.write(new JSONObject().toJSONString(setResultError(errorMsg)));
}
}Finally, a Spring configuration class WebAppConfig registers the interceptor, ensuring that every open‑API call is subject to the token validation logic.
@Configuration
public class WebAppConfig {
@Autowired
private AccessTokenInterceptor accessTokenInterceptor;
@Bean
public WebMvcConfigurer WebMvcConfigurer() {
return new WebMvcConfigurer() {
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(accessTokenInterceptor).addPathPatterns("/openApi/*");
}
};
}
}Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.