JWT权限校验小案例SpringBoot+JWT+Redis(轮子拿来用就行)

登录流程图
JWT权限校验小案例SpringBoot+JWT+Redis(轮子拿来用就行)_第1张图片
校验流程图
JWT权限校验小案例SpringBoot+JWT+Redis(轮子拿来用就行)_第2张图片
工具类太多了,可去码云上直接cv下来,防止重复造轮子
码云地址:https://gitee.com/ther661/jwt

yml配置和启动类

server:
  port: 8080
spring:
  redis:
    host: -------------
    port: 6379
    password: ---------
  main:
    allow-bean-definition-overriding: true

@SpringBootApplication
public class JwtApplication {
    public static void main(String[] args) {
        SpringApplication.run(JwtApplication.class,args);
    }
}

1.config(配置类:跨域,redis集成)

@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter implements ApplicationContextAware {


    private ApplicationContext applicationContext;

    public WebMvcConfig() {
        super();
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        super.addResourceHandlers(registry);
    }


    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);
        return new CorsWebFilter(source);
    }


    @Bean
    LoginInterceptor loginInterceptor() {
        return new LoginInterceptor();
    }


    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //拦截规则:除了login,其他都拦截判断
        registry.addInterceptor(loginInterceptor())
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login");

        super.addInterceptors(registry);
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }
}

redis

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        return redisTemplate;
    }
}
拦截器

```java
@Slf4j
@Component
public class LoginInterceptor extends HandlerInterceptorAdapter {


    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        String requestURI = request.getRequestURI();
        log.info("requestURI:{}",requestURI);

        if (StringUtils.isEmpty(token)) {
            throw new ServiceException(ResultCodeEnum.AUTH_FAIL);
        }

        Claims claim = JWTUtils.getClaim(token);
        if(claim == null){
            throw new ServiceException(ResultCodeEnum.AUTH_FAIL);
        }

        String uid = null;
        try {
            uid = JWTUtils.getOpenId(token);
        } catch (Exception e) {
            throw new ServiceException(ResultCodeEnum.AUTH_FAIL);
        }

        //用户id放到上下文 可以当前请求进行传递
        request.setAttribute(SessionContext.USER_ID_KEY, uid);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
2.controller(登录)

```java
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController extends BaseController {

    @Autowired
    private UserService userService;

    /**
     * 登陆
     *
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public UserVO login(@RequestBody LoginDTO loginDTO) {
        return userService.login(loginDTO);
    }

    /**
     * 接口测试
     *
     * @return
     */
    @GetMapping("/test")
    public String test() {
        log.info("测试当前访问用户为:{}", getUser());
        return "success";
    }
}

校验

public class BaseController {

    @Autowired
    private SessionContext sessionContext;

    public UserVO getUser() {
        return sessionContext.getUser();
    }
}

3.domain(entity,dto,vo,返回的json-Result)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    /**
     * 用户id
     */
    private String uid;
    /**
     * 用户名
     */
    private String name;
    /**
     * 密码
     */
    private String pwd;
}
@Data
public class LoginDTO {

    private String userName;

    private String pwd;


}

@Data
public class UserVO implements Serializable {

    private static final long serialVersionUID = 1L;

    private String uid;

    private String name;

    private String token;
}

Result

public class ApiResult<T> {
    private Integer code;
    private String msg;
    private String version;
    private T data;

    private ApiResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private ApiResult(ResultCodeEnum ResultCodeEnum) {
        if (ResultCodeEnum != null) {
            this.code = ResultCodeEnum.getCode();
            this.msg = ResultCodeEnum.getMsg();
        }

    }

    private ApiResult(T data, String version) {
        this.code = ResultCodeEnum.SUCCESS.getCode();
        this.msg = ResultCodeEnum.SUCCESS.getMsg();
        this.version = version;
        this.data = data;
    }


    public static <T> ApiResult<T> success(T data, String version) {
        return new ApiResult(data, version);
    }

    public static <T> ApiResult<T> success(Map<Object, String> obj) {
        return new ApiResult(obj.get("data"), (String)obj.get("version"));
    }

    public static <T> ApiResult<T> success() {
        return new ApiResult(ResultCodeEnum.SUCCESS);
    }

    public static <T> ApiResult<T> success(Integer code, String msg) {
        return new ApiResult(code, msg);
    }

    public static <T> ApiResult<T> error(ResultCodeEnum ResultCodeEnum) {
        return new ApiResult(ResultCodeEnum);
    }

    public static <T> ApiResult<T> error(Integer code, String msg) {
        return new ApiResult(code, msg);
    }

    public Integer getCode() {
        return this.code;
    }

    public String getMsg() {
        return this.msg;
    }

    public String getVersion() {
        return this.version;
    }

    public T getData() {
        return this.data;
    }

    public void setCode(final Integer code) {
        this.code = code;
    }

    public void setMsg(final String msg) {
        this.msg = msg;
    }

    public void setVersion(final String version) {
        this.version = version;
    }

    public void setData(final T data) {
        this.data = data;
    }

    @Override
    public boolean equals(final Object o) {
        if (o == this) {
            return true;
        } else if (!(o instanceof ApiResult)) {
            return false;
        } else {
            ApiResult<?> other = (ApiResult)o;
            if (!other.canEqual(this)) {
                return false;
            } else {
                label59: {
                    Object this$code = this.getCode();
                    Object other$code = other.getCode();
                    if (this$code == null) {
                        if (other$code == null) {
                            break label59;
                        }
                    } else if (this$code.equals(other$code)) {
                        break label59;
                    }

                    return false;
                }

                Object this$msg = this.getMsg();
                Object other$msg = other.getMsg();
                if (this$msg == null) {
                    if (other$msg != null) {
                        return false;
                    }
                } else if (!this$msg.equals(other$msg)) {
                    return false;
                }

                Object this$version = this.getVersion();
                Object other$version = other.getVersion();
                if (this$version == null) {
                    if (other$version != null) {
                        return false;
                    }
                } else if (!this$version.equals(other$version)) {
                    return false;
                }

                Object this$data = this.getData();
                Object other$data = other.getData();
                if (this$data == null) {
                    if (other$data != null) {
                        return false;
                    }
                } else if (!this$data.equals(other$data)) {
                    return false;
                }

                return true;
            }
        }
    }

    protected boolean canEqual(final Object other) {
        return other instanceof ApiResult;
    }


    @Override
    public String toString() {
        return "ApiResult(code=" + this.getCode() + ", msg=" + this.getMsg() + ", version=" + this.getVersion() + ", data=" + this.getData() + ")";
    }

    public ApiResult() {
    }

4.server层

@Service
public class UserService {
    @Value("${server.session.timeout:3000}")
    private Long timeout;

    @Autowired
    private RedisUtils redisUtils;

    final static String USER_NAME = "admin";

    //密码 演示用就不做加密处理了
    final static String PWD = "admin";


    public UserVO login(LoginDTO loginDTO) {

        User user = getByName(loginDTO.getUserName());

        //用户信息校验和查询
        if (user == null) {
            throw new ServiceException(ResultCodeEnum.LOGIN_FAIL);
        }
        //密码校验
        if (!PWD.equals(loginDTO.getPwd())) {
            throw new ServiceException(ResultCodeEnum.LOGIN_FAIL);
        }

        //缓存用户信息并设置过期时间
        UserVO userVO = new UserVO();
        userVO.setName(user.getName());
        userVO.setUid(user.getUid());
        userVO.setToken(JWTUtils.generate(user.getUid()));

        //信息入库redis
        redisUtils.set(RedisKeyEnum.OAUTH_APP_TOKEN.keyBuilder(userVO.getUid()), JSONObject.toJSONString(userVO), timeout);

        return userVO;
    }

    /**
     * 通过用户名获取用户
     *
     * @param name
     * @return
     */
    public User getByName(String name) {
        User user = null;
        if (USER_NAME.equals(name)) {
            user = new User("1", "张三", "Aa123456");
        }
        return user;
    }

}

你可能感兴趣的:(jwt校验)