以下内容主要是:使用注解+session+拦截器+跨域处理
一 新增注解@UserLoginToken
@Retention(RetentionPolicy.RUNTIME)
public @interface UserLoginToken {
boolean required() default true;
}
二 增加拦截器
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
// 如果不是映射到方法直接通过
if (!(object instanceof HandlerMethod)) {
return true;
}
HandlerMethod handlerMethod = (HandlerMethod) object;
Method method = handlerMethod.getMethod();
//检查有没有需要用户权限的注解
if (method.isAnnotationPresent(UserLoginToken.class)) {
UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
if (userLoginToken.required()) {
HttpSession session = httpServletRequest.getSession();
if (session.getAttribute(session.getId()) != null) {
User user = (User) session.getAttribute(session.getId());
//判断用户是否冻结,如果冻结限制登陆
if (user != null) {
if(request.getSession().getAttribute("user_login") == null){
response.setContentType("application/json;charset=utf-8");
PrintWriter out = response.getWriter();
out.write(JSON.toJSONString(ResultBean.E401));
return false;
}
}
return true;
}
throw new RuntimeException("PLEASELOGIN");
}
}
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
三:将拦截器注入容器中
public class InterceptorConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(authenticationInterceptor())
.addPathPatterns("/**"); // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
}
@Bean
public AuthenticationInterceptor authenticationInterceptor() {
return new AuthenticationInterceptor();
}
四:登录接口登录后增加session
public Object login(@RequestBody UserInfo userInfo, HttpServletRequest request) {
// 业务逻辑
request.getSession().setAttribute(request.getSession().getId(), userInfo);
}
五:在需要登录后才能访问的api接口添加注解@UserLoginToken 如:
@PostMapping("/transfer")
public MessageVO addAgent(){
// 业务逻辑
}
六:后端增加跨域处理
public class CorsConfig {
@Bean
public WebMvcConfigurer corsConfigurer() {
return new WebMvcConfigurer() {
@Override
//重写父类提供的跨域请求处理的接口
public void addCorsMappings(CorsRegistry registry) {
//添加映射路径
registry.addMapping("/**")
//放行哪些原始域
.allowedOrigins("*")
//是否发送Cookie信息
.allowCredentials(true)
//放行哪些原始域(请求方式)
.allowedMethods("GET", "POST", "PUT", "DELETE")
//放行哪些原始域(头部信息)
.allowedHeaders("*")
//暴露哪些头部信息(因为跨域访问默认不能获取全部头部信息)
.exposedHeaders("token");
}
};
}
}
七:前端ajax 请求时需要添加:
xhrFields: {withCredentials: true},
crossDomain: true,
以上步骤可以实现单个服务器下用户对接口访问的权限校验和跨域问题的解决
喜欢的朋友可以关注下哦~