복붙노트

[SPRING] 스프링 보안 3 Active Directory 인증, 데이터베이스 인증

SPRING

스프링 보안 3 Active Directory 인증, 데이터베이스 인증

나는 AD 인증으로 내 응용 프로그램에 액세스하고 내 DB에서 권한 부여 역할을 얻으려고합니다.

이것이 내 구성이다.

<beans:bean id="activeDirectoryAuthenticationProvider"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
    <beans:constructor-arg value="mydomain" />
    <beans:constructor-arg value="ldap://my URL :389" />
    <beans:property name="convertSubErrorCodesToExceptions" value="true"/>
</beans:bean>

나는 추가하려고 시도했다.

  <beans:constructor-arg>
    <beans:bean class="org.springframework.security.ldap.populator.UserDetailsServiceLdapAuthoritiesPopulator">
      <beans:constructor-arg ref="myUserDetailsService"/>
    </beans:bean>
  </beans:constructor-arg>

그러나 그것은 작동하지 않았다. 어떤 도움이 필요합니까?

많은 감사합니다 !!

해결법

  1. ==============================

    1.ActiveDirectoryLdapAuthenticationProvider는 LdapAuthoritiesPopulator를 사용하지 않습니다 (생성자에 대해 API를 확인하십시오).

    ActiveDirectoryLdapAuthenticationProvider는 LdapAuthoritiesPopulator를 사용하지 않습니다 (생성자에 대해 API를 확인하십시오).

    공급자가 포함 된 새 토큰을 반환하기 전에 공급자를 래핑하고 별도의 권한을로드하는 위임 모델을 사용할 수 있습니다.

    public class MyAuthoritySupplementingProvider implements AuthenticationProvider {
        private AuthenticationProvider delegate;
    
        public MyAuthoritySupplementingProvider(AuthenticationProvider delegate) {
            this.delegate = delegate;
        }
    
        public Authentication authenticate(Authentication authentication) {
            final Authentication a = delegate.authenticate(authentication);
    
            // Load additional authorities and create an Authentication object
            final List<GrantedAuthority> authorities = loadRolesFromDatabaseHere(a.getName());
    
            return new AbstractAuthenticationToken(authorities) {
                public Object getCredentials() {
                    throw new UnsupportedOperationException();
                }
    
                public Object getPrincipal() {
                    return a.getPrincipal();
                }
            };
        }
    
        @Override
        public boolean supports(Class<?> authentication) {
            return delegate.supports(authentication);
        }
    }
    

    이 클래스는 주로 Active Directory에 대한 기본적인 지식과 사람들이 사용하고자하는 다양한 방법으로 인해 최종 결정됩니다.

  2. ==============================

    2.이것을 두 부분으로 나누십시오. 첫 번째는 스프링 보안 xml 구성이고 두 번째 부분은 스프링 보안이 제공하는 UserContextMapper를 재정의합니다.

    이것을 두 부분으로 나누십시오. 첫 번째는 스프링 보안 xml 구성이고 두 번째 부분은 스프링 보안이 제공하는 UserContextMapper를 재정의합니다.

    보안 xml 구성은 다음과 같습니다.

    <bean id="adAuthenticationProvider"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
       <constructor-arg value="my.domain.com" />
        <constructor-arg value="ldap://<adhostserver>:<port>/" />
        <property name="convertSubErrorCodesToExceptions" value="true" />
        <property name="userDetailsContextMapper" ref="myUserDetailsContextMapper" />
    </bean>
    
    <bean id="myUserDetailsContextMapper" class="com.mycompany.sme.workflow.controller.MyDbAuthorizationFetcher">
    <property name="dataSource" ref="dataSource" />
    

    MyDbAuthorizationFetcher는 UserContextMapper 클래스를 구현하여 DB에서 권한을 가져 오는 클래스입니다.

    public class MyDbAuthorizationFetcher implements UserDetailsContextMapper {
    
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DataSource dataSource;
    
    public JdbcTemplate getJdbcTemplate() {
        return jdbcTemplate;
    }
    
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    
    public DataSource getDataSource() {
        return dataSource;
    }
    
    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }
    
    // populating roles assigned to the user from AUTHORITIES table in DB
    private List<SimpleGrantedAuthority> loadRolesFromDatabase(String username) {
    
        DbRole role = new DbRole();
        String sql = "select * from user where user_id = ?";
        jdbcTemplate = new JdbcTemplate(getDataSource());
        role = jdbcTemplate.queryForObject(sql, new Object[] { username }, new DbRoleMapper());
    
    
        try {
            dataSource.getConnection().setAutoCommit(true);
        } catch (SQLException e) {
    
        }
        List<SimpleGrantedAuthority> authoritiess = new ArrayList<SimpleGrantedAuthority>();
        SimpleGrantedAuthority auth = new SimpleGrantedAuthority(String.valueOf(role.getRoleId()));
        authoritiess.add(auth);
        return authoritiess;
    
       }
    
    @Override
    public UserDetails mapUserFromContext(DirContextOperations ctx,
            String username, Collection<? extends GrantedAuthority> authorities) {
    
        List<SimpleGrantedAuthority> allAuthorities = new ArrayList<SimpleGrantedAuthority>();
          for (GrantedAuthority auth : authorities) {
            if (auth != null && !auth.getAuthority().isEmpty()) {
               allAuthorities.add((SimpleGrantedAuthority) auth);
            }
          }
          // add additional roles from the database table
          allAuthorities.addAll(loadRolesFromDatabase(username));
          return new User(username, "", true, true, true, true, allAuthorities);
    }
    
    @Override
    public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
        // TODO Auto-generated method stub
    }
    
    }
    
  3. ==============================

    3.AbstractAuthenticationToken에서 인증 된 플래그를 true로 설정해야합니다. 그렇지 않으면 성공으로 간주하지 않습니다.

    AbstractAuthenticationToken에서 인증 된 플래그를 true로 설정해야합니다. 그렇지 않으면 성공으로 간주하지 않습니다.

  4. from https://stackoverflow.com/questions/9228932/spring-security-3-active-directory-authentication-database-authorization by cc-by-sa and MIT license