Skip to content

Commit

Permalink
Jwt header 값 및 userRepository 설정 #4
Browse files Browse the repository at this point in the history
  • Loading branch information
haeyeon0106 committed Mar 5, 2023
1 parent 28f3ae3 commit 02db6a6
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 34 deletions.
3 changes: 2 additions & 1 deletion src/main/java/com/server/dos/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
package com.server.dos.config;

import com.server.dos.OAuth2SuccessHandler;
import com.server.dos.controller.OAuth2SuccessHandler;
import com.server.dos.config.jwt.JwtAuthFilter;
import com.server.dos.config.jwt.JwtProvider;
import com.server.dos.service.CustomOAuth2UserService;
import lombok.AllArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
Expand Down
3 changes: 2 additions & 1 deletion src/main/java/com/server/dos/config/jwt/JwtAuthFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,9 @@ public class JwtAuthFilter extends GenericFilter { // 토큰 인증 처리

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String token = ((HttpServletRequest)request).getHeader("Authorization");
String token = ((HttpServletRequest) request).getHeader("Authorization");
log.info("jwt filter에서 token: "+token);
log.info("verifyToken value: " + jwtProvider.verifyToken(token));

if(token != null && jwtProvider.verifyToken(token)){
log.info("들어옴");
Expand Down
25 changes: 19 additions & 6 deletions src/main/java/com/server/dos/config/jwt/JwtProvider.java
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.Key;
import java.util.Arrays;
import java.util.Collection;
Expand All @@ -31,17 +34,18 @@ public JwtProvider(@Value("${jwt.secret}") String secretKey){
this.key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey));
}

public TokenDto generateToken(String uid, String role){
public TokenDto generateToken(String uid, String role,String nickname){

Claims claims = Jwts.claims().setSubject(uid); // sub(subject) : 토큰제목
claims.put("role",role);
claims.put("name",nickname);

Date now = new Date();

String accessToken = Jwts.builder()
.setClaims(claims) // payload "role": "ROLE_USER"
.setExpiration(new Date(now.getTime() + accessExpire)) // payload "exp" : 14234532(예시)
.signWith(SignatureAlgorithm.HS256, key) // header "alg" : "HS256"
.signWith(key) // header "alg" : "HS256"
.compact();

String refreshToken = refreshToken(uid);
Expand All @@ -55,12 +59,13 @@ public TokenDto generateToken(String uid, String role){
.build();
}


public String refreshToken(String uid){
Date now = new Date();
return Jwts.builder()
.setSubject(uid)
.setExpiration(new Date(now.getTime() + refreshExpire))
.signWith(SignatureAlgorithm.HS256, key)
.signWith(key)
.compact();
}

Expand All @@ -74,7 +79,7 @@ public boolean verifyToken(String token){
return claims.getBody()
.getExpiration()
.after(new Date());
} catch (Exception e) {
}catch (Exception e) {
return false;
}
}
Expand All @@ -86,13 +91,13 @@ public Authentication getAuthentication(String token){
Claims claims = parseClaims(token);
log.info("claims: "+ claims);

if(claims.get("auth") == null){
if(claims.get("Authorization") == null){
throw new RuntimeException("Not Authorization");
}

// 클레임에서 권한 정보 가져오기
Collection<? extends GrantedAuthority> authorities =
Arrays.stream(claims.get("auth").toString().split(","))
Arrays.stream(claims.get("Authorization").toString().split(","))
.map(SimpleGrantedAuthority::new).collect(Collectors.toList());

log.info("authorities: " + authorities);
Expand All @@ -110,4 +115,12 @@ public Claims parseClaims(String token){
}
}

public void sendAccessAndRefreshToken(HttpServletResponse response, String accessToken, String refreshToken) throws IOException {
response.setStatus(HttpServletResponse.SC_OK);
response.setHeader("Authorization",accessToken);
response.setHeader("Authorization-refresh",refreshToken);

log.info("Header 설정 완료");

}
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.server.dos;
package com.server.dos.controller;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.server.dos.config.CustomOAuth2UserService;
import com.server.dos.config.jwt.JwtProvider;
import com.server.dos.dto.TokenDto;
import com.server.dos.dto.UserDto;
Expand All @@ -23,12 +22,9 @@
@RequiredArgsConstructor
@Component
public class OAuth2SuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
// private final TokenService tokenService;
private final UserOauthMapper userRequestMapper;
private final JwtProvider jwtProvider;
// private final ObjectMapper objectMapper;

private final CustomOAuth2UserService userService;
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
throws IOException, ServletException {
Expand All @@ -38,18 +34,21 @@ public void onAuthenticationSuccess(HttpServletRequest request, HttpServletRespo
UserDto userDto = userRequestMapper.getUser(oAuth2User);

log.info("Principal에서 꺼낸 OAuth2User = {}",oAuth2User);
log.info("kakao name(handler) : "+oAuth2User.getAttributes().get("name"));
log.info("UserDto: " + userDto);


String tagUrl;
log.info("토큰 발행 시작");

TokenDto token = jwtProvider.generateToken(userDto.getEmail(),"USER");
TokenDto token = jwtProvider.generateToken(userDto.getEmail(),"USER",userDto.getName());
jwtProvider.sendAccessAndRefreshToken(response,token.getAccessToken(),token.getRefreshToken());

tagUrl = UriComponentsBuilder.fromUriString("/home")
.queryParam("token",token)
.queryParam("token","token")
.build().toUriString();


getRedirectStrategy().sendRedirect(request,response,tagUrl);

}
Expand Down
2 changes: 1 addition & 1 deletion src/main/java/com/server/dos/dto/UserDto.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
@Data
@Builder
public class UserDto {
private String nickname;
private String name;
private String email;
private String picture;
}
41 changes: 31 additions & 10 deletions src/main/java/com/server/dos/entity/user/OAuth2Attribute.java
Original file line number Diff line number Diff line change
@@ -1,27 +1,36 @@
package com.server.dos.entity.user;

import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;


import java.util.Map;

@ToString
@Builder(access = AccessLevel.PRIVATE)

@Slf4j
@Getter
public class OAuth2Attribute {

private Map<String,Object> attributes;
private String attributeKey;
private String email;
private String nickname;
private String name;

private String picture;

@Builder
public OAuth2Attribute(Map<String,Object> attributes,String attributeKey,String email,String name,String picture){
this.attributes = attributes;
this.attributeKey = attributeKey;
this.email = email;
this.name = name;
this.picture = picture;
}
public static OAuth2Attribute of(String provider, String attributeKey, Map<String, Object> attributes){
switch (provider){
case "kakao":
return ofKakao(attributeKey,attributes);
return ofKakao("email",attributes);
case "google":
return ofGoogle(attributeKey,attributes);
default:
Expand All @@ -33,26 +42,38 @@ private static OAuth2Attribute ofKakao(String attributeKey, Map<String,Object> a
Map<String,Object> kakaoProfile = (Map<String,Object>)kakaoAccount.get("profile");

return OAuth2Attribute.builder()
.nickname((String)kakaoProfile.get("nickname"))
.name((String)kakaoProfile.get("nickname"))
.email((String) kakaoAccount.get("email"))
.picture((String)kakaoProfile.get("profile_image_url"))
.attributes(attributes)
.attributes(kakaoAccount)
.attributeKey(attributeKey)
.build();
}
private static OAuth2Attribute ofGoogle(String attributeKey, Map<String,Object> attributes){

return OAuth2Attribute.builder()
.nickname((String)attributes.get("name"))
.name((String)attributes.get("name"))
.email((String) attributes.get("email"))
.picture((String) attributes.get("picture"))
.attributes(attributes)
.attributeKey(attributeKey)
.build();
}
public User toEntity(){
return User.builder()
.nickname(nickname)
.name(name)
.email(email)
.picture(picture)
.role(Role.GUEST)
.build();
}
// public Map<String,Object> convertToMap(){
// Map<String,Object> map = new HashMap<>();
// map.put("id",attributeKey);
// map.put("key",attributeKey);
// map.put("email",email);
// map.put("nickname",nickname);
// map.put("picture",picture);
// return map;
// }
}
21 changes: 18 additions & 3 deletions src/main/java/com/server/dos/entity/user/User.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,33 @@ public class User extends BaseTimeEntity {
private Long id;

@Column(nullable = false)
private String nickname;
private String name;

@Column(nullable = false)
private String email;

@Column
private String picture;

@Enumerated(EnumType.STRING)
@Column(nullable = false)
private Role role;

@Builder
public User (String nickname, String email){
this.nickname = nickname;
public User (String name, String email,String picture,Role role){
this.name = name;
this.email = email;
this.picture = picture;
this.role = role;
}

public User update(String name,String picture) {
this.name = name;
this.picture = picture;

return this;
}
public String getRoleKey(){
return this.role.getKey();
}
}
2 changes: 1 addition & 1 deletion src/main/java/com/server/dos/mapper/UserOauthMapper.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class UserOauthMapper {
public UserDto getUser(OAuth2User oAuth2User){
var attributes = oAuth2User.getAttributes();
return UserDto.builder()
.nickname((String) attributes.get("nickname"))
.name((String) attributes.get("name"))
.email((String) attributes.get("email"))
.picture((String) attributes.get("picture"))
.build();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.server.dos.config;
package com.server.dos.service;

import com.server.dos.entity.user.OAuth2Attribute;
import com.server.dos.entity.user.User;
import com.server.dos.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
Expand All @@ -14,8 +17,11 @@
import java.util.Collections;

@Slf4j
@RequiredArgsConstructor
@Service
public class CustomOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
private final UserRepository userRepository;


//사용자 정보를 요청할 수 있는 access token을 얻고나서 실행
@Override
Expand All @@ -34,12 +40,21 @@ public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2Authentic
log.info("userNameAttributeName: " + userNameAttributeName);

OAuth2Attribute oAuth2Attribute = OAuth2Attribute.of(registrationId,userNameAttributeName,oAuth2User.getAttributes());
User user = saveOrUpdate(oAuth2Attribute);

// var memberAttributes = oAuth2Attribute.convertToMap();
// memberAttribute: {nickname=카카오 이름, id=id, key=id, email=카카오 이메일}

return new DefaultOAuth2User(
Collections.singleton(new SimpleGrantedAuthority("ROLE_USER")),
oAuth2Attribute.getAttributes(),"email");
Collections.singleton(new SimpleGrantedAuthority(user.getRoleKey())),
oAuth2Attribute.getAttributes(),oAuth2Attribute.getAttributeKey());
}

public User saveOrUpdate(OAuth2Attribute oAuth2Attribute){
User user = userRepository.findByEmail(oAuth2Attribute.getEmail())
.map(entity->entity.update(oAuth2Attribute.getName(),oAuth2Attribute.getPicture()))
.orElse(oAuth2Attribute.toEntity());

return userRepository.save(user);
}
}

0 comments on commit 02db6a6

Please sign in to comment.