MockMvc seems to be clear SecurityContext after performing request (java.lang.IllegalArgumentException: Authentication object cannot be null)

I'm trying to run some integration test using SpringBoot + Spring Data Mongo + SpringMVC

I've simplified and generified the code but it should be able to reproduce the behavior with the following test.

As you can see from BookRepository interface I want the user to be able to retrieve only the books that he owns (@Query("{ 'ownerName' : '?#{principal?.username})) and I'm writing a test to perform a POST to save a Book and then verify the book has the owner set appropriately.

For the purpose of the question here I've simplified the test to just to a GET and then calling findAll()

Problem

After performing any MockMvc request, the SecurityContext is cleared using ThreadLocalSecurityContextHolderStrategy#clearContext() which cause the following exception to be thrown when I try to call repository.findAll();

java.lang.IllegalArgumentException: Authentication object cannot be null

BookRepository.java
@RepositoryRestResource
public interface BookRepository extends MongoRepository<Book, String> {

    @Query("{ 'ownerName' : ?#{principal?.username} }")
    List<Book> findAll();  

}
BookCustomRepositoryIntegrationTest.java
/**
 * Integrate data mongo + mvc
 */
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class BookCustomRepositoryIntegrationTest {

    @Autowired
    BookRepository repository;

    @Autowired
    MockMvc mockMvc;  

    @Test
    @WithMockUser
    public void reproduceBug() throws Exception {

        repository.findAll(); //Runs allright

        mockMvc.perform(get("/books")
                .contentType(APPLICATION_JSON_UTF8))
                .andExpect(status().isOk());

        repository.findAll(); //Throws exception: java.lang.IllegalArgumentException: Authentication object cannot be null


    }

}

Your case does not work, because SecurityContextPersistenceFilter and FilterChainProxy filters clear SecurityContextHolder, but the TestSecurityContextHolder (filled by WithSecurityContextTestExecutionListener) still contains SecurityContext.

Try this approach:

@Test
@WithMockUser
public void reproduceBug() throws Exception {
    repository.findAll();
    mockMvc.perform(get("/books")
            .contentType(APPLICATION_JSON_UTF8))
            .andExpect(status().isOk());
    SecurityContextHolder.setContext(TestSecurityContextHolder.getContext());
    repository.findAll();
}

java.lang.IllegalArgumentException: Authentication object cannot be , MockMvc seems to be clear SecurityContext after performing request (java.lang. IllegalArgumentException: Authentication object cannot be nulljava.lang. After making the above changes in Learn and the ADFS server, the End SSO Session logout button will work to properly sign out the user. Problem #7. After entering the login credentials on the ADFS login page, a Sign On Error! message is displayed when redirected to Learn. With the following SAML exception in the bb-services log:


I think instead of using the AutoConfigureMockMvc annotation you could configure MockMvc manually and configure Spring security as follows:

import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.*;

@RunWith(SpringRunner.class)
@SpringBootTest
public class BookCustomRepositoryIntegrationTest {

    @Before
    public void setup() {
        mockMvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity()) 1
                .build();
    }
    // ...
}

As the documentation states:

In order to use Spring Security with Spring MVC Test it is necessary to add the Spring Security FilterChainProxy as a Filter. It is also necessary to add Spring Security’s TestSecurityContextHolderPostProcessor to support Running as a User in Spring MVC Test with Annotations. This can be done using Spring Security’s SecurityMockMvcConfigurers.springSecurity().

[DATAMONGO-2400] Read/write converters not working, MockMvc seems to be clear SecurityContext after performing request (java.lang.​IllegalArgumentException: Authentication object cannot be null). I'm trying to run​  Spring Security is a framework that provides authentication, authorization, and protection against common attacks. With first class support for both imperative and reactive applications, it is the de-facto standard for securing Spring-based applications. This section discusses the logistics of Spring Security.


It may happen that you have forgotten to mark any of your controller with @Controller annotation. It happened in my case and fixing it helped fix the error. This can be one of the troubleshooting steps.

This happens because when you do not mark the controller with @controller and try to make a reference from the templating language(Thymeleaf in my case), in the runtime, it reaches down in the context and returns back losing the authentication object hence the error something like this:

Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "fragments/layout" - line 64, col 8)
    at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)
    at org.attoparser.MarkupParser.parse(MarkupParser.java:257)
    at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230)
    ... 47 more
Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#authorization.expression('!isAuthenticated()')" (template: "fragments/layout" - line 64, col 8)
    at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
...
...
...
...
... 49 more
Caused by: java.lang.IllegalArgumentException: Authentication object cannot be null
    at org.springframework.security.access.expression.SecurityExpressionRoot.<init>(SecurityExpressionRoot.java:61)

Hope this helps.

Spring Security Context Propagation with @Async, MockMvc seems to be clear SecurityContext after performing request (java.lang.​IllegalArgumentException: Authentication object cannot be null). Problem is, that the REST Controller is working when started in the production mode. In the unit test mode, the ${base.url} value is not set and an exception is thrown, when building the mockMvc object: java.lang.IllegalArgumentException: Could not resolve placeholder 'base.url' in string value "${base.url}"


SEC-3174: Combine Spring Security Test and MockMVC throws , when id is a valid ObjectId · Bug. DATAMONGO-2039MockMvc seems to be clear SecurityContext after performing request (java.lang.​IllegalArgumentException: Authentication object cannot be null) CustomConversions - Registering converter from class java.time.LocalDateTime to class org.joda.time. java,spring,junit,spring-boot My JUnit test is failing with the following error: "java.lang.IllegalArgumentException: Could not find field [userRepository] of type [null] on target [[email protected]]" Here is the Test class: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = App.class) @WebAppConfiguration


Cannot get rid of “An Authentication object was not found in the , asyncCall()'. java.lang.NullPointerException: null. So, as you can see, inside the executor  During the last year I have been involved in a very strange problem using Web Service Atomic Transaction (WS-AT) between Microsoft and Wildlfy. The WS-AT is an old OASIS standard to provide atomic transactions in the web between different services.


Spring Security Reference, java.lang.IllegalStateException: springSecurityFilterChain cannot be null. MockMvc mockMvc = MockMvcBuilders // replace standaloneSetup with line below . the authentication is not available within the method handling the request in the @Test public void doSomething() { mockMvc.perform(post("/​doSomething") . TypeError: Cannot read property “length” from null In prototype inheritance program when a property not found in a specified object “NullReferenceException was unhandled by user code” [duplicate]