Skip to content

Commit

Permalink
GM-13 시큐리티 및 OAUTH 관련 파일 생성
Browse files Browse the repository at this point in the history
  • Loading branch information
kgh2120 committed Jan 10, 2023
1 parent b96a6e6 commit 76f5aa3
Show file tree
Hide file tree
Showing 12 changed files with 276 additions and 10 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ out/

### VS Code ###
.vscode/

### security
./src/main/resources/application-oauth.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.gaaji.auth.applicationservice;

import com.gaaji.auth.domain.Auth;
import com.gaaji.auth.repository.AuthRepository;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.security.oauth2.client.userinfo.DefaultOAuth2UserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserRequest;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.OAuth2AuthenticationException;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.stereotype.Service;

@RequiredArgsConstructor
@Service
public class CustomeOAuth2UserService implements OAuth2UserService<OAuth2UserRequest, OAuth2User> {
private final AuthRepository authRepository;


@Override
public OAuth2User loadUser(OAuth2UserRequest userRequest) throws OAuth2AuthenticationException {
OAuth2UserService<OAuth2UserRequest, OAuth2User> delegate = new DefaultOAuth2UserService();
OAuth2User oAuth2User = delegate.loadUser(userRequest);

String registrationId = userRequest.getClientRegistration().getRegistrationId();
String userNameAttributeName = userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUserNameAttributeName();


OAuthAttributes attributes = OAuthAttributes.of(registrationId, userNameAttributeName, oAuth2User.getAttributes());



Auth user = saveOrUpdate(attributes);

Map<String, Object> attribute = new HashMap<>();
attribute.put("id",user.getAuthIdForToken());


return new DefaultOAuth2User(Collections.emptyList(),
attribute,
attributes.getNameAttributeKey());
}

private Auth saveOrUpdate(OAuthAttributes attributes) {
Auth user = authRepository.findByPlatformInfo(attributes.getPlatformType(), attributes.getEmail()) // <- 조회 없으면 save 후 반환, 있으면 반환,
.orElse(authRepository.save(attributes.getPlatformType(), attributes.getEmail()));

return user;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package com.gaaji.auth.applicationservice;

import com.gaaji.auth.domain.PlatformType;
import java.util.Map;
import lombok.Builder;
import lombok.Getter;
import org.springframework.security.core.userdetails.User;

@Getter
public class OAuthAttributes {
private Map<String, Object> attributes;
private String nameAttributeKey;

private String email;

private PlatformType platformType;

@Builder
public OAuthAttributes(Map<String, Object> attributes, String nameAttributeKey, String email, PlatformType platformType) {
this.attributes = attributes;
this.nameAttributeKey = nameAttributeKey;
this.email = email;
this.platformType = platformType;
}

public static OAuthAttributes of(String registrationId, String userNameAttributeName, Map<String, Object> attributes) {
if (registrationId.equals("kakao")) {
return ofKakao(userNameAttributeName, attributes);
} else if (registrationId.equals("naver")) {
return ofNaver(userNameAttributeName,attributes);
}
// TODO Facebook 찾아보기
return ofGoogle(userNameAttributeName, attributes);
}
private static OAuthAttributes ofKakao(String userNameAttributeName, Map<String, Object> attributes) {
Map<String, Object> kakao_account = (Map<String, Object>) attributes.get("kakao_account"); // 카카오로 받은 데이터에서 계정 정보가 담긴 kakao_account 값을 꺼낸다.

return OAuthAttributes.builder()
.email((String) kakao_account.get("email"))
.platformType(PlatformType.KAKAO)
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}
private static OAuthAttributes ofNaver(String userNameAttributeName, Map<String, Object> attributes) {
Map<String, Object> response = (Map<String, Object>) attributes.get("response"); // 네이버가지로 profile(nickname, image_url.. 등) 정보가 담긴 값을 꺼낸다.

return OAuthAttributes.builder()
.email((String) response.get("email"))
.platformType(PlatformType.NAVER)
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}
private static OAuthAttributes ofGoogle(String userNameAttributeName, Map<String, Object> attributes) {
return OAuthAttributes.builder()
.email((String) attributes.get("email"))
.platformType(PlatformType.GOOGLE)
.attributes(attributes)
.nameAttributeKey(userNameAttributeName)
.build();
}

public User toEntity() {
return null;
}
}
5 changes: 0 additions & 5 deletions src/main/java/com/gaaji/auth/config/Sample.java

This file was deleted.

50 changes: 50 additions & 0 deletions src/main/java/com/gaaji/auth/config/SecurityConfig.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package com.gaaji.auth.config;

import com.gaaji.auth.applicationservice.CustomeOAuth2UserService;
import java.util.Arrays;
import java.util.List;
import lombok.RequiredArgsConstructor;
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.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;

@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class SecurityConfig {

private final CustomeOAuth2UserService customOAuth2UserService;


@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {

return httpSecurity
.csrf().disable()
.headers().frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/**/**").permitAll()
.antMatchers("/**").authenticated()
.anyRequest().authenticated()
.and()

.oauth2Login()
.userInfoEndpoint()
.userService(customOAuth2UserService)
.and()
.and()
.build();


}
}

25 changes: 21 additions & 4 deletions src/main/java/com/gaaji/auth/domain/Auth.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import javax.persistence.Embedded;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import lombok.Builder;
import lombok.NoArgsConstructor;

@Entity @NoArgsConstructor
Expand All @@ -21,12 +22,28 @@ public class Auth {
@Embedded
private MannerTemparature mannerTemparature;

public void registerNickname(){

@Builder
private Auth(AuthId id, String nickname, PlatformInfo platformInfo,
MannerTemparature mannerTemparature) {
this.id = id;
this.nickname = nickname;
this.platformInfo = platformInfo;
this.mannerTemparature = mannerTemparature;
}

public static Auth signUp(){
return null;
public static Auth signUp(String id, PlatformType type, String email){
return Auth.builder()
.id(AuthId.of(id))
.nickname("익명")
.platformInfo(PlatformInfo.of(type,email))
.mannerTemparature(MannerTemparature.of(36.5))
.build();
}
public void registerNickname(String nickname){
this.nickname = nickname;
}
public String getAuthIdForToken(){
return id.getId();
}

}
11 changes: 10 additions & 1 deletion src/main/java/com/gaaji/auth/domain/AuthId.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,10 @@
import java.util.Objects;
import javax.persistence.Embeddable;
import javax.persistence.Id;
import lombok.Getter;
import lombok.NoArgsConstructor;

@Embeddable @NoArgsConstructor
@Embeddable @NoArgsConstructor @Getter
public class AuthId implements Serializable {

@Id
Expand All @@ -28,4 +29,12 @@ public boolean equals(Object o) {
public int hashCode() {
return Objects.hash(id);
}

private AuthId(String id) {
this.id = id;
}

public static AuthId of(String id) {
return new AuthId(id);
}
}
6 changes: 6 additions & 0 deletions src/main/java/com/gaaji/auth/domain/MannerTemparature.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,10 @@ public class MannerTemparature {

private double temparature;

private MannerTemparature(double temparature) {
this.temparature = temparature;
}
public static MannerTemparature of(double temparature){
return new MannerTemparature(temparature);
}
}
9 changes: 9 additions & 0 deletions src/main/java/com/gaaji/auth/domain/PlatformInfo.java
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,13 @@ public class PlatformInfo {
private PlatformType platformType;

private String platformEmail;

private PlatformInfo(PlatformType platformType, String platformEmail) {
this.platformType = platformType;
this.platformEmail = platformEmail;
}

public static PlatformInfo of(PlatformType platformType, String platformEmail){
return new PlatformInfo(platformType,platformEmail);
}
}
16 changes: 16 additions & 0 deletions src/main/java/com/gaaji/auth/repository/AuthRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.gaaji.auth.repository;

import com.gaaji.auth.domain.Auth;
import com.gaaji.auth.domain.PlatformType;
import java.util.Optional;
import java.util.UUID;

public interface AuthRepository {
Auth save(PlatformType type, String email);

Optional<Auth> findByPlatformInfo(PlatformType type, String email);

default String nextId(){
return UUID.randomUUID().toString();
}
}
26 changes: 26 additions & 0 deletions src/main/java/com/gaaji/auth/repository/AuthRepositoryImpl.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package com.gaaji.auth.repository;

import com.gaaji.auth.domain.Auth;
import com.gaaji.auth.domain.PlatformType;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;

@RequiredArgsConstructor
@Repository
public class AuthRepositoryImpl implements AuthRepository{

private final JpaAuthRepository jpaAuthRepository;

@Override
public Auth save(PlatformType type, String email) {
return jpaAuthRepository.save(Auth.signUp(this.nextId(), type, email));
}

@Override
public Optional<Auth> findByPlatformInfo(PlatformType type, String email) {
return jpaAuthRepository.findAuthByPlatformInfo_PlatformEmailAndPlatformInfo_PlatformType(type, email);
}


}
14 changes: 14 additions & 0 deletions src/main/java/com/gaaji/auth/repository/JpaAuthRepository.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.gaaji.auth.repository;

import com.gaaji.auth.domain.Auth;
import com.gaaji.auth.domain.AuthId;
import com.gaaji.auth.domain.PlatformType;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

public interface JpaAuthRepository extends JpaRepository<Auth, AuthId> {

Optional<Auth> findAuthByPlatformInfo_PlatformEmailAndPlatformInfo_PlatformType(PlatformType type, String platformEmail);

Optional<Auth> findAuthByPlatformInfo(PlatformType type, String platformEmail);
}

0 comments on commit 76f5aa3

Please sign in to comment.