使用异步注解调用远程接口Spring Security认证授权不携带Token的问题

项目中开启异步注解@EnableAsync

项目中使用异步注解:@Async

在远程调用时需要携带授权信息,如果不配置特定的线程池,系统使用默认的异步线程池,无法传递授权信息,需要在项目中配置:

@Component
public class AsyncConfig extends AsyncConfigurerSupport {

    /**
     * 异步执行需要使用权限框架自带的包装线程池  保证权限信息的传递
     */
    @Override
    public Executor getAsyncExecutor() {
        int processors = Runtime.getRuntime().availableProcessors();
        ExecutorService executorService = new ThreadPoolExecutor(processors, processors << 1,
                5000L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<>(),
                new NamedThreadFactory("async-security-pool-", false));
        return new DelegatingSecurityContextExecutorService(executorService);
    }
}

同样项目中如果使用线程池调用远程接口,需要使用DelegatingSecurityContextExecutorService线程池。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Security提供了多种身份验证(authentication)方式,其中包括token和基于表单的登录方式。 对于基于表单的登录方式,你可以使用Spring Security提供的loginPage()方法配置登录页。在该登录页中,用户可以输入用户名和密码进行身份验证。Spring Security会将这些信息封装成一个Authentication对象,并调用AuthenticationManager进行身份验证。 如果身份验证成功,Spring Security会创建一个Authentication对象并将其存储在SecurityContextHolder中。此时,用户已经成功登录。你可以通过在控制器方法中使用@AuthenticationPrincipal注解来获取已经登录的用户信息。 下面是一个基于表单的登录示例: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/", "/home").permitAll() .anyRequest().authenticated() .and() .formLogin() .loginPage("/login") .permitAll() .and() .logout() .permitAll(); } @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth .inMemoryAuthentication() .withUser("user").password("{noop}password").roles("USER"); } } ``` 在上述示例中,我们使用了基于内存的身份验证,在内存中保存了一个用户名为user,密码为password的用户。当用户访问需要身份验证的资源时,Spring Security会自动跳转到/login页面,用户可以在该页面中输入用户名和密码进行身份验证。 如果你需要使用其他的身份验证方式,你可以参考Spring Security的官方文档进行配置。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值