<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.3.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
- 拦截器配置类AuthInterceptorConfig.java
@Configuration
public class AuthInterceptorConfig implements WebMvcConfigurer {
@Bean
public AuthInterceptor initAuthInterceptor() {
return new AuthInterceptor();
}
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(initAuthInterceptor())
.addPathPatterns("/user/**")
.excludePathPatterns("/login/**");
}
}
- 拦截器实现类AuthInterceptor.java
public class AuthInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
HandlerMethod handlerMethod = (HandlerMethod) handler;
Authorized authorized = handlerMethod.getMethodAnnotation(Authorized.class);
if (authorized == null) {
authorized = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Authorized.class);
}
if (authorized != null) {
return isAuthorized(request, response);
}
return true;
}
private boolean isAuthorized(HttpServletRequest request, HttpServletResponse response) {
JSONObject userJSON = (JSONObject) request.getSession().getAttribute("LOGIN_USER");
if (userJSON != null) {
return true;
}
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8;");
try (PrintWriter writer = response.getWriter()) {
writer.print("通过鉴权");
return false;
} catch (IOException e) {
return false;
}
}
}
- 注解类Authorized.java通过@Authorized实现拦截
@Documented
@Inherited
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Authorized {
}
@Authorized
@GetMapping("/user/**")
public void user***() {
...
}
@PostMapping("/login/***")
public String login***(HttpSession session) {
...
session.setAttribute("LOGIN_USER", 缓存数据);
...
return "登录成功";
}