2016-06-20 3 views
0

데이터베이스와 Ldap을 통해 사용자를 인증하기 위해 스프링 보안과 주석을 사용하고 있습니다. 즉, Ldap은 속성 검색을 허용하지 않기 때문에 Ldap 검색을 통해 사용자 (고유 코드)와 비밀번호가 올바른지 확인한 다음 내 데이터베이스를 사용하여 권한을로드합니다. 그래서 내 데이터베이스에있는 모든 사용자가 Ldap에 존재하지만, 사용자가 내 데이터베이스가 아닌 Ldap에 존재하면 특정 페이지를 보여줍니다. 이 실제 코드 :커스텀 사용자 데이터베이스를 통한 스프링 보안 인증

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true) 
@PropertySource(value = { "classpath:application.properties" }) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 


    @Autowired 
    AuthenticationConfiguration authenticationConfiguration; 

    @Configuration 
    protected static class AuthenticationConfiguration implements 
    AuthenticationProvider { 

     @Autowired 
     private UserServices userServices; 
     @Autowired 
     LdapServices ldapServices; 

     @Override 
     public Authentication authenticate(Authentication authentication) throws AuthenticationException { 
      Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 
      String name = authentication.getName(); 
      String password = authentication.getCredentials().toString(); 
      boolean isFind = ldapServices.ldapSearch(name, password);       
      if (isFind){ 
       com.domain.User user = userServices.getByUsersEnabled(name); 
       if (user!=null) 
        authorities.add(new SimpleGrantedAuthority("ROLE_"+user.getRole().getRole()));   
       return new UsernamePasswordAuthenticationToken(name, password, authorities); 
      }   
      else return null; 
     } 


     @Override 
     public boolean supports(Class<?> authentication) { 
      return authentication.equals(UsernamePasswordAuthenticationToken.class); 
     } 
    } 

    @Autowired 
    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.authenticationProvider(authenticationConfiguration); 
     } 

...web services authentication 

나는 간단한 사용자가 내가 이름/성 및 이메일과 같은 몇 가지 정보를 추가하고 싶습니다. UserDetailsloadUserByUsernameUserDetailsService 인터페이스로 구현해야한다는 것을 알았지 만, loadUserByUsername을 내 코드와 어떻게 병합 할 수 있습니까? 이렇게하면 사용자 코드 대신 이름과 성을 표시 할 수 있습니다. 감사합니다

답변

0

나는 return new UsernamePasswordAuthenticationToken(user, password, authorities);return new UsernamePasswordAuthenticationToken(name, password, authorities);을 변경하고 내 HTML 페이지에서 내가 이름 매개 변수를 검색 할 수 sec:authentication="principal.name"를 사용

0

나 또한 비슷한 문제에 약간의 문제가 발생 한 후, 나는 내가 그것을 얻을하는 데 도움이 좋은 기사를 발견 끝난. 기사는 여기에 있습니다 : spring-ldap-custom-authorities

나는 그것이 도움이 되길 바랍니다. 기본적으로 LDAP 서버에서 인증 프로세스를 수행해야하며 나중에 사용자 정보를 얻을 수 있도록 "CustomLdapAuthoritiesPopulator"을 만들어야합니다.

<beans:bean id="ldapAuthProvider" 
    class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider"> 
    <beans:constructor-arg> 
     <beans:bean 
      class="org.springframework.security.ldap.authentication.BindAuthenticator"> 
      <beans:constructor-arg ref="contextSource" /> 
      <beans:property name="userSearch" ref="userSearch" /> 
     </beans:bean> 
    </beans:constructor-arg> 
    <beans:constructor-arg> 
     <!-- User roles --> 
     <beans:bean class="com.company.package.CustomLdapAuthoritiesPopulator" /> 
    </beans:constructor-arg> 
</beans:bean> 

을 그리고 나중에 CustomLdapAuthoritiesPopulator에 당신은 사용자 rolers 다룰 것입니다 :

당신은 당신의 XML에 이런 일을 할 것입니다. 다음과 같은 내용 :

@Service("myAuthPopulator") 
public class CustomLdapAuthoritiesPopulator implements LdapAuthoritiesPopulator { 
    @Transactional(readOnly=true) 
    @Override 
    public Collection<? extends GrantedAuthority> getGrantedAuthorities(DirContextOperations userData, String username) { 

     Set<GrantedAuthority> authorities = new HashSet<GrantedAuthority>(); 
     try { 

      User user = userService.findUserByUsername(username); 

      if (user == null) { 
       // User doesn't exist in the database 
      } else { 

       // user exists 

       //get roles 
       Set<UserRole> userRoles = user.getUserRoles(); 

       //add roles 
       for (UserRole userRole : userRoles) { 
        authorities.add(new SimpleGrantedAuthority(userRole.getRole())); 
       } 

       return authorities; 
      } 
     } catch(Exception e) { 
      //exception 
     } 
     return authorities; 
    } 

} 
+0

이 링크는 질문에 대한 답변 일지 모르지만 여기에 답변의 핵심 부분을 포함하고 참조 할 수있는 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않게 될 수 있습니다. - [리뷰에서] (리뷰/저품절 포스트/17660666) –

+0

안녕하세요 @ ProkashSarkar, 답장을 보내 주셔서 감사합니다. 나는 대답을 편집하고 그것에 약간의 코드를 추가했다. 나는 그것이 지금 더 낫다고 생각한다. –

관련 문제