Spring MVC application does not redirect to page after login

Asked

Viewed 223 times

-1

I have a problem and I would like to count on your valuable help to solve it.

After logging into the application the user should be forwarding to a catalog listing page. The login itself is ok, however, this forwarding does not happen automatically: the listing page is only displayed when you inform your url directly in the browser and press the ENTER key. Other than that, the user stays on the login screen.

Follow parts of the codes developed so far:

Java Security Controller.

//package e imports omitidos

@Controller
public class SegurancaController {

    @GetMapping("/entrar")
    public String realizarLogin(@AuthenticationPrincipal Usuario usuario) {
        if (usuario != null) {
            int usuarioId = (int) usuario.getId();

            return "redirect:/usuarios/" + usuarioId + "/catalogos/listar";

        } else
            return "entrar";
    }
}

Catalogocontroller.java

//package e imports omitidos

@Controller
@RequestMapping("usuarios/{usuarioId}/catalogos")
public class CatalogoController {
//...

    @GetMapping("/listar")
    public ModelAndView listar(@PathVariable("usuarioId") long usuarioId, ModelMap model) {
        model.addAttribute("catalogos", catalogoService.recuperarPorUsuario(usuarioId));
        model.addAttribute("usuarioId", usuarioId);

        return new ModelAndView("/catalogo/list", model);
    }
}

Securityconfig.java

//package e imports omitidos

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http 
            .authorizeRequests()
                .antMatchers("/usuarios/cadastro", "/usuarios/salvar").permitAll()
                .anyRequest().authenticated()
                .and()
            .formLogin()
                .loginPage("/entrar")
                .permitAll();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider provider = new DaoAuthenticationProvider();
        provider.setPasswordEncoder(passwordEncoder);
        provider.setUserDetailsService(userDetailsService);
        return provider;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/css/**", "/webjars/**");
    }
}

I’ve been trying to solve this problem for days without success!

I would be most grateful to all who can help. :)

Thanks in advance.

2 answers

0

In the Securityconfig class, after . loginPage("/enter"), you will put: .defaultSuccessUrl("/listar", true)

  • Hello @Mechior Happy, sorry for the delay in answering. Some problems made it impossible for me to answer before. Thank you for your help! This solves my problem, however, I am unable to get the logged-in user id to pass as part of the url in the defaultSuccessUrl("/users/" + usersId + "/catalogos/list", true). I tried with Securitycontextholder.getcontext(). getAuthentication(). getPrincipal() within the method where I declared defaultSuccessUrl(). I was not successful because I get a Nullpointerexception when I go up the project. Could you help me? Thanks in advance! :-)

0

Authentication auth = SecurityContextHolder.getContext().getAuthentication();
Usuario usuario = (Usuario)auth.getPrincipal();
int usuarioId = usuario.getId();

It should work,not forget to mark as answered the question,so help the little friends

  • Hello, @Melchior Felix! Keep getting Nullpointerexception: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'springSecurityFilterChain' defined in class path resource [org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.servlet.Filter]: Factory method 'springSecurityFilterChain' threw exception; nested exception is java.lang.NullPointerException. :(

Browser other questions tagged

You are not signed in. Login or sign up in order to post.