1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > Springboot自定义注解实现用户登录状态校验(一)

Springboot自定义注解实现用户登录状态校验(一)

时间:2024-03-01 14:51:13

相关推荐

Springboot自定义注解实现用户登录状态校验(一)

Springboot自定义注解实现用户登录状态校验(一)

拦截器方式

定义注解类

import java.lang.annotation.*;/*** @author:小飞猪* @date:/12/1 21:31* @version:1.0* @description:登录权限校验注解*/@Target({ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)@Inherited@Documentedpublic @interface LoginCheck {/*** 方法描述* @return*/String description() default "";/*** 方法是否必须校验* @return*/boolean required() default true;/*** 方法权限描述(这里可以考虑整一个权限枚举,比较方便)* @return*/String value() default "";}

实现拦截器拦截权限注解

import com.tobu.funnykits.annotions.LoginCheck;import com.tobu.funnykits.core.domain.entity.UserInfo;import org.springframework.http.HttpStatus;import org.springframework.web.method.HandlerMethod;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.time.LocalDateTime;/*** @author:小飞猪* @date:/12/1 21:25* @version:1.0* @description:登录拦截器(拦截器方式)*/public class LoginInterceptor implements HandlerInterceptor {@Overridepublic boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {// 验证权限if (this.hasPermission(request, handler)) {return true;}// 如果没有权限 则抛403异常 springboot会处理,跳转到 /error/403 页面response.sendError(HttpStatus.FORBIDDEN.value(), "对不起,无目标方法的访问权限");return false;}/*** 判断权限** @param handler* @return*/private boolean hasPermission(HttpServletRequest request, Object handler) {System.out.println("进入权限校验===========,当前时间:"+LocalDateTime.now());if (handler instanceof HandlerMethod) {HandlerMethod handlerMethod = (HandlerMethod) handler;//获取方法上的注解LoginCheck loginCheck = handlerMethod.getMethod().getAnnotation(LoginCheck.class);//情况1:方法未被注解修饰,则直接返回无权限if (loginCheck == null) {return false;}//情况2:方法被注解修饰不是必须校验类型,则返回正常if (loginCheck.required() == Boolean.FALSE) {return true;}//判断登录用户状况/*** 实现方式参考:从seesion中获取用户身份令牌并验证:当用户成功登录时创建随机加密的身份令牌,(key:身份*令牌,value:登录名)存储到Redis中并配置自定义的失效时间,同时放入到全局session。当进行权限校验时,*从全局session中获取到令牌,将获取到的令牌到redis中匹配是否存在,从而达到用户登录状态判断的目的*///判断用户是否登录Object loginToken = request.getSession().getAttribute("LOGIN_TOKEN");if (loginToken == null) {return false;}else{if(redisTemplate.hasKey(loginToken.toString())){//存在Key,可以进一步匹配Value}else{return false;}}//获取该用户的相关信息,并判断是否有权限Object loginUserObj = request.getSession().getAttribute("LOGIN_USER");UserInfo userInfo = (UserInfo)loginUserObj;String permission = userInfo.getPermission();if (permissionSet.isEmpty()) {return false;}//获取注解上的value值(也就是该方法的允许权限类型)return permission.equals(handlerMethod.getMethod().getDeclaringClass().getName()+"."+controllerMethodPermissionStr);}return true;}@Overridepublic void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}@Overridepublic void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {}}

注册拦截器

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.WebMvcConfigurer;/*** @author:小飞猪* @date:/12/1 21:52* @version:1.0* @description:注册权限拦截器*/@Configurationpublic class PermissionConfig implements WebMvcConfigurer {@Beanpublic LoginInterceptor loginInterceptor() {return new LoginInterceptor();}@Overridepublic void addInterceptors(InterceptorRegistry registry) {registry.addInterceptor(loginInterceptor()).excludePathPatterns("/static/*").excludePathPatterns("/error").addPathPatterns("/**");}}

demo

/*** 获取随机密码* @return*/@GetMapping("/getRandomPassword")@LoginCheck(description = "获取随机密码",required = true,value = "GET")public String getRandomPassword(){return randomPassWordService.getRandomPassWord();}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。