4
votes

I set contextPath in application.properties as server.contextPath=/myWebApp in spring boot application with spring security, default url as /login it not setting context path as /myWebApp and redirect back me as /login not as /myWebApp/login. How to set contextPath with spring security 4.0 ? As tomcat give warning as context []..not deploying app in container.

2
Any suggestions on this problem? I have the same issue. - RaHe

2 Answers

1
votes

I solved this issue by setting server.servlet.context-path in Application.properties file

Code Example

Application.properties

server.servlet.context-path=/myWebApp/


with this, you can also achieve a login page as you want http://localhost:8080/myWebApp/login


0
votes

In Spring Boot you can set context path 3 ways.

First in application.properties like as you do.

server.contextPath=/myWebApp 

Second the change can be done programmatically as well:

import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.stereotype.Component;

@Component
public class CustomContainer implements EmbeddedServletContainerCustomizer {

    @Override
    public void customize(ConfigurableEmbeddedServletContainer container) {

        container.setPort(8181);
        container.setContextPath("/myWebApp ");

    }

}

And Finally, by passing the system properties directly:

java -jar -Dserver.contextPath=/myWebApp spring-boot-example-1.0.jar

Spring Security Config is:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests()
                .antMatchers("/static/**").permitAll()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login")
                .usernameParameter("username")
                .passwordParameter("password")
                .loginProcessingUrl("/j_spring_security_check")
                .failureUrl("/login?error=true")
                .defaultSuccessUrl("/index")
                .and()
                .logout().logoutUrl("/logout").logoutSuccessUrl("/login")
                ;

    }
}

And without any further changes,tomcat will start automatically /myWebApp/login