Day 개발 기록

[SpringBoot + Security + JWT + JPA ] 회원가입 , 로그인 구현하기-2 본문

Spring Security/security

[SpringBoot + Security + JWT + JPA ] 회원가입 , 로그인 구현하기-2

데이25 2023. 2. 1. 19:21

먼저, member 패키지를 만들고 Member.java 와 MemberRepository 를 만든다. 

 

Member.java

@Getter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Entity
public class Member implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String email;
    private String password;

    @ElementCollection(fetch = FetchType.EAGER)
    @Builder.Default
    private List<String> roles = new ArrayList<>();

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream()
                .map(SimpleGrantedAuthority::new)
                .collect(Collectors.toList());
    }

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

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

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

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

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

사용자는 email과 password를 입력해 회원가입하고 로그인 할 수 있다.

UserDetails를 implements 하여 오버라이드 한다. 

 

 

MemberRepository

import org.springframework.data.jpa.repository.JpaRepository;

import java.util.Optional;

public interface MemberRepository extends JpaRepository<Member, Long> {
    Optional<Member> findByEmail(String email);
}

 

config 밑에 service 패키지를 만들고 CustomUserDetailService.java 클래스를 만든다.

 

CustomUserDetailService.java

import com.demo.auth.member.MemberRepository;
import lombok.RequiredArgsConstructor;
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;

@RequiredArgsConstructor
@Service
public class CustomUserDetailService implements UserDetailsService {

    private final MemberRepository memberRepository;
    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        return memberRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("사용자를 찾을 수 없습니다."));
    }


}

 

이제 다시 프로젝트를 실행하고, localhost:8080/h2-console 에 접속해본다. 

 

다음과 같이 h2 database에 Member 와 Member_Roles 테이블이 잘 만들어진것을 확인할수있다.