Page redirection using spring security

23 views Asked by At

I'm a newbie to spring security, I'm trying to create a JWT token with spring security. I have defined my successhandler function after the default form authentication of spring. The successhandler creates a jwt token and sends it as a response header. Now I want to land at my Index page how do I achieve it? How can I add the jwt as an authentication header and write a page redirection in the successhandler to my /UserIndex page? I'd also like to know we can redirect user to Admin Index or User Index based on roles in the success handler. This is my config code @Configuration @EnableWebSecurity public class JWTSecurityConfig {

 @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeRequests(authorize -> authorize
                .requestMatchers("/SignIn*").permitAll()
                .requestMatchers(PathRequest.toStaticResources().atCommonLocations()).permitAll()
                .requestMatchers(PathRequest.toH2Console()).permitAll()
                .anyRequest().authenticated()
            )    
            .formLogin()
                .loginPage("/SignIn")
                .loginProcessingUrl("/Authenticate")
                .successHandler(appAuthenticationSuccessHandler())
                .permitAll()
            .and()
            .sessionManagement(session -> session
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            )
            .headers(headers -> headers.frameOptions().sameOrigin())
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);

        return http.build();
    }
 
 @Bean
    public AuthenticationSuccessHandler appAuthenticationSuccessHandler() {
        return new AppAuthenticationSuccessHandler();
    }
 
 public class AppAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{
     @Autowired
        private JWTAuthentication jwtAuthenticationService;
     
     private static final Logger LOGGER = LoggerFactory.getLogger(AppAuthenticationSuccessHandler.class);
     @Override
       protected void handle(HttpServletRequest request, HttpServletResponse response,
       Authentication authentication) throws IOException, ServletException {
         JWTResponse jwtResponse = jwtAuthenticationService.authenticate(authentication);
         System.out.println(jwtResponse);
         Set<String> roles = authentication.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .collect(Collectors.toSet());
         
         LOGGER.info("User roles: {}", roles);
         response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Authorization", "Bearer " + jwtResponse.Token());
        }
}

This is my web controller@Controller public class WebController {

@GetMapping("/SignIn")
public String loginPage() {
    return "LoginPage";
}

@GetMapping("/AdminIndex")
public String adminIndex() {
    return "AdminIndex";
}

@GetMapping("/UserIndex")
public String userIndex() {
    return "UserIndex";
}

}

I tried sending the user to /UserIndex using a redirect in the successhandler but I get redirected back to my login page

0

There are 0 answers