0

Spring 웹 응용 프로그램에 성공적으로 로그인 한 사용자에게 역할을 할당하려고합니다. LDAP 인증을 사용하고 있습니다.사용자가 Spring 보안에 로그인 할 때 그룹 이름을 기반으로 역할을 할당하는 방법

WebSecurityConfig.java

package com.logsniffer.web.util; 

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.web.builders.HttpSecurity; 
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; 
import org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider; 
import org.springframework.context.annotation.Bean; 
import org.apache.log4j.Logger; 
import org.springframework.security.core.Authentication; 
import org.springframework.core.env.Environment; 
import org.springframework.security.ldap.DefaultSpringSecurityContextSource; 
import org.springframework.security.core.context.SecurityContextHolder; 

@Configuration 
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Autowired 
    Environment env; 

    @Autowired 
    public void registerGlobalAuthentication(AuthenticationManagerBuilder auth) 
      throws Exception 
    { 
     if ("h2".equals(env.getProperty("spring.profiles.active"))) 
      return; 

     DefaultSpringSecurityContextSource context = new DefaultSpringSecurityContextSource("ldap://10.100.7.99:389/dc=ldap,dc=com"); 
     context.afterPropertiesSet(); 

     auth.ldapAuthentication() 
       .contextSource(context) 
       .userSearchFilter("uid={0}") 
       .userSearchBase("ou=support") 
     //   .groupSearchBase("ou=support") 
     //   .groupSearchFilter(String groupSearchFilter) 
       .groupRoleAttribute("cn") 
       .rolePrefix(""); 


    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .csrf().disable() 
       .authorizeRequests() 
//    .antMatchers("/", "/home").permitAll() 
       .anyRequest() 
       .authenticated() 
       .and() 
       .formLogin() 
       .permitAll(); 
     } 
} 

는 어쩌면 나는이 잘못 이해하고있다. 나는 사용을 생각했다

.groupRoleAttribute("cn") 

사용자 역할을 설정합니다. 그러나 사용자 권한을 인쇄하려고 할 때

Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
String r= authentication.getAuthorities().toString(); 
log.info("$$$$$$$$$$ " + r); 

나는 빈 문자열을 얻습니다. 내 LDAP 트리 나는 registerGlobalAuthentication 방법 prettry 확신 다음과 같은 구성

+--> dc=ldap,dc=com (1+) 
---> cn=admin 
---> ou=hr 
+--> ou=support (1+) 
| +--> cn=admin (2) 
| | ---> cn=kaushan deva 
| | ---> cn=sameera ramasinghe 
| | ---> Create new entry here 
| +--> cn=regular (1) 
| | ---> cn=chamitha abe 

을 가지고, 내가 사용자를 인증하기 위해 노력하고있어 방법은 잘못된 것입니다. 그래서 그룹 역할 속성을 설정할 수 없습니다. 그러나 나는 이것 때문에 매우 새로운 오류이기 때문에 오류를 찾을 수 없습니다.

내가 원하는 것은 그의 그룹 (또는 regular)을 기반으로 로그인하는 각 사용자에게 사용자 역할을 설정하는 것입니다.

+0

예 0입니다. 링크를 가져 주셔서 감사합니다. 나는 그것을 통과 할 것이다. 한편,이 질문에 대한 통찰력을 제공 할 수 있다면 좋을 것입니다. – SameeraR

답변

-2

Spring의 로그인 성공 처리기를 사용하여이를 수행 할 수 있습니다. 코드 예제 아래

@Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .formLogin() 
       .loginProcessingUrl("/app/url") 
       .usernameParameter("j_username") 
       .passwordParameter("j_password") 
       .successHandler(loginSuccessHandler) 
       .failureHandler(loginFailureHandler) 
       .permitAll() 
       .and() 
      .logout() 
       .logoutUrl("/app/logout") 
       .logoutSuccessHandler(ajaxLogoutSuccessHandler) 
       .deleteCookies("JSESSIONID") 
       .permitAll() 
       .and() 
      .csrf() 
       .disable() 
      .authorizeRequests() 
       .antMatchers("/resources/**").permitAll() 
       .antMatchers("/api/**").authenticated(); 
    } 

로그인 성공 처리기 :

@Component 
public class LoginSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { 

    @Override 
    public void onAuthenticationSuccess(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication) 
      throws IOException, ServletException { 
     User user =  (User)authentication.getPrincipal(); 
     String name = user.getUsername(); 
     //Your Code based on code and set role in Spring Security 
     response.setStatus(HttpServletResponse.SC_OK); 

    } 
} 
-1

두 번째 방법은 ApplicationDetailService과 같이 수행 할 수 있습니다

@Autowired 
    public void configureGlobal(AuthenticationManagerBuilder auth) 
      throws Exception { 
     auth.userDetailsService(userDetailsService).passwordEncoder(encryptDecrypt); 
    } 

은 ApplicatonDetailService :

@Service("userDetailsService") 
public class ApplicationUserDetailsService implements UserDetailsService { 

    @Transactional(readOnly = true) 
    public UserDetails loadUserByUsername(final String username) 
      throws UsernameNotFoundException { 

     com.your.User domainUser = userDAO.findByEmail(username); 

     List<GrantedAuthority> authList = getGrantedAuthorities(new SimpleGrantedAuthority("ROLE_ADMIN")); 
     return new User(domainUser.getEmail(), domainUser.getPassword(), 
      enabled, accountNonExpired, credentialsNonExpired, 
      accountNonLocked, authList); 

    } 
} 

님의 역할 기반 설정할 수 있습니다 콘디에 보조 :

List<GrantedAuthority> authList = getGrantedAuthorities(new SimpleGrantedAuthority("ROLE_ADMIN"));