Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,10 @@ dependencies {
// Swagger
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.0.1'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-api:3.0.1'

// Security
implementation 'org.springframework.boot:spring-boot-starter-security'
testImplementation 'org.springframework.security:spring-security-test'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,12 @@ public class Member extends BaseEntity {
@Column(name = "point", nullable = false)
private Integer point = 0;

@Column(name = "email", nullable = false, length = 50)
@Column(name = "email", nullable = false, unique = true, length = 50)
private String email;

@Column(name = "password", nullable = false)
private String password;

@Column(name = "phone_number", length = 11)
private String phoneNumber;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

import com.example.umc10th.domain.member.entity.Member;
import org.springframework.data.jpa.repository.JpaRepository;
// JpaRepository: save(), findById(), findAll(), delete() 등 기본 CRUD 기능 자동 제공

import java.util.Optional;

// JpaRepository: save(), findById(), findAll(), delete() 등 기본 CRUD 기능 자동 제공
public interface MemberRepository extends JpaRepository<Member, Long> {
Optional<Member> findByEmail(String email);
Comment on lines 9 to +10
boolean existsByEmail(String email);
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
import com.example.umc10th.domain.mission.repository.MissionRepository;
import com.example.umc10th.global.enums.Address;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
Expand All @@ -46,6 +47,7 @@ public class MemberService {
private final MemberTermRepository memberTermRepository;
private final MemberMissionRepository memberMissionRepository;
private final MissionRepository missionRepository;
private final PasswordEncoder passwordEncoder;

public MemberResDTO.MyPage getMyPage() {
Member member = memberRepository.findById(CURRENT_MEMBER_ID)
Expand All @@ -55,10 +57,15 @@ public MemberResDTO.MyPage getMyPage() {

@Transactional
public MemberResDTO.SignUp signUp(MemberReqDTO.SignUp dto) {
if (memberRepository.existsByEmail(dto.email())) {
throw new MemberException(MemberErrorCode.MEMBER_EMAIL_DUPLICATED);
}

Member member = Member.builder()
.name(dto.name())
.nickname(dto.nickname())
.email(dto.email())
.password(passwordEncoder.encode(dto.password()))
.socialUid(dto.email())
.socialType(SocialType.KAKAO)
.gender(parseGender(dto.gender()))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.example.umc10th.global.config;

import com.example.umc10th.global.security.handler.CustomAccessDeniedHandler;
import com.example.umc10th.global.security.handler.CustomAuthenticationEntryPoint;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@EnableWebSecurity
@Configuration
public class SecurityConfig {

private final String[] allowUris = {
// Swagger 허용
"/swagger-ui/**",
"/swagger-resources/**",
"/v3/api-docs/**",
// 회원가입, 로그인 허용
"/api/v1/auth/**"
};

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(requests -> requests
.requestMatchers(allowUris).permitAll()
.anyRequest().authenticated()
Comment on lines +29 to +33
)
Comment on lines +31 to +34
.formLogin(form -> form
.defaultSuccessUrl("/swagger-ui/index.html", true)
.permitAll()
)
.logout(logout -> logout
.logoutUrl("/logout")
.logoutSuccessUrl("/login?logout")
.permitAll()
)
// 에러 상황 핸들러
.exceptionHandling(exception -> exception
.accessDeniedHandler(customAccessDeniedHandler())
.authenticationEntryPoint(customAuthenticationEntryPoint())
);

return http.build();
}

@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public CustomAccessDeniedHandler customAccessDeniedHandler() {
return new CustomAccessDeniedHandler();
}

@Bean
public CustomAuthenticationEntryPoint customAuthenticationEntryPoint() {
return new CustomAuthenticationEntryPoint();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.umc10th.global.security.entity;

import com.example.umc10th.domain.member.entity.Member;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.springframework.lang.Nullable;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;

@Getter
@RequiredArgsConstructor
public class AuthMember implements UserDetails {

private final Member member;

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
return List.of();
}

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

@Override
public String getUsername() {
return member.getEmail();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.example.umc10th.global.security.handler;

import com.example.umc10th.global.apiPayload.ApiResponse;
import com.example.umc10th.global.apiPayload.code.BaseErrorCode;
import com.example.umc10th.global.apiPayload.code.GeneralErrorCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import java.io.IOException;

public class CustomAccessDeniedHandler implements AccessDeniedHandler {

@Override
public void handle(
HttpServletRequest request,
HttpServletResponse response,
AccessDeniedException accessDeniedException
) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
BaseErrorCode code = GeneralErrorCode.FORBIDDEN;
Comment on lines +22 to +23

// 응답 Content-Type, HTTP 상태코드 정의
response.setContentType("application/json;charset=UTF-8");
response.setStatus(code.getStatus().value());

// Response Body에 응답통일한 객체를 넣기
ApiResponse<Void> errorResponse = ApiResponse.onFailure(code, null);

// 실제 Response로 덮어쓰기
objectMapper.writeValue(response.getOutputStream(), errorResponse);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.example.umc10th.global.security.handler;

import com.example.umc10th.global.apiPayload.ApiResponse;
import com.example.umc10th.global.apiPayload.code.BaseErrorCode;
import com.example.umc10th.global.apiPayload.code.GeneralErrorCode;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import java.io.IOException;

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException
) throws IOException {
ObjectMapper objectMapper = new ObjectMapper();
Comment on lines +11 to +22
BaseErrorCode code = GeneralErrorCode.UNAUTHORIZED;

// 응답 Content-Type, HTTP 상태코드 정의
response.setContentType("application/json;charset=UTF-8");
response.setStatus(code.getStatus().value());

// Response Body에 응답통일한 객체를 넣기
ApiResponse<Void> errorResponse = ApiResponse.onFailure(code, null);

// 실제 Response로 덮어쓰기
objectMapper.writeValue(response.getOutputStream(), errorResponse);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.example.umc10th.global.security.service;

import com.example.umc10th.domain.member.entity.Member;
import com.example.umc10th.domain.member.repository.MemberRepository;
import com.example.umc10th.global.security.entity.AuthMember;
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;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

private final MemberRepository memberRepository;

@Override
public UserDetails loadUserByUsername(
String username
) throws UsernameNotFoundException {

Member member = memberRepository.findByEmail(username)
.orElseThrow(() -> new UsernameNotFoundException("존재하지 않는 회원입니다."));

return new AuthMember(member);
Comment on lines +22 to +26
}
}