Skip to content

Commit

Permalink
[feat] 시큐리티 추가 중 #55
Browse files Browse the repository at this point in the history
  • Loading branch information
LeeVell committed Dec 27, 2024
1 parent 66392ac commit c85dc0f
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 23 deletions.
48 changes: 29 additions & 19 deletions src/main/java/org/team10/washcode/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,41 +1,51 @@
package org.team10.washcode.config;

import lombok.AllArgsConstructor;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
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.core.userdetails.UserDetailsService;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.team10.washcode.jwt.CustomUserDetails;
import org.team10.washcode.jwt.JwtAuthenticationFilter;
import org.team10.washcode.jwt.JwtProvider;

import java.io.IOException;
import java.util.List;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final UserDetailsService userDetailsService;

private final JwtProvider jwtProvider;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
http
.csrf().disable()
.cors().and() // CORS 설정 추가
.authorizeHttpRequests(auth -> auth
// .requestMatchers("/api/**").permitAll()
// .requestMatchers("/swagger-ui/**").permitAll()
// .requestMatchers("/v3/api-docs/**").permitAll()
// .requestMatchers("/").permitAll()
// .anyRequest().authenticated()
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return
http
.csrf(AbstractHttpConfigurer::disable)
.formLogin(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable)
.cors(AbstractHttpConfigurer::disable)
.headers(header -> header.frameOptions(HeadersConfigurer.FrameOptionsConfig::disable))
.authorizeHttpRequests((auth) -> auth
.requestMatchers("/WEB-INF/view/**","/upload/**","/error","/swagger-ui/**", "/v3/api-docs/**").permitAll()
.requestMatchers("/","/register","/api/user/login","/login").permitAll()
.requestMatchers("/main").permitAll()
.requestMatchers("/api/user/address").permitAll()
.dispatcherTypeMatchers(jakarta.servlet.DispatcherType.FORWARD).permitAll()
.dispatcherTypeMatchers(jakarta.servlet.DispatcherType.INCLUDE).permitAll()
.anyRequest().permitAll()
)
.addFilterBefore(new JwtAuthenticationFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class);

return http.build();

)
//.addFilterBefore(new JwtAuthenticationFilter(jwtProvider), UsernamePasswordAuthenticationFilter.class)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package org.team10.washcode.jwt;

import io.jsonwebtoken.JwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
Expand All @@ -9,22 +10,26 @@
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.team10.washcode.Enum.UserRole;

import java.io.IOException;
import java.util.List;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

private final JwtProvider jwtProvider;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

String accessToken = jwtProvider.resolveAccessToken(request);
// 1-1. 유효한 토큰인지 확인
if(accessToken!=null && jwtProvider.validateToken(accessToken)){
// 2. 유저정보 저장
// 1-1. 유효한 토큰인지 확인
if(accessToken!=null && jwtProvider.validateToken(accessToken)) {
// 2. 유저정보 저장
this.setAuthentication(accessToken);
}
filterChain.doFilter(request,response);
Expand Down
15 changes: 14 additions & 1 deletion src/main/java/org/team10/washcode/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,17 @@
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseCookie;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.team10.washcode.RequestDTO.user.LoginReqDTO;
import org.team10.washcode.RequestDTO.user.RegisterReqDTO;
import org.team10.washcode.RequestDTO.user.UserUpdateReqDTO;
import org.team10.washcode.ResponseDTO.user.UserProfileResDTO;
import org.team10.washcode.entity.User;
import org.team10.washcode.jwt.CustomUserDetails;
import org.team10.washcode.jwt.JwtProvider;
import org.team10.washcode.repository.UserRepository;

Expand Down Expand Up @@ -63,7 +68,9 @@ public ResponseEntity<?> signup(RegisterReqDTO registerReqDTO){
user.setAddress(registerReqDTO.getAddress());
user.setPhone(registerReqDTO.getPhone());
user.setRole(registerReqDTO.getRole());
user.setKakao_id(registerReqDTO.getKakao_id());
if(registerReqDTO.getKakao_id()!=null) {
user.setKakao_id(registerReqDTO.getKakao_id());
}

userRepository.save(user);

Expand All @@ -85,6 +92,7 @@ public ResponseEntity<?> login(LoginReqDTO loginReqDTO){
return ResponseEntity.status(400).body("잘못된 비밀번호 입니다.");
}


User user = userRepository.findByEmail(loginReqDTO.getEmail()).orElseThrow(() -> new RuntimeException("해당 계정을 찾을 수 없습니다."));

String accessToken = jwtProvider.generateAccessToken(user.getId(),user.getRole());
Expand All @@ -95,6 +103,11 @@ public ResponseEntity<?> login(LoginReqDTO loginReqDTO){

ResponseCookie refreshCookie = getRefreshToken(refreshToken);

UserDetails userDetails = new CustomUserDetails(user.getId(), user.getRole());
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails.getUsername(),null,userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

return ResponseEntity
.ok()
.header(HttpHeaders.SET_COOKIE, refreshCookie.toString())
Expand Down

0 comments on commit c85dc0f

Please sign in to comment.