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

Feature/19: MemberRepository에 Spring Data Jpa 도입 #20

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
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: 1 addition & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -37,5 +37,4 @@ out/
.vscode/

## ADD
mysql_data
compose.yml
mysql_data
9 changes: 8 additions & 1 deletion app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,14 @@ dependencies {
runtimeOnly 'com.mysql:mysql-connector-j'
developmentOnly 'org.springframework.boot:spring-boot-devtools'

testImplementation 'com.h2database:h2' // H2를 테스트용 DB로 사용 시
// jwt
implementation 'io.jsonwebtoken:jjwt-api:0.12.3'
implementation 'io.jsonwebtoken:jjwt-impl:0.12.3'
implementation 'io.jsonwebtoken:jjwt-jackson:0.12.3'

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

}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package org.example.domain.global.config;

import lombok.RequiredArgsConstructor;
import org.example.domain.jwt.JWTFilter;
import org.example.domain.jwt.JWTUtil;
import org.example.domain.jwt.LoginFilter;
import org.example.domain.member.MemberRepository;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {
private final AuthenticationConfiguration authenticationConfiguration;
private final JWTUtil jwtUtil;
private final MemberRepository memberRepository;
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
return configuration.getAuthenticationManager();
}
@Bean
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http.csrf((auth) -> auth.disable());
http.formLogin((auth) -> auth.disable());
http.httpBasic((auth) -> auth.disable());

http.authorizeHttpRequests((auth) ->
auth.requestMatchers("/login","/profile/add").permitAll()
.anyRequest().authenticated());

http.addFilterBefore(new JWTFilter(jwtUtil,memberRepository), LoginFilter.class);
http.addFilterAt(new LoginFilter(authenticationManager(authenticationConfiguration),jwtUtil), UsernamePasswordAuthenticationFilter.class);

http.sessionManagement((session) -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS));

return http.build();
}
}

This file was deleted.

This file was deleted.

51 changes: 51 additions & 0 deletions app/src/main/java/org/example/domain/jwt/JWTFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package org.example.domain.jwt;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.login.CustomUserDetails;
import org.example.domain.member.MemberRepository;
import org.example.domain.member.entity.Member;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@RequiredArgsConstructor
@Slf4j
public class JWTFilter extends OncePerRequestFilter {
private final JWTUtil jwtUtil;
private final MemberRepository memberRepository;

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authorization = request.getHeader("Authorization");

if(authorization == null || !authorization.startsWith("Bearer ")) {
log.debug("token is null");
filterChain.doFilter(request,response);
return;
}

log.debug("token exists");
String token = authorization.split(" ")[1];

if(jwtUtil.isExpired(token)){
filterChain.doFilter(request,response);
return;
}

String username = jwtUtil.getUsername(token);
String role = jwtUtil.getRole(token);

Member member = memberRepository.findByUsername(username).get();
CustomUserDetails customUserDetails = new CustomUserDetails(member);
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(customUserDetails, null, customUserDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);
filterChain.doFilter(request,response);
}
}
42 changes: 42 additions & 0 deletions app/src/main/java/org/example/domain/jwt/JWTUtil.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package org.example.domain.jwt;

import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Date;

//JWT 0.12.3
@Component
public class JWTUtil {
private SecretKey secretKey;

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

public String getUsername(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("username", String.class);
}

public String getRole(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().get("role", String.class);
}

public Boolean isExpired(String token) {
return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload().getExpiration().before(new Date());
}

public String createJwt(String username, String role, Long expiredMs) {
return Jwts.builder()
.claim("username", username)
.claim("role", role)
.issuedAt(new Date(System.currentTimeMillis()))
.expiration(new Date(System.currentTimeMillis() + expiredMs))
.signWith(secretKey)
.compact();
}
}
63 changes: 63 additions & 0 deletions app/src/main/java/org/example/domain/jwt/LoginFilter.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
package org.example.domain.jwt;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.login.CustomUserDetails;
import org.example.domain.login.dto.request.LoginRequest;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;

@RequiredArgsConstructor
@Slf4j
public class LoginFilter extends UsernamePasswordAuthenticationFilter {

private final AuthenticationManager authenticationManager;
private final JWTUtil jwtUtil;


@Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
ObjectMapper objectMapper = new ObjectMapper();

try {
LoginRequest loginRequest = objectMapper.readValue(request.getInputStream(), LoginRequest.class);
String username = loginRequest.getUsername();
String password = loginRequest.getPassword();
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(username, password, null);
log.debug("authToken = {}", authToken);
return authenticationManager.authenticate(authToken);
} catch (IOException e) {
throw new RuntimeException(e);
}
}

@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
CustomUserDetails customUserDetails = (CustomUserDetails)authResult.getPrincipal(); // 인증된 사용자 정보
String username = customUserDetails.getUsername();
Collection<? extends GrantedAuthority> authorities = authResult.getAuthorities();
Iterator<? extends GrantedAuthority> iterator = authorities.iterator();
GrantedAuthority auth = iterator.next();
String role = auth.getAuthority();
String token = jwtUtil.createJwt(username, role, 60 * 60 * 10000L);
response.addHeader("Authorization", "Bearer " + token);
}

@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
response.setStatus(401);
}
}
58 changes: 58 additions & 0 deletions app/src/main/java/org/example/domain/login/CustomUserDetails.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
package org.example.domain.login;

import org.example.domain.member.entity.Member;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;

public class CustomUserDetails implements UserDetails {
private final Member member;

public CustomUserDetails(Member member) {
this.member = member;
}

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
Collection<GrantedAuthority> collection = new ArrayList<>();
collection.add(new GrantedAuthority() {
@Override
public String getAuthority() {
return member.getRole();
}
});
return collection;
}

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

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

@Override
public boolean isAccountNonExpired() {
return true;
}

@Override
public boolean isAccountNonLocked() {
return true;
}

@Override
public boolean isCredentialsNonExpired() {
return true;
}

@Override
public boolean isEnabled() {
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package org.example.domain.login;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.example.domain.member.MemberRepository;
import org.example.domain.member.entity.Member;
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
@Slf4j
public class CustomUserDetailsService implements UserDetailsService {
private final MemberRepository memberRepository;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
Member member = memberRepository.findByUsername(username).get();
if(member != null) {
return new CustomUserDetails(member);
}
return null;
}


}
Loading
Loading