본문 바로가기

STUDY/Spring

Spring Boot | Spring Security 한 유저에게 여러 Authority(ROLE) 부여하기 (UserDetails)

UsernamePasswordAuthenticationToken에서 계속 에러가 발생해서 아예 싹 뜯어 고쳤다..

 

현재 테이블 구조가 대충 이런식..

USERS테이블에 authority값을 두지 않고, authorities테이블을 따로 두어 참조하고 있음

CREATE TABLE `users` (
  `id` mediumint(9) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `password` varchar(500) DEFAULT NULL,
  `enabled` tinyint(4) DEFAULT NULL
  PRIMARY KEY (`id`)
)

CREATE TABLE `authorities` (
  `user_id` mediumint(9) DEFAULT NULL,
  `authority` varchar(45) DEFAULT NULL,
  KEY `fk_authorities_user_id_idx` (`user_id`)
)

 

1. CustomUserDetails 생성

UserDetails를 상속받아 User를 작성

@Data
@ToString
public class User implements UserDetails {
    private int id;
    private String username;
    private String password;
    private ArrayList<GrantedAuthority> authorities;
    private boolean enabled;

    @Override
    public String getUsername() {
        return username;
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        ArrayList<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(authorities);
        return authList;
    }
}

 

2. Mapper작성

해당 회원의 authority값을 받는 mapper를 작성해주고..

<select id="loadUserAuthorities" parameterType="Integer" resultType="String">
	select authority from authorities where user_id = #{user_id}
</select>

 

3. Service작성

이런식으로 서비스를 작성해주었음!

    public User findByPk(String user_id) {
        User user = userMapper.findByPk(user_id);
        user.setAuthorities(loadUserAuthorities(user.getId()));
        return user;
    }

    public ArrayList<GrantedAuthority> loadUserAuthorities(int user_id) {

        List<String> authorities = userMapper.loadUserAuthorities(user_id);
        ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();

        for (String auth: authorities) {
            grantedAuthorities.add(new SimpleGrantedAuthority(auth));
        }

        return grantedAuthorities;
    }

 

이제 잘 됨^-^...

 

+) 참고

 

Spring security : Multiple roles for a single user

My application needs me to define multiple roles for a single user . I have read Spring security with database and multiple roles? . Why should we implement our own UserDetails ? Existing one co...

stackoverflow.com