Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AuthenticationSuccessHandler in Spring Security

I've used spring security in a Spring Boot application and there are 2 types of users: one is an ADMIN, and one just a simple user. I get the data from a DataSource, then I execute an SQL query.

My problem is with a redirection: for every user I have a different homepage. I'm trying to use to AthenticationSuccessHandler, but it won't work.

Please help.


My Spring security class configuration :

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.sql.DataSource;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    Securityhandler successHandler;

    // Pour l'authentification des Utilisateur de Table Utilisateur
    @Autowired  
    public void GlobalConfig(AuthenticationManagerBuilder auth,DataSource dataSource) throws Exception {
        auth.jdbcAuthentication()
            .dataSource(dataSource) 
            .usersByUsernameQuery("SELECT  \"Pseudo\" AS principal , \"Password\" AS  credentials , true FROM \"UTILISATEUR\" WHERE \"Pseudo\" =  ? ")
            .authoritiesByUsernameQuery("SELECT  u.\"Pseudo\" AS principal , r.role as role  FROM \"UTILISATEUR\" u ,\"Role\" r where u.id_role=r.id_role AND \"Pseudo\" = ?  ")
            .rolePrefix("_ROLE");
    }

    // ne pas appliqué la securité sur les ressources 
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
        .antMatchers("/bootstrap/**","/css/**");

    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()   
            .authorizeRequests()
            .anyRequest()   
                .authenticated()        
                .and()
                .formLogin()
                .loginPage("/login")
                .permitAll()
                .successHandler(successHandler);
    }

}


And this is my AuthenticationSuccessHandler:

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

public class Securityhandler implements AuthenticationSuccessHandler {

    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains("ROLE_Admin")) {
            response.sendRedirect("/admin/home.html");
        }
    }
}


And this is the error in the console:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration': Injection of autowired dependencies failed;

like image 332
Kamel Mili Avatar asked Mar 29 '16 13:03

Kamel Mili


People also ask

What is the use of spring boot security AuthenticationSuccessHandler interface?

Interface AuthenticationSuccessHandler. Strategy used to handle a successful user authentication. Implementations can do whatever they want but typical behaviour would be to control the navigation to the subsequent destination (using a redirect or a forward).

How do I install AuthenticationSuccessHandler?

Modify you applicationContext. In your applicationContext. xml, create a new bean containing our Custom AuthenticationSuccessHandler class. Next, add our custom authenticationsuccesshandler bean to our form login or create a new form login entity if you don't have one. form login is part of the http filter.

What are antMatchers in Spring Security?

The antMatchers() is a Springboot HTTP method used to configure the URL paths from which the Springboot application security should permit requests based on the user's roles. The antmatchers() method is an overloaded method that receives both the HTTP request methods and the specific URLs as its arguments.

What are levels of security in spring?

Apart from authentication, spring security also check authorization of the logged in user. After login which user is authorize to access the resource is done on the bases of user's ROLE. At the time of creating user in WebSecurityConfig class, we can specify user?


2 Answers

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class Securityhandler implements AuthenticationSuccessHandler {

     public void onAuthenticationSuccess(HttpServletRequest request,   HttpServletResponse response, Authentication authentication) throws IOException  {
        Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
        if (roles.contains("ROLE_ADMIN")) {
            response.sendRedirect("admin/home.html");
        }
    }
}


You've missed the @Component annotation in your success handler class.

like image 117
amani92 Avatar answered Oct 18 '22 18:10

amani92


Rather than sublcassing AuthenticationSuccessHandler, It's worth knowing about the Spring security role-checking config:

@Configuration
@EnableWebSecurity
public class SecSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
          .authorizeRequests()
          .antMatchers("/admin/**").hasRole("ADMIN");
    }
    ...
} 

OR pre-checking a Role per endpoint:

@Autowired
@PreAuthorize("hasRole('ADMIN')")
@RequestMapping("/")
public ModelAndView home(HttpServletRequest request) throws Exception {

}

where the default Role prefix is ROLE_

https://docs.spring.io/spring-security/site/docs/3.0.x/reference/el-access.html https://www.baeldung.com/spring-security-expressions-basic

like image 42
Black Avatar answered Oct 18 '22 16:10

Black