12

What ever link I type in the address bar it keeps redirecting me to the login page. How can I prevent that?

For example if i add http://localhost:8080/asdasdsa > it will redirect me to http://localhost:8080/account/login, so if i add anything after http://localhost:8080/ i will be redirected to account/login view.

My security config:

package com.example.configuration;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @Autowired
    private DataSource dataSource;

    @Value("${spring.queries.users-query}")
    private String usersQuery;

    @Value("${spring.queries.roles-query}")
    private String rolesQuery;

    @Override
    protected void configure(AuthenticationManagerBuilder auth)
            throws Exception {
        auth
            .jdbcAuthentication()
                .usersByUsernameQuery(usersQuery)
                .authoritiesByUsernameQuery(rolesQuery)
                .dataSource(dataSource)
                .passwordEncoder(bCryptPasswordEncoder);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/index").permitAll()
                .antMatchers("/other/other").permitAll()
                .antMatchers("/account/login").permitAll()
                .antMatchers("/account/registration").permitAll()
                .antMatchers("/account/admin/**").hasAuthority("ADMIN")
                .anyRequest().authenticated()
                .and()
            .csrf().disable()
            .formLogin()
                .loginPage("/account/login")
                .failureUrl("/account/login?error=true")
                .defaultSuccessUrl("/account/admin/")
                .usernameParameter("email")
                .passwordParameter("password")
                .and()
            .logout().permitAll()
                .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                .logoutSuccessUrl("/")
                .and()
            .exceptionHandling()
                .accessDeniedPage("/access-denied");
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
           .ignoring()
               .antMatchers("/resources/**", "/static/**", "/css/**", "/js/**", "/images/**", "/img/**");
    }
}
john
  • 796
  • 1
  • 13
  • 34
  • i have link on index page to go to registration form using thymeleaf: Register clicking on this it redirects me to account/login – john Jan 24 '17 at 14:03
  • @dur Yes /index works, but it seems that i cant click on links... is there anyway to prevent auto redirect to login page? – john Jan 25 '17 at 09:35

3 Answers3

13

You configured that all other URLs must be authenticated, see Spring Security Reference:

Authorize Requests

Our examples have only required users to be authenticated and have done so for every URL in our application. We can specify custom requirements for our URLs by adding multiple children to our http.authorizeRequests() method. For example:

protected void configure(HttpSecurity http) throws Exception {
  http
      .authorizeRequests()                                                          1
          .antMatchers("/resources/**", "/signup", "/about").permitAll()            2
          .antMatchers("/admin/**").hasRole("ADMIN")                                3
          .antMatchers("/db/**").access("hasRole('ADMIN') and hasRole('DBA')")      4
          .anyRequest().authenticated()                                             5
          .and()
      // ...
      .formLogin();
}

1 There are multiple children to the http.authorizeRequests() method each matcher is considered in the order they were declared.

2 We specified multiple URL patterns that any user can access. Specifically, any user can access a request if the URL starts with "/resources/", equals "/signup", or equals "/about".

3 Any URL that starts with "/admin/" will be restricted to users who have the role "ROLE_ADMIN". You will notice that since we are invoking the hasRole method we do not need to specify the "ROLE_" prefix.

4 Any URL that starts with "/db/" requires the user to have both "ROLE_ADMIN" and "ROLE_DBA". You will notice that since we are using the hasRole expression we do not need to specify the "ROLE_" prefix.

5 Any URL that has not already been matched on only requires that the user be authenticated

dur
  • 15,689
  • 25
  • 79
  • 125
3

Try with 127.0.0.1 instead of localhost.

Explanation

Your browser doesn't set the JSESSIONID cookie for localhost (see this SO question), so when redirecting after successful login the next request looks not authenticated to the server.

If you use idea and you open the browser clicking on the Services panel, you can add this config in your application-dev.yml to fix that:

server:
  address: 127.0.0.1
laffuste
  • 16,287
  • 8
  • 84
  • 91
0

Here's a workaround!

// Required to provide UserDetailsService for "remember functionality"
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER");
}

Add the above snippet to your Security Config class, add the same username and password defined in pom.xml here as well. (without removing the "{noop}" part)

So next time you login, don't forget to click on "remember me" check box else the issue will keep repeating.

You may refer this article for further details.

Anurag Bhalekar
  • 830
  • 7
  • 9