拦截器:
package com.beagledata.gaea.securitydoc;
import com.beagledata.gaea.securitydoc.interceptor.AuthcInterceptor;
import com.beagledata.gaea.securitydoc.interceptor.TokenInterceptor;
import com.thetransactioncompany.cors.CORSFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
-
Created by liulu on 2018/8/13.
*/
@Configuration
public class DefaultWebMvcConfigurerAdapter extends WebMvcConfigurerAdapter {
@Bean
TokenInterceptor getTokenInterceptorBean() {
return new TokenInterceptor();
}@Bean
AuthcInterceptor getAuthcInterceptorBean() {
return new AuthcInterceptor();
}@Bean
public FilterRegistrationBean corsFilterBean() {
Map<String, String> properties = new HashMap<String, String>();
properties.put(“cors.allowGenericHttpRequests”, “true”);
properties.put(“cors.allowOrigin”, “");
properties.put(“cors.allowSubdomains”, “false”);
properties.put(“cors.supportedMethods”, “GET, HEAD, POST, OPTIONS”);
properties.put(“cors.supportedHeaders”, “Accept, Origin, X-Requested-With, token, Content-Type, Last-Modified, Authorization”);
properties.put(“cors.supportsCredentials”, “true”);
properties.put(“cors.maxAge”, “3600”);
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
filterRegistrationBean.setFilter(new CORSFilter());
filterRegistrationBean.setInitParameters(properties);
filterRegistrationBean.setName(“CORS”);
filterRegistrationBean.setUrlPatterns(Collections.singletonList("/”));
return filterRegistrationBean;
}@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(getTokenInterceptorBean())
.addPathPatterns(
“/"
).excludePathPatterns(
"/login/”
);registry.addInterceptor(getAuthcInterceptorBean()) .addPathPatterns( "/user/**" );
}
}
package com.beagledata.gaea.securitydoc.interceptor;
import com.beagledata.gaea.securitydoc.common.SessionHolder;
import com.beagledata.gaea.securitydoc.exception.ForbiddenException;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
-
校验是否授权登录
-
Created by liulu on 2018/8/16.
*/
public class AuthcInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
if (SessionHolder.currentUserId() > 0) {
return true;
}
throw new ForbiddenException();
}@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 {}
}
package com.beagledata.gaea.securitydoc.interceptor;
import com.beagledata.gaea.securitydoc.common.Constants;
import com.beagledata.gaea.securitydoc.common.SessionHolder;
import com.beagledata.gaea.securitydoc.entity.User;
import com.beagledata.gaea.securitydoc.exception.UnauthorizedException;
import com.beagledata.gaea.securitydoc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
-
判断用户是否存在
-
-
Created by liulu on 2018/8/13.
*/
public class TokenInterceptor implements HandlerInterceptor {
@Autowired
private RedisTemplate sessionRedisTemplate;
@Autowired
private UserService userService;/**
- @Author: mahongfei
- @description: 判断用户是否存在
*/
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
String JWTToken = httpServletRequest.getHeader(Constants.TOKEN_HEADER_NAME);
if (null != JWTToken) {
try {
HashOperations ops = sessionRedisTemplate.opsForHash();
User user = (User) ops.get(userService.decodeJWTToken(JWTToken).getUserid(), “loginUser”);
if (null != user) {
SessionHolder.remove();
SessionHolder.set(user);
return true;
}
} catch (Exception e) {
throw new UnauthorizedException();
}
}
throw new UnauthorizedException();
}
@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 {}
}
异常类
package com.beagledata.gaea.securitydoc.exception;
/**
- access_token校验异常
- Created by liulu on 2018/8/10.
*/
public class UnauthorizedException extends RuntimeException {
}
package com.beagledata.gaea.securitydoc.exception;
/**
- access_token校验异常
- Created by liulu on 2018/8/10.
*/
public class UnauthorizedException extends RuntimeException {
}
package com.beagledata.gaea.securitydoc;
import com.beagledata.gaea.securitydoc.common.Result;
import com.beagledata.gaea.securitydoc.exception.ForbiddenException;
import com.beagledata.gaea.securitydoc.exception.UnauthorizedException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
-
Created by liulu on 2017/12/19.
*/
@ControllerAdvice
public class WebExceptionHandler {
private Logger logger = LoggerFactory.getLogger(this.getClass());/**
- 未知异常
- @author liulu
- 2018/1/11 9:57
*/
@ExceptionHandler(Exception.class)
@ResponseBody
public Result exceptionHandler(Exception e) {
logger.error(e.getLocalizedMessage(), e);
return Result.newError().withMsg(“系统繁忙,请稍候再试”);
}
/**
- 请求方法错误异常
- @author liulu
- 2018/1/11 9:56
*/
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
@ResponseBody
public Result httpRequestMethodNotSupportedExceptionHandler(HttpRequestMethodNotSupportedException e) {
String[] supportedMethods = e.getSupportedMethods();
if (supportedMethods != null && supportedMethods.length > 0) {
return Result.newError()
.withCode(HttpStatus.METHOD_NOT_ALLOWED.value())
.withMsg(“请使用” + supportedMethods[0] + “请求”);
}
return Result.newError().withCode(HttpStatus.METHOD_NOT_ALLOWED.value()).withMsg(“不支持当前请求方法”);
}
/**
- 业务错误异常
- @author liulu
- 2018/1/11 9:56
*/
@ExceptionHandler({
IllegalArgumentException.class,
IllegalStateException.class
})
@ResponseBody
public Result illegalExceptionHandler(Exception e) {
return Result.newError().withMsg(e.getMessage());
}
/**
- 前端参数校验异常
- @author liulu
- 2018/1/11 9:56
*/
@ExceptionHandler(BindException.class)
@ResponseBody
public Result bindExceptionHandler() {
return Result.newError().withMsg(“参数校验出错,请检查参数”);
}
/**
- 未授权登录
- @author liulu
- 2018/1/11 9:56
*/
@ExceptionHandler(ForbiddenException.class)
@ResponseBody
public Result forbiddenExceptionHandler() {
return Result.newError().withCode(Result.CODE_FORBIDDEN);
}
/**
- access_token校验失败
- @author liulu
- 2018/1/11 9:56
*/
@ExceptionHandler(UnauthorizedException.class)
@ResponseBody
public Result unauthorizedExceptionHandler() {
return Result.newError().withCode(Result.CODE_UNAUTHORIZED);
}
}
使用前需要与前端定义接口凭证和返回码
/**
* 用户未授权登录
/
public static final int CODE_FORBIDDEN = 403;
/*
* 用户未登录
/
public static final int CODE_UNAUTHORIZED = 401;
/*
* 请求接口凭证头部
*/
public static final String TOKEN_HEADER_NAME = “token”;
redis的相关依赖:
org.springframework.session
spring-session
org.springframework.boot
spring-boot-starter-data-redis