Search code examples
javaspringspring-mvcspring-security

How to add PathVariable to DefaultSuccessUrl in Spring Security?


In Spring Security Config I have the next method:

@Configuration
@EnableGlobalMethodSecurity(jsr250Enabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
           .authorizeRequests()
               .antMatchers("/register/**").permitAll()
               .anyRequest()
               .authenticated()
               .and()   
        .formLogin()
           .loginPage("/login")
           .defaultSuccessUrl("/profile") // <-- here
               .permitAll();
    }
}

Can I somehow redirect to URL /profile/{user_id} after successful login?

Now it redirects to URL /profile. I will be thankful for any advice here.


Solution

  • Hi, you can to try something like this:

    1. Create a custom AuthenticationSuccessHandler where you will extract it from Authentication->Principal(what is usually jwt token where you have user_id) -> you can convert it into an object for more flexibility work and you can pass your user_id into MDC what is ThreadLocal. enter image description here

    2. Create a bean of AuthenticationSuccessHandler in your SecurityConfig class enter image description here

    3. Finally you can extract it from MDC(threadLocal)

    .defaultSuccessUrl("/profile/" + MDC.get("user_id"))
    

    P.S. Just give me a feedback if it was helpfully