AuthenticationSuccessHandler Spring Security

时间:2016-03-29 13:41:59

标签: java spring spring-security spring-boot

我在Spring启动应用程序中使用了spring security,有两种类型的用户,一个ADMIN,一个是简单的用户,我从Datasource获取数据,然后执行Query,我的问题是重定向我每个用户一个不同的主页,我正在尝试使用AthenticationSuccessHandler,但它不会工作请帮助这是我的代码;

我的Spring安全类配置:

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)

}

}

这是我的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");
    }
}
}

这是控制台中的错误:

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

2 个答案:

答案 0 :(得分:11)

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");
        }
    }
}

你在successHandler类中错过了@compoment

答案 1 :(得分:2)

与其讨好AuthenticationSuccessHandler, 值得了解Spring安全角色检查配置:

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

或预先检查每个端点的角色:

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

}

其中默认角色前缀为ROLE_

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