Spring Security's redirect to login page returns 404 - spring

I want to use Spring Security 4.0.3 in my project but I don't really know how to do this in combination with the other technologies:
Vaadin 7.5.8
Vaadins official Spring Addon 1.0.0
Spring 4.2.1
Tomcat 8 Server
I read a few articles about Vaadin and Spring Security but i didn't found anything about integreting it with the official Vaadin Spring Addon.
Because I'm new to Vaadin I followed Vaadins official Spring tutorial and the Spring Security documentation. I want to setup my project without Spring Boot! Currently I got the following:
#WebListener
public class MyContextLoaderListener extends ContextLoaderListener
{
}
#WebServlet(value = "/*", asyncSupported = true)
public class Servlet extends SpringVaadinServlet
{
}
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter
{
#Autowired
UserDetailsService userDetailsService;
#Bean
public PasswordEncoder passwordEncoder()
{
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
#Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception
{
// #formatter:off
http
.authorizeRequests()
.antMatchers("/VAADIN/**", "/UIDL/**", "/login**", "/resources/**").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/#!", true).permitAll()
.and()
.logout().permitAll()
.and()
.csrf().disable();
// #formatter:on
// TODO plumb custom HTTP 403 and 404 pages
/* http.exceptionHandling().accessDeniedPage("/access?error"); */
}
}
public class SecurityWebApplicationInitializer extends AbstractSecurityWebApplicationInitializer
{
}
My pom.xml looks like this:
[...]
<spring.version>4.2.1.RELEASE</spring.version>
<spring.security.version>4.0.3.RELEASE</spring.security.version>
[...]
<dependencies>
[...]
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${spring.security.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${spring.security.version}</version>
</dependency>
</dependencies>
[...]
Now I'm asking myself if I implemented it the right way. Preferably I don't want to use a web.xml instead I want to use Java configuration.
The server starts without an error but when I open the URL I get the following error message:
HTTP Status 404 - Request was not handled by any registered handler.
Can anyone help me?
EDIT:
I don't know if I'm on the right way but I added an asterisk to "/*" in the annotation of the SpringVaadinServlet:
#WebServlet(value = "/**", asyncSupported = true)
Now after the browser redirects to http://localhost:8080/myApp/login I get a normal 404 Not Found without anything...

Related

How to resolve javax.servlet.ServletException: Circular view path for basic Spring Security?

Im new to Spring Boot and was trying to implement basic Spring Security for a single endpoint in my Spring Boot controller. But I dont know how to resolve the Circular View Error
My Controller
#Controller
#RequestMapping("/api")
public class HelloSecurityController {
#RequestMapping({"/hello"})
public static String helloWorld() {
return "hello";
}
My Security Configurer Class
#EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
#Autowired
private MyUserDetailsService myUserDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(myUserDetailsService);
}
#Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
```
My MyUserDetailsService which returns a simple User with Password
#Service
public class MyUserDetailsService implements UserDetailsService {
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
return new User("foo","foo", new ArrayList<>());
The Dependencies I kept in maven pom file during initializing Spring Boot Project
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
The Package structure of my project:
proj_struct
After logging in using the username and password at the login form page generated by spring security Im getting the error:
javax.servlet.ServletException: Circular view path [hello]: would dispatch back to the current handler URL [/api/hello] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
I have not kept any static template (HTML/JSP) in the templates folder. I dont know if I have to as after login I just want to see a simple String. How do I resolve this?

NoSuchMethodError on Spring Boot Security

I'm following this tutorial : https://www.baeldung.com/spring-boot-security-autoconfiguration to add Simple Auth. to my Spring Boot Project. When i try to run my application i always get this error :
Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NoSuchMethodError: org.springframework.util.Assert.isTrue(ZLjava/util/function/Supplier;)V
IDK why im getting this or is this related something about Version problem. Do you guys have any idea about this ?
You can relate your question with this answer
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
security configuration class
#Configuration
#EnableWebSecurity
public class Config extends WebSecurityConfigurerAdapter{
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("username")
.password("password")
.roles("ADMIN","USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/greetings").hasRole("ADMIN")
.and()
.httpBasic()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
}
}
A simple restController
#GetMapping("/greetings")
public String greetings(){
return "Hello World!";
}
this is the basic security using memory authentication. you can relate your pom.xml and configuration.class, In most cases spring-boot, resolves the versions by default.

Springboot Spring Security Ldap Login page not showing up

I created a springboot application with spring security dependencies.
I following some tutorials and most of the say the same. I add the dependencies needed and then create a websecurityconfig file. I created these and when I run the project on my local host it works fine. I pushed my application to a remote server and I am not seeing the login page.
Here are my list of dependencies
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
And here is my websecurity config
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
LdapConfig ldapConfig;
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
#Bean
public UserDetailsContextMapper userDetailsContextMapper() {
return new CustomUserDetailsContextMapper();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
LdapAuthenticationProviderConfigurer<AuthenticationManagerBuilder>.ContextSourceBuilder contextSourceBuilder = auth.ldapAuthentication()
.userSearchBase(ldapConfig.getUserSearchBase())
.userSearchFilter(ldapConfig.getUserSearchFilter())
.groupSearchBase(ldapConfig.getGroupSearchBase())
.groupSearchFilter(ldapConfig.getGroupSearchFilter())
.groupRoleAttribute(ldapConfig.getGroupRoleAttribute())
.userDetailsContextMapper(userDetailsContextMapper())
.contextSource();
if (ldapConfig.getPort() != null) {
contextSourceBuilder.port(ldapConfig.getPort());
}
contextSourceBuilder
.root(ldapConfig.getRoot())
.url(ldapConfig.getUrl())
.managerDn(ldapConfig.getManagerDn())
.managerPassword(ldapConfig.getManagerPassword());
}
}
This has eaten up a lot of my time, any one Please help me...
Are you getting a Not Authorized when trying to get to the login page ?
Because it looks like you are requiring someone to already be authenticated to access it.
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
You'll need something similar to
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin();
}
to allow the login page to be reached.

How to run hazelcast session replication using vaadin4spring?

I am writing a simple demo application using hazelcast session replication based on the shared security example
mentioned in here https://github.com/peholmst/vaadin4spring.
The problem is that if i am starting the application it stays on the login site with "communication error".
With vaadin debug on, it shows me "Response didn't contain a server id. Please verify that the server is up-to-date and that the response data has not been modified in transmission."
In the IDE no stack trace is shown.
I tried also the working example here https://vaadin.com/blog/microservices-high-availability, but it didnĀ“t give me a hint how to integrate hazelcast with vaadin4spring.
Here is my configuration:
public void configure(AuthenticationManagerBuilder auth) throws Exception {
User.UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication().withUser("user").password("{noop}user").roles("USER")
.and()
.withUser("admin").password("{noop}admin").roles("ADMIN");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable(); // Use Vaadin's built-in CSRF protection instead
http.authorizeRequests().antMatchers("/login/**").anonymous()
.antMatchers("/vaadinServlet/UIDL/**").permitAll()
.antMatchers("/vaadinServlet/HEARTBEAT/**").permitAll().anyRequest().authenticated();
http.httpBasic().disable();
http.formLogin().disable();
// Remember to add the VaadinSessionClosingLogoutHandler
http.logout().addLogoutHandler(new VaadinSessionClosingLogoutHandler()).logoutUrl("/logout")
.logoutSuccessUrl("/login?logout").permitAll();
http.exceptionHandling().authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login"));
// Instruct Spring Security to use the same RememberMeServices as Vaadin4Spring. Also remember the key.
//http.rememberMe().rememberMeServices(rememberMeServices()).key("myAppKey");
// Instruct Spring Security to use the same authentication strategy as Vaadin4Spring
http.sessionManagement().sessionAuthenticationStrategy(sessionAuthenticationStrategy());
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/VAADIN/**");
}
/**
* The {#link AuthenticationManager} must be available as a Spring bean for Vaadin4Spring.
*/
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
/**
* The {#link SessionAuthenticationStrategy} must be available as a Spring bean for Vaadin4Spring.
*/
#Bean
public SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new SessionFixationProtectionStrategy();
}
#Bean(name = VaadinSharedSecurityConfiguration.VAADIN_AUTHENTICATION_SUCCESS_HANDLER_BEAN)
VaadinAuthenticationSuccessHandler vaadinAuthenticationSuccessHandler(HttpService httpService,
VaadinRedirectStrategy vaadinRedirectStrategy) {
return new VaadinUrlAuthenticationSuccessHandler(httpService, vaadinRedirectStrategy, "/");
}
#Bean
public HazelcastInstance hazelcastInstance() {
MapAttributeConfig attributeConfig = new MapAttributeConfig()
.setName(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE)
.setExtractor(PrincipalNameExtractor.class.getName());
Config config = new Config();
config.setProperty("hazelcast.max.no.heartbeat.seconds", "60")
.getMapConfig("spring:session:sessions")
.addMapAttributeConfig(attributeConfig)
.addMapIndexConfig(new MapIndexConfig(HazelcastSessionRepository.PRINCIPAL_NAME_ATTRIBUTE, false));
config.getGroupConfig().setName("admin");
return Hazelcast.newHazelcastInstance(config);
}
pom snippet:
<java.version>1.8</java.version>
<vaadin.version>8.7.2</vaadin.version>
<spring-boot-ext.version>2.0.0.RELEASE</spring-boot-ext.version>
</properties>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-hazelcast</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.vaadin.spring.extensions</groupId>
<artifactId>vaadin-spring-ext-boot</artifactId>
<version>${spring-boot-ext.version}</version>
</dependency>
<dependency>
<groupId>org.vaadin.spring.extensions</groupId>
<artifactId>vaadin-spring-ext-security</artifactId>
<version>${spring-boot-ext.version}</version>
</dependency>
<dependency>
<groupId>org.vaadin.spring.extensions</groupId>
<artifactId>vaadin-spring-ext-core</artifactId>
<version>${spring-boot-ext.version}</version>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.vaadin</groupId>
<artifactId>vaadin-bom</artifactId>
<version>${vaadin.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

Spring web app returns HTTP Status 406

I'm creating a basic spring based web app:
pom dependencies:
<properties>
<java-version>1.8</java-version>
<springframework-version>4.3.3.RELEASE</springframework-version>
<jackson-version>2.8.3</jackson-version>
<org.slf4j-version>1.7.6</org.slf4j-version>
<logback.version>1.1.7</logback.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${springframework-version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
<!-- Logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${org.slf4j-version}</version>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>${logback.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- #Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
</dependencies>
In order to skip the usage of web.xml I'm using WebApplicationInitializer:
public class AppInitializer implements WebApplicationInitializer {
#Override
public void onStartup(ServletContext servletContext) throws ServletException {
WebApplicationContext context = getContext();
servletContext.addListener(new ContextLoaderListener(context));
ServletRegistration.Dynamic dispatcher = servletContext.addServlet("DispatcherServlet", new DispatcherServlet(context));
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");
}
private AnnotationConfigWebApplicationContext getContext() {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setConfigLocation(SpringModule.class.getPackage().getName());
return context;
}
Here is my spring config class:
#Configuration
#ComponentScan(basePackages = "com.company.app")
public class SpringModule extends WebMvcConfigurerAdapter {
public SpringModule() {
super();
}
private MappingJackson2HttpMessageConverter customJackson2HttpMessageConverter() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
jsonConverter.setObjectMapper(objectMapper);
return jsonConverter;
}
#Override
public void configureMessageConverters(List<HttpMessageConverter<?>> messageConverters) {
messageConverters.add(customJackson2HttpMessageConverter());
messageConverters.add(new Jaxb2RootElementHttpMessageConverter());
messageConverters.add(new StringHttpMessageConverter());
messageConverters.add(new ByteArrayHttpMessageConverter());
messageConverters.add(new ResourceHttpMessageConverter());
messageConverters.add(new SourceHttpMessageConverter());
messageConverters.add(new FormHttpMessageConverter());
super.configureMessageConverters(messageConverters);
}
/*
* Configure ContentNegotiationManager
*/
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.ignoreAcceptHeader(true).defaultContentType(
MediaType.APPLICATION_JSON);
}
Here is my test controller:
#Controller
#RequestMapping(value = "/user")
public class SomeController {
#RequestMapping(value = "/", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public Person helloElad() {
return new Person("some name");
}
}
When testing the controller (using browser) I'm getting:
If I'm returning a plain String it works fine.
I tries to debug method configureMessageConverters and configureContentNegotiation but for some reason it never gets there (on bootstrapping), I'm not sure it is related to the problem though.
Any ideas?
HTTP 406 is an indication that your request content is not negotiated, it is probably that necessary http message converters are not found in configuration. Simple way to add basic set of message converter would be annotating your controller #EnableMvc
I had the same problem and couldn't find a solution here or elsewhere.
I also tried the advice of applying #EnableMvc on my AppConfig but that caused a different problem in which Tomcat wouldn't even successfully start up.
Eventually, I had to rewrite my AppInit class as follows:
https://github.com/viralpatel/spring4-restful-example/tree/master/src/main/java/net/viralpatel/spring/config
Now, I'm getting JSON back when I return a POJO. I don't like this fix. The code seems incomplete compared to the AppInit shown in the problem here, but I'm unstuck.

Resources