Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

시큐리티 /access-token로 바뀐 url에 permitAll, 로그인 시 리프레시 토큰 무조건 새로 발급 #129

Merged
merged 4 commits into from
Nov 29, 2023
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
@Service
@RequiredArgsConstructor
public class MemberValidator {
private MemberRepository memberRepository;
private final MemberRepository memberRepository;

public void validateEmailDuplication(String email) {
if (memberRepository.existsByEmail(email)) {
throw new Exception400("존재하는 이메일 입니다.");
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package com.timcooki.jnuwiki.domain.security.config;

import com.timcooki.jnuwiki.domain.security.service.MemberSecurityService;
import com.timcooki.jnuwiki.util.errors.exception.Exception401;
import com.timcooki.jnuwiki.util.errors.exception.Exception403;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
Expand All @@ -17,7 +22,9 @@
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.HandlerExceptionResolver;

@Slf4j
@EnableWebSecurity
@Configuration
@RequiredArgsConstructor
Expand All @@ -34,7 +41,8 @@ public void configure(HttpSecurity http) throws Exception {
}

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity,
@Autowired @Qualifier("handlerExceptionResolver") final HandlerExceptionResolver resolver) throws Exception {
return httpSecurity
.httpBasic()
.disable()
Expand All @@ -48,11 +56,23 @@ public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws
.and()
.apply(new CustomSecurityFilterManager())

.and()
.exceptionHandling().authenticationEntryPoint((request, response, authException) -> {
log.info("{}, {}", request.getRemoteAddr(), authException.getMessage());
resolver.resolveException(request, response, null, new Exception401("인증되지 않은 사용자입니다."));
})

.and()
.exceptionHandling().accessDeniedHandler((request, response, accessDeniedException) -> {
log.info("{}, {}", request.getRemoteAddr(), accessDeniedException.getMessage());
resolver.resolveException(request, response, null, new Exception403("접근 권한이 없습니다."));
})

.and()
.authorizeRequests()
.antMatchers(HttpMethod.GET, "/docs/**").permitAll()

.antMatchers("/members/join", "/members/login", "/members/refresh-token", "/members/check/**")
.antMatchers("/members/join", "/members/login", "/members/access-token", "/members/check/**")
.permitAll()

.antMatchers("/swagger-ui/**", "/v3/**")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
package com.timcooki.jnuwiki.domain.security.config;


import static com.timcooki.jnuwiki.domain.security.config.JwtProvider.cutTokenPrefix;

import com.timcooki.jnuwiki.domain.member.entity.Member;
import com.timcooki.jnuwiki.domain.member.entity.MemberRole;
import com.timcooki.jnuwiki.util.TimeFormatter;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.MalformedJwtException;
Expand Down Expand Up @@ -42,9 +41,8 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
}

try {
String token = cutTokenPrefix(bearerToken);
String email = (String) JwtProvider.getClaims(token).get("memberEmail");
MemberRole memberRole = MemberRole.valueOf((String) JwtProvider.getClaims(token).get("memberRole"));
String email = (String) JwtProvider.getClaims(bearerToken).get("memberEmail");
MemberRole memberRole = MemberRole.valueOf((String) JwtProvider.getClaims(bearerToken).get("memberRole"));
log.info("email: {}, role: {}", email, memberRole);

MemberDetails userDetails = new MemberDetails(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ public static String cutTokenPrefix(String bearerToken) {
public static Claims getClaims(String token) {
return Jwts.parser()
.setSigningKey(secretKey)
.parseClaimsJws(token)
.parseClaimsJws(cutTokenPrefix(token))
.getBody();
}

public static Instant getExpiration(String token) {
return getClaims(cutTokenPrefix(token))
return getClaims(token)
.getExpiration()
.toInstant();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,5 +13,4 @@
public interface RefreshTokenRepository extends JpaRepository<RefreshToken, Long> {
Optional<RefreshToken> findByToken(String token);
List<RefreshToken> findByMemberAndExpiredDateIsAfter(Member member, Instant expiredDate);
boolean existsByMemberAndExpiredDateIsAfter(Member member, Instant expiredDate);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@
import com.timcooki.jnuwiki.domain.security.config.JwtProvider;
import com.timcooki.jnuwiki.util.TimeFormatter;
import com.timcooki.jnuwiki.util.errors.exception.Exception401;
import java.util.List;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -42,11 +41,6 @@ public WrapAccessTokenResDTO renewAccessToken(String refreshToken) {


public RefreshToken createRefreshToken(Member member) {
if (refreshTokenRepository.existsByMemberAndExpiredDateIsAfter(member, Instant.now())) {
List<RefreshToken> refreshTokens = refreshTokenRepository.findByMemberAndExpiredDateIsAfter(member, Instant.now());
return refreshTokens.get(refreshTokens.size() - 1);
}

String refreshToken = JwtProvider.createRefreshToken(member.getEmail(), member.getRole().toString());
Instant expiration = JwtProvider.getExpiration(refreshToken);

Expand All @@ -60,7 +54,6 @@ public RefreshToken createRefreshToken(Member member) {

public void verifyExpiration(RefreshToken token) {
if (token.getExpiredDate().isBefore(Instant.now())) {
refreshTokenRepository.delete(token);
throw new Exception401("리프레시 토큰이 만료되었습니다. 재로그인을 해주세요.");
}
}
Expand Down
Loading