简体   繁体   中英

Spring security context and @Repository bean

Is it safe to access to the Spring Security context from @Repository bean?

Let us say that we have some @Repository :

public interface FooRep {
    Foo getFoo();
}

@Repository
public class FooRepImpl {    
    public Foo getFoo() {
       Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
       return (Foo)authentication.getDetails();
    }
}

It is wrapped into service layer:

public interface FooService {
     Foo getFoo();
}

@Service    
public class FooServiceImpl {
    @Autowired FooRep fooRep;

    public Foo getFoo() {
        return fooRep.getFoo();
    }
}

And let us say that this method is accessed from secured controller, something like that:

@RestController
@Secured
public void FooController {
     @Autowired FooService fooSer;

     @RequestMapping("/foo");
     public Foo getFoo() {
         return fooSer.getFoo();
     }
}

This is very simplified example, but essential part of logic is here.

Please, do not ask me why do I need it and do not give me advices how to restructure this architecture.

I only need to know, can it cause any issues related to multithread usage?

The question is arisen, because we have experienced cases when authentication.getDetails() contained Foo instance different from that which was placed there in the authentication interceptor. This is very weird and looks impossible.

There is a case when you start eg a Job which has no access to Request so don't have access to auth info but the Job still uses the repository.

If you create a new thread and access the repository from the thread again could be an issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM