相关疑难解决方法(0)

Spring Security和@Async(经过身份验证的用户混淆)

我使用@Async异步调用Spring方法.该方法调用其他使用@PreAuthorize,Spring Security Annotation注释的方法.要使授权工作,我必须将SecurityContextHolder模式设置为MODE_INHERITABLETHREADLOCAL,以便将身份验证信息传递给异步调用.到目前为止一切正常.

但是,当我以不同的用户身份注销和登录时,在异步方法中,SecurityContextHolder会存储已注销的旧用户的身份验证信息.它当然会引起不必要的AccessDenied异常.同步调用没有这样的问题.

我已定义<task:executor id="executors" pool-size="10"/>,所以可能是一个问题,一旦执行程序池中的线程已初始化,它将不会覆盖身份验证信息?

spring asynchronous spring-security

33
推荐指数
5
解决办法
1万
查看次数

如何在异步任务执行程序中启用请求范围

在我的应用程序中,我有一些异步Web服务.服务器接受请求,返回OK响应并使用AsyncTaskExecutor启动处理请求.我的问题是如何在此处启用请求范围,因为在此处理中我需要获取注释的类:

@Scope(value = WebApplicationContext.SCOPE_REQUEST, proxyMode = ScopedProxyMode.TARGET_CLASS)
Run Code Online (Sandbox Code Playgroud)

现在我得到例外:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.requestContextImpl': Scope 'request' is not active for the current thread; consider defining a scoped proxy for this bean if you intend to refer to it from a singleton; nested exception is java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web …
Run Code Online (Sandbox Code Playgroud)

java spring

32
推荐指数
5
解决办法
3万
查看次数

在servlet多部分帖子中无法访问Spring Security信息

我在servlet多部分帖子中无法访问Spring Security信息.弹出安全信息在常规get和post方法中可用,但不适用于多部分post方法.我尝试直接通过SecurityContextHolder.getContext().getAuthentication()以及访问SecurityContextHolder.getContext().getAuthentication()的注入服务来访问此安全信息失败.

我还实现了一个HttpRequestHandler和一个ServletWrappingController.再一次,我能够成功地将spring bean注入其中并访问Spring Security信息以获取常规的get和post方法,但是我无法访问多部分帖子的Spring Security信息.我知道Spring 3.0中内置了新的MultiPart功能,但由于我们的网站需要完全访问文件上传流,我将无法使用它们.出于这个原因,我专注于HttpServlet,HttpRequestHandler和ServletWrappingController.

我在这里发布的代码是为解决这个特定问题所编写的所有测试代码,我面临着在分段上传期间无法获得的安全信息(并不意味着具有生产质量).这是一个HttpServlet.

如果我做错了,请告诉我.或者,如果没有,是否有解决方法或更好的方法来完成可以访问Spring Security信息的多部分上传,同时保持对文件上载流的访问?任何人可以提供此问题的任何帮助将不胜感激!

下面是测试servlet代码.根据使用Spring Security 3.1登录到网站的用户,下面有关哪些有效以及哪些无效的评论:

//many import statements not displayed 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class UploadServlet extends HttpServlet {

    public void service(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
        super.service(req, res);
    }

    public void init(ServletConfig config) throws ServletException { 
        super.init(config); 

        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, 
          config.getServletContext()); 
    } 


    //The following is always injected and available
    //however, it only returns valid security information for regular get and post methods,
    //not for multipart post …
Run Code Online (Sandbox Code Playgroud)

java spring servlets spring-mvc spring-security

7
推荐指数
1
解决办法
862
查看次数

Java Future - Spring Authentication在AuditorAware中为null

这是我的情景:

我的应用程序启用了Mongo审核,使用自定义AuditorAware从当前用户获取SecurityContext.这适用于同步方法,并且当前审计员已成功保存,但我无法使其与@Async方法一起正常工作.

我有一个异步方法(CompletableFuture),可以对我的Mongo数据库进行一些更新.当AuditorAware.getCurrentAuditor()被调用时,没有任何身份验证信息存在,我不能让现任核数师(SecurityContextHolder.getContext().getAuthentication()回报null).

@Override
public User getCurrentAuditor() {
   Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

   if (authentication == null || !authentication.isAuthenticated()
                || authentication instanceof AnonymousAuthenticationToken) {
            log.error("Not authenticated");
            return null;
    }

    [...]

}
Run Code Online (Sandbox Code Playgroud)

我用的是DelegatingSecurityContextAsyncTaskExecutor:

@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {

    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(100);
        executor.setQueueCapacity(200);
        executor.initialize();

        return new DelegatingSecurityContextAsyncTaskExecutor(executor);
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new ItacaExceptionHandler();
    } …
Run Code Online (Sandbox Code Playgroud)

java spring spring-security mongodb completable-future

3
推荐指数
2
解决办法
1926
查看次数

使用@Async时的SecurityContextHolder.getContext()NPE

我正在尝试将spring服务的一系列顺序调用转换为异步.

我已经注释了方法@Async并添加了taskExecutor configuratinos.

我可以看到该方法现在异步调用但我遇到SecurityContextHolder.getContext()抛出此错误的问题 :

java.util.concurrent.ExecutionException: java.lang.NullPointerException

非常感谢任何见解.谢谢!

java spring multithreading spring-security

2
推荐指数
1
解决办法
1904
查看次数

如何在使用 Async 创建的线程中访问安全上下文

我将 Async 与使用 Feign 调用远程服务的方法一起使用,我需要将 oauth2 令牌附加到请求中,为此我使用了 RequestInterceptor。

@Bean
public RequestInterceptor requestTokenBearerInterceptor() {

    return requestTemplate -> {

        Object principal = SecurityContextHolder
                .getContext()
                .getAuthentication()
                .getPrincipal();

        if (!principal.equals("anonymousUser")) {

            OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails)
                    SecurityContextHolder.getContext().getAuthentication().getDetails();

            requestTemplate.header("Authorization", "bearer " + details.getTokenValue());
        }
    };
}
Run Code Online (Sandbox Code Playgroud)

但是当 requestInterceptor 在另一个线程中使用时,我无法访问相同的安全上下文,因此 getAuthentication 返回 null。

我尝试在执行程序配置中修复它,我创建了一个 DelegatingSecurityContextExecutor 来包装执行程序和安全上下文。但似乎 bean 是在“主”线程中创建的,并且安全上下文与当时使用的安全上下文不同,当执行 RestController 方法时,因此 getAuthentication() 仍然返回 null。

   @Bean(name = "asyncExecutor")

    public Executor asyncExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(3);
        executor.setMaxPoolSize(3);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("AsynchThread-");
        executor.initialize();

        Executor wrappedExecutor = new DelegatingSecurityContextExecutor(executor, SecurityContextHolder.getContext());

        return …
Run Code Online (Sandbox Code Playgroud)

multithreading asynchronous spring-mvc spring-boot spring-cloud-feign

2
推荐指数
1
解决办法
1016
查看次数