How to use Interceptor in Spring?

Asked

Viewed 54 times

0

I’m a beginner, and in the project I’m developing I used the Interceptor to block access to other resources if the user is not logged in to the session.

For example: if the user has not logged in, he cannot access the main page of the application!

So far, so good!

But then I thought about using the Interceptor in a "reverse" way, that is, if the user is already logged in to the session, he cannot access the login/registration page again before logging out.

You can do this with the Interceptor?

My client:

@Component
public class AutorizadorInterceptor extends HandlerInterceptorAdapter{

   @Override
   public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
       String uri = request.getRequestURI();
       if( uri.endsWith("login") || uri.endsWith("cadastro") || uri.endsWith("/") || uri.endsWith("css")){
           return true;
       } 


       if(request.getSession().getAttribute("usuarioLogado") != null) { 
           return true;
       }

       response.sendRedirect("login");
       return false;
   }
}

1 answer

0


Friend, I suggest using the default setting of Spring Security extending the class Websecurityconfigureradapter. Take a look at this tutorial from the link below, it is quite complete:

 @EnableWebSecurity
 public class SecurityWebConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {
      http
        .authorizeRequests()
            .antMatchers("/resources/**").permitAll() // aqui vc colocar teus CSS, JS            
            .anyRequest().authenticated() 
        .and()
        .formLogin()
            .loginPage("/login").permitAll();
    }
}

Source:

https://blog.algaworks.com/spring-security/

Browser other questions tagged

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