복붙노트

[SPRING] 스프링 : 스프링 보안 사용자에게 사용자 정의 세부 정보 추가

SPRING

스프링 : 스프링 보안 사용자에게 사용자 정의 세부 정보 추가

나는 현재 Spring MVC 애플리케이션에서 작업 중이며 로그인 할 때 (사용자 이름, 비밀번호, 사용자 정의 값 삽입) Spring Security 로그인 사용자 권한 필드에 사용자 정의 필드를 추가해야한다. 이 값은 사용자가 로그인 할 때 어디에서나 사용할 수 있어야합니다 (예 : pricipal.getValue를 통해).

나는 커스텀 사용자 클래스와 커스텀 서비스에 대해 많은 것을 읽었지만 내 문제에 대한 실질적인 해결책을 찾을 수 없다.

어떤 도움이 될거야!

해결법

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

    1.Avinash와 마찬가지로 User 클래스가 UserDetails를 구현하도록 만들고 UserDetailsService를 구현하고 해당 메서드를 재정의하여 사용자 정의 User 객체를 반환 할 수도 있습니다.

    Avinash와 마찬가지로 User 클래스가 UserDetails를 구현하도록 만들고 UserDetailsService를 구현하고 해당 메서드를 재정의하여 사용자 정의 User 객체를 반환 할 수도 있습니다.

    @Service("userDetailsService")
    public class MyUserDetailsService implements UserDetailsService {
    
        //get user from the database, via Hibernate
        @Autowired
        private UserDao userDao;
    
        @Transactional(readOnly=true)
        @Override
        public UserDetails loadUserByUsername(final String username)
            throws UsernameNotFoundException {
    //CUSTOM USER HERE vvv
            User user = userDao.findByUserName(username);
            List<GrantedAuthority> authorities =
                                          buildUserAuthority(user.getUserRole());
    //if you're implementing UserDetails you wouldn't need to call this method and instead return the User as it is
            //return buildUserForAuthentication(user, authorities);
    return user;
    
        }
    
        // Converts user to spring.springframework.security.core.userdetails.User
        private User buildUserForAuthentication(user,
            List<GrantedAuthority> authorities) {
            return new User(user.getUsername(), user.getPassword(),
                user.isEnabled(), true, true, true, authorities);
        }
    
        private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
    
            Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
    
            // add user's authorities
            for (UserRole userRole : userRoles) {
                setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
            }
    
            List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
    
            return Result;
        }
    
    }
    

    그리고 사용자 정의 UserdetailsService를 사용하여 WebConfigurerAdapter를 구성하면됩니다.

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    
        //authorization logic here ...
    }
    
        @Bean
        public PasswordEncoder passwordEncoder(){
            // return preferred PasswordEncoder ...//
        }
    
    
    }
    

    여기에 사용자 정의 UserDetails 구현 샘플이 있습니다. 사용자 정의 UserDetails

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

    2.UserDetails 인터페이스를 구현하는 클래스를 생성하십시오.

    UserDetails 인터페이스를 구현하는 클래스를 생성하십시오.

    public class User implements UserDetails {
        // Your user properties
        // implement methods
    }
    

    그런 다음 일단 인증되면 프로젝트의 모든 위치에서이 객체에 액세스 할 수 있습니다.

    User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    
  3. from https://stackoverflow.com/questions/41770156/spring-add-custom-user-details-to-spring-security-user by cc-by-sa and MIT license