I get a 404 error when testing forms authentication with Spring Security

Overview

When I tested forms authentication with the following configuration in Spring Security, a 404 error occurred.

                       POST 
            --------------------------------->
 Form screen AuthenticationProvider
 ·username
 ・ Password <=================================
 User information

SecurityConfig.java


@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/webjars/**", "/css/");
    }

    @Override
    protected void configure(HttpSecurity http) {
        http.authorizeRequests()
                .antMatchers("signin").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginProcessingUrl("/authentication")
                .loginPage("signin")
                .failureUrl("signin" + "?error")
                .successForwardUrl("/hoge/list")
                .failureForwardUrl("/authenticationError")
                .usernameParameter("username")
                .passwordParameter("password")
                .and()
                .logout()
                .logoutSuccessUrl("signin");

}

TestClass.java


@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = HogeApplication.class)
public class TestClass {

    @Before
public void Prepare request() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .build();
    }

    @Test
public void Authenticate with request URL() throws Exception {
        ResultActions result = mvc.perform(
                MockMvcRequestBuilders.post("/authentication")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .param("username",User account)
                .param("password",password)
        );
        result.andExpect(status().isOk())
                .andExpect(forwardedUrl("/hoge/list"));
    }
}
 Assertion results

java.lang.AssertionError: Status 
Expected :200
Actual   :404

Workaround

Take the following two workarounds.

Applying the above, the test class will be as follows.

TestClass.java


@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ContextConfiguration(classes = HogeApplication.class)
public class TestClass {

    @Before
public void Prepare request() {
        mvc = MockMvcBuilders
                .webAppContextSetup(context)
                .apply(springSecurity()) //If this is not applied, even if csrf is set, it will be 404.
                .build();
    }

    @Test
public void Authenticate with request URL() throws Exception {
        ResultActions result = mvc.perform(
                MockMvcRequestBuilders.post("/authentication")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .with(csrf())
                .param("username",User account)
                .param("password",password)
        );
        result.andExpect(status().isOk())
                .apply(springSecurity()) //If this is not applied, even if csrf is set, it will be 404.
                .andExpect(forwardedUrl("/hoge/list"));
    }
}

About form settings

Official documentation also mentions csrf (), but explicitly post The username and password did not pass to the server side in the following implementation without requesting. There may be something wrong, but I don't know. .. ..

TestClass.java


public class TestClass {
Methods that do not pass the public parameter() {
        ResultActions result2 = mvc.perform(formLogin("/authentication")
                .user(User account).password(password));
        result2.andExpect(status().isOk())
                .andExpect(forwardedUrl("/clients/list"))
                .andDo(MockMvcResultHandlers.print());
        ResultActions result3 = mvc.perform(MockMvcRequestBuilders.post("/authentication")
                .contentType(MediaType.APPLICATION_FORM_URLENCODED)
                .with(csrf())
                .with(user(User account).password(password)));
        result3.andExpect(status().isOk())
                .andExpect(forwardedUrl("/clients/list"))
                .andDo(MockMvcResultHandlers.print());
    }
}

The result was the same with csrf (). AsHeader ().

Apply springSecurity

If springSecurity () is not applied, it will be 404 even if csrf () is set in MockMvcRequestBuilders # post.

Recommended Posts

I get a 404 error when testing forms authentication with Spring Security
I get an error when adding a dependency
A memo when "I do not get a certificate error with a self-signed certificate using Java's Keytool"
Implemented authentication function with Spring Security ②
Implemented authentication function with Spring Security ③
Implemented authentication function with Spring Security ①
Authentication / authorization with Spring Security & Thymeleaf
I get a Ruby version error when I try to start Rails.
DB authentication with Spring Security & hashing with BCrypt
Achieve BASIC authentication with Spring Boot + Spring Security
[Visual Studio Code] I get a syntax error when debugging when using rbenv
Try LDAP authentication with Spring Security (Spring Boot) + OpenLDAP
Add your own authentication items with Spring Security
[Introduction to Spring Boot] Authentication function with Spring Security
When I renew the certificate with CircleCI × fastlane, I get an exit status: 65 error.
What I was addicted to when developing a Spring Boot application with VS Code
A memorandum when trying Spring Data JPA with STS
About Spring Security authentication
A memo that I was addicted to when making batch processing with Spring Boot
Implement a simple Rest API with Spring Security with Spring Boot 2.0
I tried to get started with Spring Data JPA
A memorandum when creating a REST service with Spring Boot
When I bcrypt with node + docker, I got an error
Create a simple demo site with Spring Security with Spring Boot 2.1
Error handling when the maximum file size is exceeded when uploading a file with Spring Boot
I have a question. I get an error when playing a video in Listview on android.
I wrote a test with Spring Boot + JUnit 5 now
A new employee tried to create an authentication / authorization function from scratch with Spring Security
When starting Eclipse debug, I get a `ERROR: JDWP Transport dt_socket failed` error and cannot start.
I tried to get started with Swagger using Spring Boot
Implement a simple Rest API with Spring Security & JWT with Spring Boot 2.0
Get started with Spring boot
Login function with Spring Security
Error when playing with java
Error when introducing SNS authentication
I tried printing a form with Spring MVC and JasperReports 1/3 (JasperReports settings)
I tried printing a form with Spring MVC and JasperReports 3/3 (Spring MVC control)
When I push to Heroku, I get angry with Precompiling assets failed.
I implemented an OAuth client with Spring Boot / Security (LINE login)
I made a simple search form with Spring Boot + GitHub Search API.
What I was addicted to when implementing google authentication with rails
I got a Permission Denied error when I put Laravel in Docker
Spring Security usage memo Authentication / authorization
Use Basic Authentication with Spring Boot
Spring Boot Tutorial Using Spring Security Authentication
I made a GUI with Swing
Get validation results with Spring Boot
Learn Spring Security authentication processing architecture
Oauth2 authentication with Spring Cloud Gateway
I tried GraphQL with Spring Boot
I tried Flyway with Spring Boot
About error when implementing spring validation
I get an error with bundle install and puma cannot be installed.
Spring Boot + MyBatis I get this error if I don't set the database
A story I was addicted to when testing the API using MockMVC
I tried printing a form with Spring MVC and JasperReports 2/3 (form template creation)
[LINE BOT] I made a ramen BOT with Java (Maven) + Heroku + Spring Boot (1)
When registering a new user, I got an error called ActiveRecord :: NotNullViolation and how to deal with it.
When introducing JOOQ to Spring boot, a story that was dealt with because an error occurred around Liquibase