SpringBoot 整合security 实现自定义Token和clientId登录及退出(三)
代码写好了,我们可以来测试一下写得是否满足我们的需求
测试工具:postman
在登录接口,输入用户名和密码
发送请求
获得用户返回的信息
数据库user_token 新增一条数据(这里就不截图了)
在新建一个请求
@RestController
@RequestMapping(value = "api")
@SuppressWarnings("all")
public class UserController {
@Autowired
private UserService userService;
@ResponseBody
@PostMapping(value = "selectAll")
public ResultData selectUser() {
List<UserInfo> userInfos = userService.selectAll();
ResultData resultData = new ResultData();
resultData.setCode(1);
resultData.setMsg("sucess");
resultData.setData(userInfos);
return resultData;
}
}
发送请求
在headers 加上登录的clientId 和 accessToken
成功查询到数据
最后再创建个退出登录的处理
package com.example.demo.base.common;
import com.example.demo.base.dto.ResultData;
import com.example.demo.base.dto.UserDetailsInfo;
import com.example.demo.base.service.TokenService;
import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 用户退出登录处理
*/
@Component
@SuppressWarnings("all")
public class DemoLogoutSuccessHandler implements LogoutSuccessHandler {
@Autowired
private TokenService tokenService;
@Override
public void onLogoutSuccess(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
Authentication authentication) throws IOException, ServletException {
Gson gson = new Gson();
ResultData resultData = new ResultData(1, "logout successful", null);
if (authentication != null && authentication.getPrincipal() != null) {
String clientId = httpServletRequest.getHeader("clientId");
// 删除Token
tokenService.deleteToken(clientId);
}
httpServletResponse.getWriter().write(gson.toJson(resultData));
}
}
退出登录
使用token再访问时,就会失败