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

[PC-379] 어드민 모듈 로그인 기능 #34

Merged
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
3 changes: 2 additions & 1 deletion admin/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ dependencies {
implementation project(':common:domain')
implementation project(':common:format')
implementation project(':common:exception')

implementation project(':common:auth')

testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}
Expand Down
6 changes: 6 additions & 0 deletions admin/src/main/java/org/yapp/auth/application/AdminRole.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package org.yapp.auth.application;

public enum AdminRole {
ADMIN,
ROLE_ADMIN;
}
40 changes: 40 additions & 0 deletions admin/src/main/java/org/yapp/auth/application/AuthService.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.yapp.auth.application;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.yapp.auth.AuthToken;
import org.yapp.auth.AuthTokenGenerator;
import org.yapp.auth.application.dto.LoginDto;
import org.yapp.domain.user.User;
import org.yapp.error.code.auth.AuthErrorCode;
import org.yapp.error.exception.ApplicationException;
import org.yapp.user.application.UserService;

@Slf4j
@Service
@RequiredArgsConstructor
public class AuthService {

private final UserService userService;

private final AuthTokenGenerator authTokenGenerator;

@Value("${admin.password}")
private String PWD;

public AuthToken login(LoginDto loginDto) {
String oauthId = loginDto.oauthId();
String password = loginDto.password();

User loginUser = userService.getUserByOauthId(oauthId);

if (password.equals(PWD) && loginUser.getRole().equals(AdminRole.ADMIN.toString())) {
return authTokenGenerator.generate(loginUser.getId(), null,
AdminRole.ROLE_ADMIN.toString());
} else {
throw new ApplicationException(AuthErrorCode.ACCESS_DENIED);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package org.yapp.auth.application.dto;

public record LoginDto(String oauthId, String password) {

}
28 changes: 28 additions & 0 deletions admin/src/main/java/org/yapp/auth/presentation/AuthController.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package org.yapp.auth.presentation;

import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
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;
import org.yapp.auth.AuthToken;
import org.yapp.auth.application.AuthService;
import org.yapp.auth.presentation.request.LoginRequest;
import org.yapp.util.CommonResponse;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/v1/auth/")
public class AuthController {

private final AuthService authService;

@PostMapping("/login")
public ResponseEntity<CommonResponse<AuthToken>> login(
@RequestBody @Valid LoginRequest loginRequest) {
AuthToken authToken = authService.login(loginRequest.toDto());
return ResponseEntity.ok(CommonResponse.createSuccess(authToken));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package org.yapp.auth.presentation.request;

import jakarta.validation.constraints.NotNull;
import org.yapp.auth.application.dto.LoginDto;

public record LoginRequest(@NotNull String loginId, @NotNull String password) {

public LoginDto toDto() {
return new LoginDto(loginId, password);
}
}
7 changes: 6 additions & 1 deletion admin/src/main/java/org/yapp/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,20 @@
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;
import org.springframework.security.web.util.matcher.RequestMatchers;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.yapp.jwt.JwtFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

private final JwtFilter jwtFilter;

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
return http.csrf(AbstractHttpConfigurer::disable)
Expand All @@ -33,6 +37,7 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.permitAll()
.anyRequest()
.hasAnyRole("ADMIN"))
.addFilterBefore(jwtFilter, UsernamePasswordAuthenticationFilter.class)
.build();
}

Expand All @@ -47,6 +52,6 @@ private CorsConfigurationSource corsConfigurationSource() {
}

private RequestMatcher getMatcherForAnyone() {
return RequestMatchers.anyOf(antMatcher("/admin/v1/login/**"));
return RequestMatchers.anyOf(antMatcher("/admin/v1/auth/login/**"));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ public User getUserById(Long userId) {
.orElseThrow(() -> new ApplicationException(UserErrorCode.NOTFOUND_USER));
}

public User getUserByOauthId(String oauthId) {
return userRepository.findByOauthId(oauthId)
.orElseThrow(() -> new ApplicationException(UserErrorCode.NOTFOUND_USER));
}

public PageResponse<UserProfileValidationResponse> getUserProfilesWithPagination(int page,
int size) {
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Direction.DESC, "createdAt"));
Expand Down
2 changes: 2 additions & 0 deletions admin/src/main/java/org/yapp/user/dao/UserRepository.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,4 +9,6 @@
public interface UserRepository extends JpaRepository<User, Long> {

Optional<User> findById(Long userId);

Optional<User> findByOauthId(String oauthId);
}
2 changes: 1 addition & 1 deletion admin/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
spring:
profiles:
include: db
include: db, secret
19 changes: 19 additions & 0 deletions common/auth/build.gradle
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
plugins {
id 'java'
}

group = 'org.yapp'
version = '0.0.1-SNAPSHOT'

repositories {
mavenCentral()
}

dependencies {
testImplementation platform('org.junit:junit-bom:5.10.0')
testImplementation 'org.junit.jupiter:junit-jupiter'
}

test {
useJUnitPlatform()
}
5 changes: 5 additions & 0 deletions common/auth/src/main/java/org/yapp/auth/AuthToken.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package org.yapp.auth;

public record AuthToken(String accessToken, String refreshToken) {

}
30 changes: 30 additions & 0 deletions common/auth/src/main/java/org/yapp/auth/AuthTokenGenerator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package org.yapp.auth;

import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.yapp.jwt.JwtUtil;

@Component
@RequiredArgsConstructor
public class AuthTokenGenerator {

private final JwtUtil jwtUtil;

@Value("${jwt.accessToken.expiration}")
private Long accessTokenExpiration;

@Value("${jwt.refreshToken.expiration}")
private Long refreshTokenExpiration;


public AuthToken generate(Long userId, String oauthId, String role) {
String accessToken = jwtUtil.createJwt("access_token", userId, oauthId, role,
accessTokenExpiration);

String refreshToken = jwtUtil.createJwt("refesh_token", userId, oauthId, role,
refreshTokenExpiration);

return new AuthToken(accessToken, refreshToken);
}
}
Comment on lines +10 to +30
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

책임 분리 좋은 것 같습니다!

68 changes: 68 additions & 0 deletions common/auth/src/main/java/org/yapp/jwt/JwtFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package org.yapp.jwt;

import io.jsonwebtoken.ExpiredJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collections;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

@RequiredArgsConstructor
@Component
public class JwtFilter extends OncePerRequestFilter {

private final JwtUtil jwtUtil;

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

String accessToken = request.getHeader("Authorization");
if (accessToken == null || !accessToken.startsWith("Bearer ")) {
filterChain.doFilter(request, response);
return;
}
accessToken = accessToken.substring(7);

try {
jwtUtil.isExpired(accessToken);
} catch (ExpiredJwtException e) {

PrintWriter writer = response.getWriter();
writer.print("access token expired");

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}

String category = jwtUtil.getCategory(accessToken);
if (!category.equals("access_token")) {
PrintWriter writer = response.getWriter();
writer.print("invalid access token");

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
return;
}

Long userId = jwtUtil.getUserId(accessToken);
String role = jwtUtil.getRole(accessToken);

Authentication authToken =
new UsernamePasswordAuthenticationToken(userId, null, Collections.singleton(
(GrantedAuthority) () -> role));

SecurityContextHolder.getContext().setAuthentication(authToken);

filterChain.doFilter(request, response);
}
}
89 changes: 89 additions & 0 deletions common/auth/src/main/java/org/yapp/jwt/JwtUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
package org.yapp.jwt;

import io.jsonwebtoken.Jwts;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class JwtUtil {

private final SecretKey secretKey;

public JwtUtil(@Value("${jwt.secret}") String secret) {
secretKey = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8),
Jwts.SIG.HS256.key().build().getAlgorithm());
}

public String getOauthId(String token) {
String oauthId;
try {
oauthId = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token)
.getPayload().get("oauthId", String.class);
} catch (Exception e) {
throw new RuntimeException();
}
return oauthId;
}

public String getRole(String token) {
String role;
try {
role = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload()
.get("role", String.class);
} catch (Exception e) {
throw new RuntimeException();
}
return role;
}

public Boolean isExpired(String token) {
boolean before;
try {
before = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token)
.getPayload().getExpiration().before(new Date());
} catch (Exception e) {
throw new RuntimeException();
}
return before;
}

public String createJwt(String category, Long userId, String oauthId, String role,
Long expiredMs) {
return Jwts.builder()
.claim("category", category)
.claim("userId", userId)
.claim("oauthId", oauthId)
.claim("role", role)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expiredMs))
.signWith(secretKey)
.compact();
}

public Long getUserId(String token) {
Long userId;
try {
userId = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token)
.getPayload().get("userId", Long.class);
} catch (Exception e) {
throw new RuntimeException();
}
return userId;
}

public String getCategory(String token) {
String category;
try {
category = Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token)
.getPayload().get("category", String.class);
} catch (Exception e) {
throw new RuntimeException();
}
return category;
}
}

Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,10 @@
@RequiredArgsConstructor
public enum AuthErrorCode implements ErrorCode {
OAUTH_ERROR(HttpStatus.FORBIDDEN, "Oauth Error"),
ACCESS_DENIED(HttpStatus.FORBIDDEN, "권한이 없습니다."),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

에러 메시지 한글로 하는 거 좋은 것 같습니다!
앞으로는 에러메시지 한글로 할까요?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

에러 메시지가 한글인게 더 명확한 것 같습니다 !

그리고, 에러가 발생한 응답이 전달될때 클라이언트 분들은 저희 서비스만의 에러 코드(ex. 1404, 1402 ...)가 같이 전달되었으면 하는 바람이 있으신 것 같습니다. 한글로 변환하는 김에 저희 서비스 에러코드도 지정하는 것이 어떨까요 ?

;


private final HttpStatus httpStatus;
private final String message;
}
Loading