Skip to content

Commit

Permalink
[LINKER-99] Token기반 인증 FIlter 설정 추가 (#31)
Browse files Browse the repository at this point in the history
* [LINKER-X] fix: 회원가입 API 삭제

* [LINKER-X] feat: Filter 설정
  • Loading branch information
ktj1997 authored Jan 27, 2024
1 parent b7590de commit ca8894c
Show file tree
Hide file tree
Showing 7 changed files with 56 additions and 49 deletions.
Original file line number Diff line number Diff line change
@@ -1,35 +1,52 @@
package com.imlinker.coreapi.configuration;

import com.imlinker.coreapi.core.auth.security.jwt.JwtAuthenticationFilter;
import com.imlinker.coreapi.core.auth.security.jwt.JwtTokenProperties;
import com.imlinker.coreapi.core.auth.security.jwt.JwtTokenProvider;
import com.imlinker.coreapi.core.auth.security.jwt.TokenProperties;
import com.imlinker.coreapi.core.auth.security.oauth2.*;
import com.imlinker.coreapi.support.exception.FilterExceptionHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
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.configuration.WebSecurityCustomizer;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
@EnableConfigurationProperties({JwtTokenProperties.class, TokenProperties.class})
public class SecurityConfiguration {
private final JwtTokenProvider jwtTokenProvider;
private final FilterExceptionHandler filterExceptionHandler;
private final CustomOAuth2UserService customOAuth2UserService;
private final CustomAccessDeniedHandler customAccessDeniedHandler;
private final CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
private final CustomAuthenticationSuccessHandler customAuthenticationSuccessHandler;
private final CustomAuthorizationRequestResolver customOAuth2AuthorizationRequestResolver;

private final String[] ignoredPath = {
"/ping",
"/error-types",
"/favicon.ico",
"/v3/api-docs/**",
"/swagger-resources/**",
"/swagger-ui/**",
"/webjars/**",
"/swagger/**"
};

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable)
.httpBasic(AbstractHttpConfigurer::disable);

// oAuthHandler
http.oauth2Login(
loginHandler ->
loginHandler
Expand All @@ -41,27 +58,29 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
authorizationEndpoint.authorizationRequestResolver(
customOAuth2AuthorizationRequestResolver)));

// SpringSecurity ExceptionHandler
http.exceptionHandling(
exceptionHandling ->
exceptionHandling
.accessDeniedHandler(customAccessDeniedHandler)
.authenticationEntryPoint(customAuthenticationEntryPoint));

http.authorizeHttpRequests(authorizeRequests -> authorizeRequests.anyRequest().permitAll());
// Authorization Check
http.authorizeHttpRequests(
authorization ->
authorization
.requestMatchers(ignoredPath)
.permitAll()
.requestMatchers("/oauth2/**")
.permitAll()
.anyRequest()
.authenticated());

return http.build();
}
// CustomFilter
http.addFilterBefore(
new JwtAuthenticationFilter(jwtTokenProvider, filterExceptionHandler),
UsernamePasswordAuthenticationFilter.class);

@Bean
public WebSecurityCustomizer webSecurityCustomizer() {
return (web) ->
web.ignoring()
.requestMatchers(
"/v3/api-docs/**",
"/swagger-resources/**",
"/swagger-ui/**",
"/webjars/**",
"/swagger/**",
"/favicon.ico");
return http.build();
}
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,10 @@
package com.imlinker.coreapi.core.auth.controller;

import com.imlinker.coreapi.core.auth.controller.request.SignUpRequest;
import com.imlinker.coreapi.support.response.ApiResponse;
import com.imlinker.enums.OperationResult;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/v1/auth")
@Tag(name = "Auth API", description = "인증 관련 API")
public class AuthController {

@PostMapping("/sign-up")
@Operation(summary = "회원가입 하기")
public ApiResponse<OperationResult> signUp(@RequestBody SignUpRequest request) {
return ApiResponse.success(OperationResult.SUCCESS);
}
}
public class AuthController {}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,17 @@
import com.imlinker.error.ErrorType;
import io.jsonwebtoken.Claims;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.GenericFilterBean;

@Slf4j
@AllArgsConstructor
public class JwtAuthenticationFilter extends GenericFilterBean {

Expand All @@ -23,23 +24,22 @@ public class JwtAuthenticationFilter extends GenericFilterBean {
@Override
public void doFilter(
ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
throws IOException {
try {
String token = ((HttpServletRequest) servletRequest).getHeader("Authorization");
if (token != null) {
if (token != null && token.startsWith("Bearer ")) {
log.info("[인증필터][시작] token: {}", token);
Claims claims =
jwtTokenProvider.parseClaims(token.replace("Bearer ", ""), TokenType.ACCESS_TOKEN);
if (claims != null) {
SecurityContextHolder.getContext()
.setAuthentication(jwtTokenProvider.generateAuthentication(claims));
}
}

filterChain.doFilter(servletRequest, servletResponse);
} catch (Exception e) {
filterExceptionHandler.sendErrorMessage(
(HttpServletResponse) servletResponse, ErrorType.INTERNAL_PROCESSING_ERROR, e.getCause());
}
filterChain.doFilter(servletRequest, servletResponse);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public class JwtTokenProvider {
private final JwtTokenProperties jwtTokenProperties;
private final FilterExceptionHandler filterExceptionHandler;

public String generateToken(Email email, TokenType tokenType) {
public String generateToken(Long id, Email email, TokenType tokenType) {
JwtTokenProperties.TokenProperties properties =
tokenType == TokenType.ACCESS_TOKEN
? jwtTokenProperties.getAccess()
Expand All @@ -36,6 +36,7 @@ public String generateToken(Email email, TokenType tokenType) {
Instant expire = now.plus(properties.getExpire(), ChronoUnit.MILLIS);

return Jwts.builder()
.claim("id", id)
.claim("email", email.getValue())
.setIssuedAt(Date.from(now))
.setExpiration(Date.from(expire))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.imlinker.domain.auth.OAuthVendor;
import com.imlinker.domain.common.Email;
import com.imlinker.domain.common.URL;
import com.imlinker.domain.user.User;
import com.imlinker.domain.user.UserService;
import com.imlinker.error.ApplicationException;
import com.imlinker.error.ErrorType;
Expand Down Expand Up @@ -68,8 +69,11 @@ public void onAuthenticationSuccess(
userService.createUser(oAuthId, nickname, email, profileImgUrl, oAuth2User.getVendor());
}

String accessToken = jwtTokenProvider.generateToken(email, TokenType.ACCESS_TOKEN);
String refreshToken = jwtTokenProvider.generateToken(email, TokenType.REFRESH_TOKEN);
User user = userService.findByOAuthInfo(oAuth2User.getVendor(), oAuthId);
String accessToken =
jwtTokenProvider.generateToken(user.getId(), email, TokenType.ACCESS_TOKEN);
String refreshToken =
jwtTokenProvider.generateToken(user.getId(), email, TokenType.REFRESH_TOKEN);

String redirectUri =
String.format(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.imlinker.domain.auth.OAuthVendor;
import com.imlinker.domain.common.Email;
import com.imlinker.domain.common.URL;
import com.imlinker.error.ApplicationException;
import com.imlinker.error.ErrorType;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
Expand All @@ -13,6 +15,12 @@
public class UserService {
private final UserRepository userRepository;

public User findByOAuthInfo(OAuthVendor oAuthVendor, String oAuthIdentifier) {
return userRepository
.findByOAuthVendorAndOAuthIdentifier(oAuthVendor, oAuthIdentifier)
.orElseThrow(() -> new ApplicationException(ErrorType.USER_NOT_FOUND));
}

public boolean isMember(OAuthVendor oAuthVendor, String oAuthIdentifier) {
return userRepository
.findByOAuthVendorAndOAuthIdentifier(oAuthVendor, oAuthIdentifier)
Expand Down

0 comments on commit ca8894c

Please sign in to comment.