it-source

인증스프링 보안의 성공 담당자

criticalcode 2023. 6. 20. 21:41
반응형

인증스프링 보안의 성공 담당자

Spring Boot 애플리케이션에서 Spring 보안을 사용해 본 적이 있는데, 두 가지 유형의 사용자가 있습니다. 하나는 관리자이고 다른 하나는 단순 사용자입니다.나는 a로부터 데이터를 얻습니다.DataSource그런 다음 SQL 쿼리를 실행합니다.

제 문제는 리디렉션입니다. 모든 사용자에 대해 다른 홈페이지를 가지고 있습니다.나는 사용하려고 노력하고 있습니다.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);
    }

}


그리고 이것은 의 인증입니다.성공 처리기:

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'인 빈을 만드는 동안 오류가 발생했습니다.security.config.config.confirmation.web.configuration.웹 보안 구성':자동 배선 종속성 주입에 실패했습니다.

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


성공 처리기 클래스의 주석을 놓쳤습니다.

서브캐싱보다는AuthenticationSuccessHandlerSpring 보안 역할 확인 구성에 대해 알아볼 가치가 있습니다.

@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

언급URL : https://stackoverflow.com/questions/36286112/authenticationsuccesshandler-in-spring-security

반응형