인프런 커뮤니티 질문&답변

qheogus55님의 프로필 이미지

작성한 질문수

스프링부트 시큐리티 & JWT 강의

스프링부트 시큐리티 27강 - jwt토큰 서버 구축 완료

안녕하세요 강사님! 질문있습니다.!

23.05.15 07:21 작성

·

497

0

강의 에서는 User 객체에 String roles를 만들고

PrincipalDetailse 객체의 getAuthorities함수에서 밑에 처럼 진행하였는데요

    public PrincipalDetails(Customer customer) {
        this.customer = customer;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        customer.getRoleList().forEach(r -> {
            authorities.add(() -> r);
        });
        return authorities;
    }

User객체의 Role role 필드를 추가하여

public enum Role {
    ROLE_CUSTOMER,ROLE_ADMIN,ROLE_SELLER
}

PrincipalDetailse 객체의 getAuthorities함수 적는방법이 도무지 생각나지 않아 질문드립니다 ㅠ 어떻게 해야할까요.. 도움 구하고싶습니다,

답변 2

1

최주호님의 프로필 이미지
최주호
지식공유자

2023. 05. 17. 13:53

package com.example.kakao.users;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Converter
public class StringArrayConverter implements AttributeConverter<List<String>, String> {

    private static final String SPLIT_CHAR = ",";

    @Override
    public String convertToDatabaseColumn(List<String> attribute) {
        return attribute.stream().map(String::valueOf).collect(Collectors.joining(SPLIT_CHAR));
    }

    @Override
    public List<String> convertToEntityAttribute(String dbData) {
        if(dbData == null) { // JPA save는 select부터 하기 때문에, null을 체크해줘야 한다.
            return Collections.emptyList();
        } else {
            return Arrays.stream(dbData.split(SPLIT_CHAR))
                    .map(String::valueOf)
                    .collect(Collectors.toList());
        }
    }
}

 

package com.example.kakao.users;

import lombok.*;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
@Entity
@Table(name="user_tb")
public class User{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String email; // 인증시 필요한 필드
    private String password;
    private String username;

    @Convert(converter = StringArrayConverter.class)
    private List<String> roles = new ArrayList<>(); // role은 한 개 이상

    @Builder
    public User(int id, String email, String password, String username, List<String> roles) {
        this.id = id;
        this.email = email;
        this.password = password;
        this.username = username;
        this.roles = roles;
    }
}
package com.example.kakao._core.security;

import com.example.kakao.users.User;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.stream.Collectors;

@RequiredArgsConstructor
@Getter
public class CustomUserDetails implements UserDetails {

    private final User user;

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

    @Override
    public String getPassword() {
        return user.getPassword();
    }

    @Override
    public String getUsername() {
        return user.getEmail();
    }

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

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

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

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

 

 

 

 

 

 

0

qheogus55님의 프로필 이미지
qheogus55
질문자

2023. 05. 18. 03:41

public enum Role {
    ROLE_CUSTOMER,
    ROLE_SELLER;
}
//
public class Customer extends BaseTimeEntity {

   @Enumerated(EnumType.STRING)
    private Role role;

}

 

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new GrantedAuthority() {
            @Override
            public String getAuthority() {
                return customer.getRole().toString();
            }
        });
        return authorities;
    }
    @Override
    public void signUpCustomer(CustomerSignUpDto customerSignUpDto) throws Exception {
        Customer customer = customerSignUpDto.toEntity();
        customer.encodePassword(passwordEncoder);
        customer.addCustomerAuthority();

        if (customerRepository.findByUsername(customer.getUsername()).isPresent()) {
            throw new Exception("이미 존재하는 아이디입니다.");
        }
        customerRepository.save(customer);
    }
    public void addSellerAuthority(){
        this.role = Role.ROLE_SELLER;
    }

답변 매우감사드립니다!!

혹시 이 코드도 제대로 동작하는데 문제없을까요?..