복붙노트

[SPRING] 봄 보안 컨텍스트에 저장된 주 객체에 추가 세부 사항 추가하기

SPRING

봄 보안 컨텍스트에 저장된 주 객체에 추가 세부 사항 추가하기

Spring 3.0과 Spring Security 3을 사용하고 있습니다. Spring Security를 ​​사용하여 데이터베이스에 대해 사용자를 인증 할 수 있습니다. 사용 :

SecurityContextHolder.getContext().getAuthentication().getPrincipal()

현재 로그인 한 사용자의 사용자 이름을 검색 할 수 있습니다. Spring Security 컨텍스트에 저장된 주 객체에 대한 사용자 ID 및 모듈 액세스와 같은 추가 정보를 추가하여 나중에 검색 할 수 있습니다. 주요 개체에 추가 정보를 어떻게 추가 할 수 있으며 나중에 jsp 또는 java 클래스에서 어떻게 검색 할 수 있습니까? 가능한 경우 적절한 코드 스 니펫을 제공하십시오.

편집 : 내 데이터베이스에 액세스하려면 JDBC를 사용하고 있습니다.

미리 감사드립니다.

해결법

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

    1.인증 된 사용자에게 세부 정보를 추가하려면 Spring 보안 User 객체를 확장해야하는 User 객체의 구현을 먼저 만들어야합니다. 그런 다음 인증 된 사용자에게 추가하려는 등록 정보를 추가 할 수 있습니다. 이 작업이 완료되면 UserDetailService에서 사용자 객체의 구현을 반환해야합니다 (LDAP를 인증에 사용하지 않는 경우). 이 링크는 인증 된 사용자에게 세부 정보를 추가하는 데 필요한 세부 정보를 제공합니다.

    인증 된 사용자에게 세부 정보를 추가하려면 Spring 보안 User 객체를 확장해야하는 User 객체의 구현을 먼저 만들어야합니다. 그런 다음 인증 된 사용자에게 추가하려는 등록 정보를 추가 할 수 있습니다. 이 작업이 완료되면 UserDetailService에서 사용자 객체의 구현을 반환해야합니다 (LDAP를 인증에 사용하지 않는 경우). 이 링크는 인증 된 사용자에게 세부 정보를 추가하는 데 필요한 세부 정보를 제공합니다.

    http://javahotpot.blogspot.in/2013/12/spring-security-adding-more-information.html

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

    2.(기본 스프링 보안 설정이 작동하고 기본 컴포넌트가 어떻게 작동 하는지를 알고 있다고 가정합니다)

    (기본 스프링 보안 설정이 작동하고 기본 컴포넌트가 어떻게 작동 하는지를 알고 있다고 가정합니다)

    가장 "올바른"방법은 사용자 정의 인증 구현을 리턴하는 AuthenticationProvider의 자체 구현을 제공하는 것입니다. 그런 다음이 인증 인스턴스를 필요한 모든 항목으로 채울 수 있습니다. 예 :

    public class MyAuthentication extends UsernamePasswordAuthenticationToken implements Authentication {
    
        public MyAuthentication(Object principal, Object credentials, int moduleCode) {
            super(principal, credentials);
            this.moduleCode = moduleCode;
        }
    
        public MyAuthentication(Object principal, Object credentials,  Collection<? extends GrantedAuthority> authorities,int moduleCode) {
            super(principal, credentials, authorities);
            this.moduleCode = moduleCode;
        }
    
        private int moduleCode;
    
        public getModuleCode() {
            return moduleCode;
        }   
    }
    
    
    public class MyAuthenticationProvider extends DaoAuthenticationProvider {
    
        private Collection<GrantedAuthority> obtainAuthorities(UserDetails user) {
            // return granted authorities for user, according to your requirements
        }
    
        private int obtainModuleCode(UserDetails user) {
            // return moduleCode for user, according to your requirements
        }
    
        @Override
        public Authentication createSuccessAuthentication(Object principal, Authentication authentication, UserDetails user) {
            // Suppose this user implementation has a moduleCode property
            MyAuthentication result = new MyAuthentication(authentication.getPrincipal(),
                                                           authentication.getCredentials(),
                                                           obtainAuthorities(user),
                                                           obtainModuleCode(user));
            result.setDetails(authentication.getDetails());
            return result;
        }
    }
    

    그런 다음 applicationContext.xml에서 다음을 수행합니다.

    <authentication-manager>
        <authentication-provider ref="myAuthenticationProvider">
    </authentication-manager>
    
    <bean id="myAuthenticationProvider" class="MyAuthenticationProvider" scope="singleton">
        ...
    </bean>
    

    나는 당신이 AuthenticationDetails와 AuthenticationDetailsSource의 커스텀 구현을 제공함으로써 작동하도록 할 수 있다고 생각하지만, 이는 덜 깨끗한 접근이라고 생각한다.

  3. ==============================

    3.필요한 것은 다음과 같습니다.

    필요한 것은 다음과 같습니다.

    예를 들어

    public class CurrentUser extends User{
    
       //This constructor is a must
        public CurrentUser(String username, String password, boolean enabled, boolean accountNonExpired,
                boolean credentialsNonExpired, boolean accountNonLocked,
                Collection<? extends GrantedAuthority> authorities) {
            super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        }
        //Setter and getters are required
        private String firstName;
        private String lastName;
    
    }
    

    사용자 정의 사용자 상세 정보는 다음과 같습니다.

    @Service("userDetailsService")
    public class CustomUserDetailsService implements UserDetailsService {
    
    @Override
    public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {
    
        //Try to find user and its roles, for example here we try to get it from database via a DAO object
       //Do not confuse this foo.bar.User with CurrentUser or spring User, this is a temporary object which holds user info stored in database
        foo.bar.User user = userDao.findByUserName(username);
    
        //Build user Authority. some how a convert from your custom roles which are in database to spring GrantedAuthority
        List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
    
        //The magic is happen in this private method !
        return buildUserForAuthentication(user, authorities);
    
    }
    
    
    //Fill your extended User object (CurrentUser) here and return it
    private User buildUserForAuthentication(foo.bar.User user, 
    List<GrantedAuthority> authorities) {
        String username = user.getUsername();
        String password = user.getPassword();
        boolean enabled = true;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;
    
        return new CurrentUser(username, password, enabled, accountNonExpired, credentialsNonExpired,
                accountNonLocked, authorities);
       //If your database has more information of user for example firstname,... You can fill it here 
      //CurrentUser currentUser = new CurrentUser(....)
      //currentUser.setFirstName( user.getfirstName() );
      //.....
      //return currentUser ;
    }
    
    private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
    
        Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
    
        // Build user's authorities
        for (UserRole userRole : userRoles) {
            setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
        }
    
        return new ArrayList<GrantedAuthority>(setAuths);
    }
    
    }
    

    스프링 보안 컨텍스트 구성

    @Configuration
    @EnableWebSecurity
    @PropertySource("classpath://configs.properties")
    public class SecurityContextConfig extends WebSecurityConfigurerAdapter {
    
        @Autowired
        @Qualifier("userDetailsService")
        private UserDetailsService userDetailsService;
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService);
        }
    

    다 끝났어!

    (CurrentUser) getAuthentication (). getPrincipal ()을 호출하여 새로 CurrentUser를 얻거나 일부 속성을 설정할 수 있습니다.

  4. ==============================

    4.사용자가해야하는 "유일한"일은 UserDetails 객체의 구현을 반환하는 고유 한 UserDetailsService 구현을 만드는 것입니다.

    사용자가해야하는 "유일한"일은 UserDetails 객체의 구현을 반환하는 고유 한 UserDetailsService 구현을 만드는 것입니다.

    JPA 기반 UserDetailsService를 구현하는 자습서는 여기를 참조하십시오.

  5. from https://stackoverflow.com/questions/20349594/adding-additional-details-to-principal-object-stored-in-spring-security-context by cc-by-sa and MIT license