PrincipalDetails.java
package com.codesign.base.auth;
import com.codesign.base.model.User;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import java.util.ArrayList;
import java.util.Collection;
@Data
public class PrincipalDetails implements UserDetails {
private User user;
public PrincipalDetails(User user) {
this.user = user;
}
@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> authorities = new ArrayList<>();
user.getRoleList().forEach(item -> {
authorities.add(() -> item);
});
return authorities;
}
@Override
public String getPassword() {
return user.getPassword();
}
@Override
public String getUsername() {
return user.getUsername();
}
@Override
public boolean isAccountNonExpired() {
return true;
}
@Override
public boolean isAccountNonLocked() {
return true;
}
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
public boolean isEnabled() {
return true;
}
}
@Override된 메서드들을 User객체에서 꺼내서 return 해준다.
@Override된 메서드들을 true로 변경해준다.
User.java
package com.codesign.base.model;
import lombok.Data;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Data
public class User {
private long id;
private String username;
private String password;
private String roles; // USER, ADMIN
public List<String> getRoleList(){
return this.roles.length() > 0 ? Arrays.asList(this.roles.split(",")) : Collections.emptyList();
}
}
PrincipalDetailsService.java
package com.codesign.base.auth;
import com.codesign.base.model.User;
import com.codesign.base.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
@Service
@RequiredArgsConstructor
@Slf4j
public class PrincipalDetailsService implements UserDetailsService {
private final UserService userService;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
log.info("========= oadUserByUsername =========");
User user = userService.findByUsername(username);
return new PrincipalDetails(user);
}
}
db에서 유저 정보를 조회해서 UserDetails
타입 객체로 return해준다.
참고
https://www.youtube.com/watch?v=GEv_hw0VOxE&list=PL93mKxaRDidERCyMaobSLkvSPzYtIk0Ah