Java/Spring Boot Security

Spring boot Security DB 연동

바리새인 2024. 6. 9. 23:03

DB 연동 객체

@Data
public class Member {
	private String id;
	private String name;
	private String passwd;
}

@Service
public class MemberService {
	MemberMapper memberMapper;
	
	public MemberService(MemberMapper memberMapper) {
		this.memberMapper = memberMapper;
	}

	public List<Member> getMemberList() {
		return memberMapper.getMemberList();
	}
	
	public Member getMember(String id) {
		return memberMapper.getMember(id);
	}
	
	public int createMember(Member member) {
		return memberMapper.createMember(member);
	}
	
	public int updateMember(Member member) {
		return memberMapper.updateMember(member);
	}

	public int deleteMember(String id) {
		return memberMapper.deleteMember(id);
	}
}

@Mapper
public interface MemberMapper {
	Member getMember(String id);
	List<Member> getMemberList();
	int createMember(Member member);
	int updateMember(Member member);
	int deleteMember(String id);
}

Security 객체

public class UserPrincipal implements UserDetails{
	private Member member;
	
	public UserPrincipal(Member member) {
		this.member = member;
	}

	@Override
	public Collection<? extends GrantedAuthority> getAuthorities() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getPassword() {
		// TODO Auto-generated method stub
		return this.member.getPasswd();
	}

	@Override
	public String getUsername() {
		// TODO Auto-generated method stub
		return this.member.getId();
	}

	@Override
	public boolean isAccountNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		// TODO Auto-generated method stub
		return true;
	}

	@Override
	public boolean isEnabled() {
		// TODO Auto-generated method stub
		return true;
	}
}

@Service
public class MemberUserDetailService  implements UserDetailsService {

	@Autowired
	MemberMapper memberMapper;
	
	@Override
	public UserDetails loadUserByUsername(String id) throws UsernameNotFoundException {
		Member member =  memberMapper.getMember(id);
		if(member == null) {
			throw new UsernameNotFoundException("UsernameNotFoundException");
		}

		return new UserPrincipal(member);
	}
}

TS

  • There is no PasswordEncoder mapped for the id "null"

조회한 계정의 비밀번호가 DB 컬럼에 암호화 안된 상태에서 저장된 경우 발생
암호화 적용된 데이터의 앞부분에 '{bcrypt}'가 있어야 됨

# 수동으로 DB에 직접 데이터 입력시 아래 결과 앞에 '{bcrypt}'를 붙임
# 결과값이 항상 다름, 하지만 로그인하면 잘 됨
System.out.println(new BCryptPasswordEncoder().encode(member.getPasswd()))

# 비밀번호 수동 입력 쿼리
update member set
	passwd='{bcrypt}$2a$10$QLzj6IaRazYl9KQ8Mvzwl.PK4qn6GG8dXuWje9D8xBmcoh8jgAnlW'
where id='temp';

암호화 미적용
암호화 적용