Java Spring Security 中的 AuthenticationSuccessHandler

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36286112/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:39:51  来源:igfitidea点击:

AuthenticationSuccessHandler in Spring Security

javaspringspring-securityspring-boot

提问by Kamel Mili

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.

我在 Spring Boot 应用程序中使用了 spring security,并且有两种类型的用户:一种是管理员,一种只是简单用户。我从 a 获取数据DataSource,然后执行 SQL 查询。

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.

我的问题是重定向:对于每个用户,我都有不同的主页。我正在尝试使用 to AthenticationSuccessHandler,但它不起作用。

Please help.

请帮忙。



My Spring security class configuration :

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

}


And this is my AuthenticationSuccessHandler:


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

org.springframework.beans.factory.BeanCreationException:创建名为“org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration”的bean时出错:自动装配依赖项的注入失败;

采纳答案by amani92

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 @Componentannotation in your success handler class.


您错过了@Component成功处理程序类中的注释。

回答by Black

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

而不是 sublcasing AuthenticationSuccessHandler,值得了解的是 Spring 安全角色检查配置:

@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_

其中默认角色前缀是 ROLE_

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

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