Skip to content

Commit

Permalink
Merge pull request #24 from LinaKK/ref/be/product
Browse files Browse the repository at this point in the history
Ref/be/product
  • Loading branch information
LinaKK authored Jan 2, 2025
2 parents 800afec + 1e6dd08 commit 75b4bb0
Show file tree
Hide file tree
Showing 6 changed files with 130 additions and 7 deletions.
3 changes: 3 additions & 0 deletions server/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ dependencies {
//cache
implementation 'org.springframework.boot:spring-boot-starter-data-redis'
implementation 'org.springframework.boot:spring-boot-starter-cache'

//oauth2.0
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
}

tasks.named('test') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package greenNare.auth.handler;

import greenNare.auth.jwt.JwtTokenizer;
import greenNare.auth.utils.CustomAuthorityUtils;
import greenNare.cache.CacheService;
import greenNare.member.entity.Member;
import greenNare.member.service.MemberService;
import org.springframework.cache.Cache;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

public class OAuth2MemberSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private final JwtTokenizer jwtTokenizer;
private final CustomAuthorityUtils customAuthorityUtils;
private final MemberService memberService;

private final CacheService cacheService;

public OAuth2MemberSuccessHandler(JwtTokenizer jwtTokenizer,
CustomAuthorityUtils customAuthorityUtils,
MemberService memberService,
CacheService cacheService){
this.jwtTokenizer = jwtTokenizer;
this.customAuthorityUtils = customAuthorityUtils;
this.memberService = memberService;
this.cacheService = cacheService;
}

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
var oAuth2User = (OAuth2User)authentication.getPrincipal();
String email = String.valueOf(oAuth2User.getAttributes().get("email"));

//가입된 회원인지 확인
try {
memberService.findMemberByEmail(email);
} catch (Exception e){
//가입안된 이메일이면 DB 저장
String name = String.valueOf(oAuth2User.getAttributes().get("name"));
Member newMember = new Member();
newMember.setEmail(email);
newMember.setName(name);
newMember.setPoint(0);
memberService.createMember(newMember);
}

//토큰 생성해서 반환
Member member = memberService.findMemberByEmail(email);
String accessToken = delegateAccessToken(member);
String refreshToken = delegateRefreshToken(member);

response.setHeader("Authorization", "Bearer " + accessToken);
response.setHeader("Refresh", refreshToken);
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

return;
}

private String delegateAccessToken(Member member) {
Map<String, Object> claims = new HashMap<>();
claims.put("username", member.getEmail());
claims.put("roles", member.getRoles());
claims.put("memberId", member.getMemberId());

String subject = member.getEmail();
Date expiration = jwtTokenizer.getTokenExpiration(jwtTokenizer.getAccessTokenExpirationMinutes());
String base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(jwtTokenizer.getSecretKey());

String accessToken = jwtTokenizer.generateAccessToken(claims, subject, expiration, base64EncodedSecretKey);

return accessToken;

}

private String delegateRefreshToken(Member member){
String subject = member.getEmail();

Date expiration = jwtTokenizer.getTokenExpiration(jwtTokenizer.getRefreshTokenExpirationMinutes());
String base64EncodedSecretKey = jwtTokenizer.encodeBase64SecretKey(jwtTokenizer.getSecretKey());

String refreshToken = jwtTokenizer.generateRefreshToken(subject, expiration, base64EncodedSecretKey);
cacheService.putCache("RefreshToken", Integer.toString(member.getMemberId()) ,refreshToken);

return refreshToken;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import greenNare.auth.filter.JwtVerificationFilter;
import greenNare.auth.handler.MemberAuthenticationFailureHandler;
import greenNare.auth.handler.MemberAuthenticationSuccessHandler;
import greenNare.auth.handler.OAuth2MemberSuccessHandler;
import greenNare.auth.jwt.JwtTokenizer;
import greenNare.auth.utils.CustomAuthorityUtils;
import greenNare.cache.CacheService;
Expand All @@ -19,6 +20,7 @@
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.client.web.OAuth2LoginAuthenticationFilter;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
Expand Down Expand Up @@ -70,6 +72,8 @@ public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
.antMatchers(HttpMethod.PATCH, "/*/").hasRole("USER")
.antMatchers(HttpMethod.GET, "/*/").hasAnyRole("USER", "ADMIN")
.anyRequest().permitAll()
)
.oauth2Login(oauth2 -> oauth2.successHandler(new OAuth2MemberSuccessHandler(jwtTokenizer, authorityUtils, memberService, cacheService))
);

return http.build();
Expand Down Expand Up @@ -114,14 +118,15 @@ public void configure(HttpSecurity builder) throws Exception {
JwtRefreshFilter jwtRefreshFilter = new JwtRefreshFilter(jwtTokenizer, memberService, cacheService);

builder
.addFilter(jwtAuthenticationFilter)
.addFilterAfter(jwtAuthenticationFilter, OAuth2LoginAuthenticationFilter.class)
.addFilterAfter(jwtRefreshFilter, JwtAuthenticationFilter.class)
.addFilterAfter(jwtVerificationFilter, JwtRefreshFilter.class);

}
}



}


Expand Down
2 changes: 1 addition & 1 deletion server/src/main/java/greenNare/member/entity/Member.java
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class Member implements Serializable {
@Column(length = 100, nullable = false)
private String name;

@Column(length = 100, nullable = false)
@Column(length = 100, nullable = true)
private String password;
@Column(nullable = false)
private int point;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,6 @@ public Member updateMember(Member member) {

Member findMember = findVerifiedMember(member.getMemberId());


Optional.ofNullable(member.getName())
.ifPresent(name -> findMember.setName(name));

Expand Down
30 changes: 26 additions & 4 deletions server/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,9 +1,22 @@
externalImagePath: home/ssm-user/seb44_main_026/images/
spring:
log-request-details: true
#mvc:
# static-path-pattern: /images/**
#resources:
# static-locations: file:${externalImagePath}

security:
oauth2:
client:
registration:
google:
clientId: ${GOOGLE_CLIENT_ID}
clientSecret: ${GOOGLE_CLIENT_SECRET}
scope:
- email
- profile

cache:
type: redis

Expand Down Expand Up @@ -77,10 +90,19 @@ logging:
level:
org.hibernate.SQL: DEBUG
org.hibernate.type.descriptor.sql.BasicBinder: TRACE
org:
springframework:
jdbc:
core: TRACE
org.springframework.web: DEBUG
org.springframework.security: DEBUG
org.springframework.web.servlet.DispatcherServlet: DEBUG

# org:
# springframework: DEBUG
# pattern:
# console: "%d{yyyy-MM-dd HH:mm:ss} - %msg%n"

# org:
# springframework:
# jdbc:
# core: TRACE

jwt:
key: jasdfasfd1312345351354314560984745
Expand Down

0 comments on commit 75b4bb0

Please sign in to comment.