• Springboot 使用Jwt token失效时接口无响应(乌龙)


    问题背景:新项目使用Springboot框架,鉴权使用了Jwt

    处理cors:

    @Configuration
    public class WebMvcConfig implements WebMvcConfigurer {
    
        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedHeaders("*")
                    .allowedMethods("*")
                    .allowedOrigins("*")
                    .allowCredentials(true);
        }
    }

    使用自定义Jwt鉴权:

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        JwtAuthenticationEntryPoint unauthorizedHandler;
        @Autowired
        RestAuthenticationAccessDeniedHandler accessDeniedHandler;
        @Autowired
        CustomUserDetailsServiceImpl CustomUserDetailsService;
        @Autowired
        JwtAuthenticationTokenFilter authenticationTokenFilter;
        @Autowired
        private MyPermissionEvaluator myPermissionEvaluator;
    
    
    
        @Autowired
        public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
            authenticationManagerBuilder
                    // 设置UserDetailsService
                    .userDetailsService(CustomUserDetailsService)
                    // 使用BCrypt进行密码的hash
                    .passwordEncoder(passwordEncoder());
        }
    
        /**
         * 装载BCrypt密码编码器
         * @return
         */
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    
        @Override
        protected void configure(HttpSecurity httpSecurity) throws Exception {
            httpSecurity
                    .exceptionHandling().accessDeniedHandler(accessDeniedHandler).and()
                    .cors().and()//乌龙在这行,一开始没有配置这个 
    //如果您使用的是Spring Security,请确保在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置。
    //乌龙在这行,一开始没有配置这个 //乌龙在这行,一开始没有配置这个 // 由于使用的是JWT,我们这里不需要csrf .csrf().disable() .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and() // 基于token,所以不需要session .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .authorizeRequests() // 对于获取token的rest api要允许匿名访问 .antMatchers("/admin/login", "/admin/register","/error/**").permitAll() // 除上面外的所有请求全部需要鉴权认证 .anyRequest().authenticated(); // 禁用缓存 httpSecurity.headers().cacheControl(); // 添加JWT filter httpSecurity .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class); } @Override public void configure(WebSecurity web) { web .ignoring().antMatchers(HttpMethod.OPTIONS, "/**").and() .ignoring() .antMatchers( "/favicon.ico", "/**/*.css", "/**/*.js", "/**/*.png", "/**/*.gif", "/**/*.ttf" ); } @Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); } /** * 注入自定义PermissionEvaluator */ @Bean public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler(){ DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler(); handler.setPermissionEvaluator(myPermissionEvaluator); return handler; } }

    然后就出问题了:登录后使用token Jwt鉴权正常,前端跨域正常,但是当token失效后接口200 但是拿不到数据

    这个样子 This request has no response data available

    用postman请求正常:报token失效

    由于之前解决了跨域问题就没考虑跨域,怀疑的方向是Jwt拦截后没有处理返回或者dochain断掉了

    后来看了下浏览器的console发现token失效后出现了跨域问题,

    搜索发现security配置里少了一个配置:.cors().and()

    如果使用的是Spring Security,请确保在Spring Security级别启用CORS,以允许它利用Spring MVC级别定义的配置。

    好吧,security没有启用cors

    fixed 一切正常

  • 相关阅读:
    基于requirejs和oclazyloadjs的实际按需加载的angular项目
    vue源码解析data与watcher
    video标签播放数据调整
    ngnix搭建前端服务
    面试总结篇(一)
    mongodb的安装、配置、启动、数据库密码的配置;
    今天随手写个发布订阅的 event.js
    Mac OS系统使用的链接,以及关于前端软件的安装(持续更新)
    bind 以及原型 1px边框的实现(面试后内容整理)
    flexbox的学习,display:flex display:box 淘宝触屏版、饿了么网布局分析分析
  • 原文地址:https://www.cnblogs.com/timseng/p/12021725.html
Copyright © 2020-2023  润新知