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 一切正常

原文地址:https://www.cnblogs.com/timseng/p/12021725.html

时间: 2024-08-30 15:29:32

Springboot 使用Jwt token失效时接口无响应(乌龙)的相关文章

使用Loadrunner 录制脚本时程序无响应

解决方法: step1:IE 设置-Internet 选项-高级-启用第三方浏览器扩展-去掉该选项 step2:右键我的电脑-属性-高级系统设置-性能-设置-数据执行保护-选中第二项,然后添加iexplore.exe和vugen.exe 参考路径: C:\Program Files\Internet Explorer\iexplore.exe D:\Program Files\HP\LoadRunner\bin\vugen.exe step3:重启电脑,再进行录制 本人遇到这个问题的时候通过上面

SpringBoot集成JWT实现token验证

原文:https://www.jianshu.com/p/e88d3f8151db JWT官网: https://jwt.io/ JWT(Java版)的github地址:https://github.com/jwtk/jjwt 什么是JWT Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).定义了一种简洁的,自包含的方法用于通信双方之间以JSON对象的形式安全的传递信息.因为数字签名的存在,这些信息是可信的,JWT

实战SpringBoot集成JWT实现token验证

作者:意识流丶 www.jianshu.com/p/e88d3f8151db JWT官网:https://jwt.io/ JWT(Java版)的github地址:https://github.com/jwtk/jjwt 什么是JWT Json web token (JWT), 是为了在网络应用环境间传递声明而执行的一种基于JSON的开放标准((RFC 7519).定义了一种简洁的,自包含的方法用于通信双方之间以JSON对象的形式安全的传递信息.因为数字签名的存在,这些信息是可信的,JWT可以使用

一个失误导致微信下载图片接口Token失效

公司的应用调了一个微信上传下载图片的接口,本来在线上跑的好好的,什么问题没有,但是这两天总是不定时的出现下载下来的图片损坏,拿着Token和serverid去接口测试网页验证,返回的是Token失效了,返回信息:"errcode": 40001, "errmsg": "invalid credential, access_token is invalid or not latest hint: [17ZG50664ent3].我是把Token和ticket

springboot之Jwt验证

简介 什么是JWT(Json Web Token) jwt是为了在网络应用环境间传递声明而执行的一种基于json的开放标准.该token被设计紧凑且安全的,特别适用于SSO场景. jwt的声明一般被用来在身份提供者和服务提供者之间传递被认证的用户身份信息. JWT长什么样 eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJ0ZXN0MDAyIiwiZXhwIjoxNTEwOTcwMjU4fQ._FOqy5l44hODu3DjXh762LNUTLNQH15fdCUerdseDpmSK

IdentityServer4实战 - 谈谈 JWT Token 的安全策略

一.前言 众所周知,IdentityServer4 默认支持两种类型的 Token,一种是 Reference Token,一种是 JWT Token .前者的特点是 Token 的有效与否是由 Token 颁发服务集中化控制的,颁发的时候会持久化 Token,然后每次验证都需要将 Token 传递到颁发服务进行验证,是一种中心化的比较传统的验证方式.JWT Token 的特点与前者相反,每个资源服务不需要每次都要都去颁发服务进行验证 Token 的有效性验证,该 Token 由三部分组成,其中

memcached缓存失效时的高并发访问问题解决

memcached一般用于在访问一些性能相对低下的数据接口时(如数据库),为了保证这些数据接口的稳定性,加上memcached以减少访问次数,保证这些数据接口的健壮性.一般memcached的数据都是定时失效的,当数据失效时一般会再次去访问取数据接口,然后将其更新至memcached中.这时就会有一个问题,当某个数据失效时,恰好同时有大量的客户端访问该数据,这时这些客户端都会发现该数据失效,然后都会去调用数据接口去取数据更新,这自然就瞬间地使数据接口失去了memcached的保护,有可能造成系统

SpringBoot中如何灵活的实现接口数据的加解密功能?

数据是企业的第四张名片,企业级开发中少不了数据的加密传输,所以本文介绍下SpringBoot中接口数据加密.解密的方式. 本文目录 一.加密方案介绍二.实现原理三.实战四.测试五.踩到的坑 一.加密方案介绍 对接口的加密解密操作主要有下面两种方式: 自定义消息转换器 优势:仅需实现接口,配置简单.劣势:仅能对同一类型的MediaType进行加解密操作,不灵活. 使用spring提供的接口RequestBodyAdvice和ResponseBodyAdvice 优势:可以按照请求的Referrer

PHP JWT token实现

原文链接:https://www.jb51.net/article/146790.htm 机制: 代码如下: <?php /**  * PHP实现jwt  */ class Jwt {   //头部   private static $header=array(     'alg'=>'HS256', //生成signature的算法     'typ'=>'JWT'  //类型   );   //使用HMAC生成信息摘要时所使用的密钥   private static $key='12