I have a problem in spring security, when I login successfully, the home page that I've set, does not load and the page redirects to the login page. in application logs I've found this two lines after each other :

AuditEvent [timestamp=Sun Jul 30 16:45:40 IRDT 2017, principal=pooya, type=AUTHENTICATION_SUCCESS, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null}]

AuditEvent [timestamp=Sun Jul 30 16:45:41 IRDT 2017, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails@957e: RemoteIpAddress: 127.0.0.1; SessionId: null, type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]

The user information is :

username:pooya
role:ROLE_ADMIN

and this is my security configuration:

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private TypeScanner typeScanner;

    @Bean
    public Object userRestService() {
        Set<Class<? extends AbstractUserRestService>> subTypesOf = typeScanner.getSubTypesOf(AbstractUserRestService.class);
        if (subTypesOf.size() <= 1) {
            return new UserRestService();
        }
        return null;
    }

    @Bean
    public Object userLoginController() {
        Set<Class<? extends AbstractLoginController>> subTypesOf = typeScanner.getSubTypesOf(AbstractLoginController.class);
        if (subTypesOf.size() <= 1) {
            return new UserLoginController();
        }
        return null;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers(
                        "/login**",
                        "/resources/**",
                        "/app/resources/**",
                        "/vendors/**"
                )
                .permitAll()
                .anyRequest()
                .hasRole("ADMIN")
                .and()
                .formLogin()
                .failureUrl("/login.html?error")
                .loginProcessingUrl("/login")
                .loginPage("/login.html")
                .passwordParameter("password")
                .usernameParameter("username")
                .defaultSuccessUrl("/#",true)
                .and()
                .logout()
                .logoutUrl("/logout")
                .and()
                .csrf()
                .disable()
                .sessionManagement()
                .maximumSessions(1000)
                .expiredUrl("/logout?expired");

    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(10);
    }

    @Bean
    public DaoAuthenticationProvider authProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(securityProvider());
        authProvider.setPasswordEncoder(passwordEncoder());
        return authProvider;
    }

    @Bean
    public AbstractUserSecurityProvider securityProvider(){
        return new AbstractUserSecurityProvider(){

        };
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authProvider());
    }

}

and this is my user detail service:

 public abstract class AbstractUserSecurityProvider<S extends AbstractUserService> implements UserDetailsService {

    @Autowired
    private S service;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        User user = new User(s, "", Collections.EMPTY_LIST);
        user.eraseCredentials();

        UserEntity userEntity = service.findByUsername(user.getUsername());
        if(userEntity == null){
            throw new UsernameNotFoundException("Invalid username/password.");
        }
        User result = basicTransformer.convert(userEntity, User.class);
        return new User(result.getUsername().trim(), result.getPassword().trim(), result.getAuthorities());
    }

}

Comment From: khalilkb

Hi pooyaho, did you fix this problem. If yes pls can u share the fix !!!

Comment From: mhyeon-lee

@pooyaho @khalilkb Is this the same problem? https://github.com/spring-projects/spring-security/issues/5487#issuecomment-40619585

Comment From: khalilkb

@mhyeon-lee i have the same behavior, but my problem is that the authContext get cleared after being successfully authenticated and then get filled by anonymousUser. I will try it though. Thx

Comment From: SDMitchell

I don't know if this helps debug the issue at all, but this was driving me crazy.

  • In June I used JHIpster v4.14.4 to generate a UAA and a gateway application. Everything worked great out of the box.
  • The other day I installed the latest JHipster and generated a UAA and a gateway application and I got the exact problem listed in this issue (authContext gets cleared and filled by anonymousUser after successful authenticate).

I figured it was something I was doing (and I tried quite a few things) but to no avail. I then realized via the scrolling version numbers when running the application that this install was JHipster 5.2.0. Sure enough, the huge difference was Spring 1.5.13 -> Spring 2.0.4.

I have no fix - I reverted to the old version of JHipster and everything I generate works. I am only making this comment because it is very easy to generate both sets of code to both reproduce the problem and diff across the code.

Comment From: rwinch

Can anyone reproduce the issue without using JHipster? If so, please log the HTTP Request / Response of requesting the log in page, submitting the credentials, the result of submitting the credentials and any subsequent redirects.

Comment From: gwegwe1234

@khalilkb Did you solve your problem? I have same issue, SecurityContextHolder get cleared and get filled by anonymous after redirect other url. If you fix this problem, help me please.

Comment From: rwinch

@gwegwe1234 Can you provide minimal sample that reproduces the issue?

Comment From: max91

Hello =)

Faced a similar problem. After debugging, I found out that if the JSESSIONID cookie is secure in the browser, then the spring cannot install a new cookie and, accordingly, after login, resets the context to anonymous. I noticed this problem in google chrome. That being said, everything works well in safari. I checked on different versions of spring boot from 2.1.1 to 2.3.3, the problem does not depend on the version

Comment From: spring-projects-issues

If you would like us to look at this issue, please provide the requested information. If the information is not provided within the next 7 days this issue will be closed.

Comment From: spring-projects-issues

Closing due to lack of requested feedback. If you would like us to look at this issue, please provide the requested information and we will re-open the issue.