October 22, 2024
Chicago 12, Melborne City, USA
security

Spring Security Login System


I am building login system using spring security but everytime I login and try to access anonther page, it just redirects me to the Login.html.

private UsernamePasswordAuthenticationToken authentication;

snippet of my post mapping /logged method:
authentication = new UsernamePasswordAuthenticationToken(accountModel, null);
            SecurityContextHolder.getContext().setAuthentication(authentication);

and this is SecurityConfiguration class: 
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(authz -> authz
                .requestMatchers("/register", "/logged", "/favicon.ico").permitAll()
                .anyRequest().authenticated() 
            )
            .formLogin(form -> form
                .loginPage("/login")
                .permitAll()
                .defaultSuccessUrl("/logged", true)
            ).sessionManagement(session -> session
            .sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED)
        );
        return http.build();
    }

    
}

I tried some google researches and gpt problem solving skills



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video