user role column -> table

This commit is contained in:
liquidjoo
2019-05-31 11:28:46 +09:00
parent d7d166d989
commit c1a5d7fb59
14 changed files with 146 additions and 70 deletions

View File

@@ -28,7 +28,7 @@ dependencies {
compile('org.springframework.security:spring-security-oauth2-jose') compile('org.springframework.security:spring-security-oauth2-jose')
implementation 'org.springframework.boot:spring-boot-starter-actuator' implementation 'org.springframework.boot:spring-boot-starter-actuator'
implementation 'org.springframework.boot:spring-boot-starter-freemarker' implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.cloud:spring-cloud-starter-oauth2' implementation 'org.springframework.cloud:spring-cloud-starter-oauth2'
// implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.5.RELEASE' // implementation 'org.springframework.security.oauth.boot:spring-security-oauth2-autoconfigure:2.1.5.RELEASE'

View File

@@ -78,7 +78,7 @@ public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
// .and() // .and()
// .addFilterBefore(filter, CsrfFilter.class); // .addFilterBefore(filter, CsrfFilter.class);
// .csrf().disable(); // .csrf().disable();
http.formLogin().loginPage("/login").permitAll() http.formLogin().loginPage("/login").permitAll().failureHandler(customAuthFailureHandler)
.and() .and()
.requestMatchers().antMatchers("/login/**", "/logout", "/oauth/authorize", "/oauth/confirm_access", "/oauth2/**") .requestMatchers().antMatchers("/login/**", "/logout", "/oauth/authorize", "/oauth/confirm_access", "/oauth2/**")
.and() .and()

View File

@@ -5,7 +5,7 @@ import lombok.Getter;
public enum SocialType { public enum SocialType {
FACEBOOK("facebook"), FACEBOOK("facebook"),
GOOGLE("google"), GOOGLE("google"),
KAKAO("kakao"); UNEEDCOMMS("uneedcomms");
private final String ROLE_PREFIX = "ROLE_"; private final String ROLE_PREFIX = "ROLE_";

View File

@@ -11,24 +11,25 @@ import java.util.Collection;
import java.util.List; import java.util.List;
@Data @Data
public class UserDetail implements UserDetails { public class CustomUserDetails implements UserDetails {
private static final long serialVersionUID = 6396079419309274853L; private static final long serialVersionUID = 6396079419309274853L;
private Long id; private Long id;
private String username; private String username;
private String password; private String password;
private List<String> roles; private List<String> userRole;
public UserDetail(User user) { public CustomUserDetails(User user, List<String> userRole) {
this.id = user.getId(); this.id = user.getId();
this.username = user.getUsername(); this.username = user.getUsername();
this.password = user.getPassword(); this.password = user.getPassword();
this.userRole = userRole;
} }
@Override @Override
public Collection<? extends GrantedAuthority> getAuthorities() { public Collection<? extends GrantedAuthority> getAuthorities() {
List<GrantedAuthority> authorities = new ArrayList<>(); List<GrantedAuthority> authorities = new ArrayList<>();
for (String role: roles) { for (String role: userRole) {
authorities.add(new SimpleGrantedAuthority(role)); authorities.add(new SimpleGrantedAuthority(role));
} }
return authorities; return authorities;

View File

@@ -1,17 +1,18 @@
package io.bluemoon.authorizationserver.domain.user; package io.bluemoon.authorizationserver.domain.user;
import io.bluemoon.authorizationserver.domain.social.SocialType; import io.bluemoon.authorizationserver.domain.social.SocialType;
import lombok.Builder; import lombok.*;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*; import javax.persistence.*;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import java.util.Collection;
import java.util.Date; import java.util.Date;
@Entity @Entity
@Data @Getter
@Setter
@NoArgsConstructor @NoArgsConstructor
@AllArgsConstructor
public class User { public class User {
@Id @Id
@GeneratedValue(strategy = GenerationType.IDENTITY) @GeneratedValue(strategy = GenerationType.IDENTITY)
@@ -36,6 +37,9 @@ public class User {
@Enumerated(EnumType.STRING) @Enumerated(EnumType.STRING)
private SocialType socialType; private SocialType socialType;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "user", fetch = FetchType.EAGER)
private Collection<UserRole> userRole;
@Column @Column
private LocalDateTime createdAt; private LocalDateTime createdAt;
@@ -53,15 +57,14 @@ public class User {
// private Date regDate = new Date(); // private Date regDate = new Date();
@Builder @Builder
public User(String username, String name, String password, String email, String principal, public User(String username, String name, String password, String email, String principal, LocalDateTime createdAt, LocalDateTime updatedAt, SocialType socialType) {
SocialType socialType, LocalDateTime createdAt, LocalDateTime updatedAt) {
this.username = username; this.username = username;
this.name = name; this.name = name;
this.password = password; this.password = password;
this.email = email; this.email = email;
this.principal = principal; this.principal = principal;
this.socialType = socialType;
this.createdAt = createdAt; this.createdAt = createdAt;
this.updatedAt = updatedAt; this.updatedAt = updatedAt;
this.socialType = socialType;
} }
} }

View File

@@ -0,0 +1,30 @@
package io.bluemoon.authorizationserver.domain.user;
import lombok.*;
import javax.persistence.*;
@Getter
@Setter
@Entity
@ToString(exclude = "user")
@NoArgsConstructor
@AllArgsConstructor
public class UserRole {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String role;
@ManyToOne(optional = false)
@JoinColumn(name = "userId")
private User user;
@Builder
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
}

View File

@@ -0,0 +1,10 @@
package io.bluemoon.authorizationserver.domain.user;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface UserRoleRepository extends JpaRepository<UserRole, Integer> {
List<UserRole> findByUser(User user);
}

View File

@@ -1,37 +1,49 @@
package io.bluemoon.authorizationserver.service.user; package io.bluemoon.authorizationserver.service.user;
import io.bluemoon.authorizationserver.domain.user.User; import io.bluemoon.authorizationserver.domain.user.*;
import io.bluemoon.authorizationserver.domain.user.UserDetail;
import io.bluemoon.authorizationserver.domain.user.UserRepository;
import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.Arrays; import java.util.Arrays;
import java.util.List;
@Service @Service
public class CustomUserDetailsServiceImpl implements UserDetailsService { public class CustomUserDetailsServiceImpl implements UserDetailsService {
// User Info // User Info
private UserRepository userRepository; private UserRepository userRepository;
private UserRoleRepository userRoleRepository;
public CustomUserDetailsServiceImpl( public CustomUserDetailsServiceImpl(
UserRepository userRepository UserRepository userRepository,
UserRoleRepository userRoleRepository
) { ) {
this.userRepository = userRepository; this.userRepository = userRepository;
this.userRoleRepository = userRoleRepository;
} }
@Override @Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println("why?????????????"+username);
User user = userRepository.findByUsername(username); User user = userRepository.findByUsername(username);
System.out.println(user); System.out.println(user);
List<UserRole> userRole = userRoleRepository.findByUser(user);
System.out.println(userRole);
System.out.println("---------------------------");
List<String> urs = new ArrayList<>();
for (UserRole ur : userRole) {
urs.add(ur.getRole());
}
if (user == null) { if (user == null) {
throw new UsernameNotFoundException("UsernameNotFound[" + username + "]"); throw new UsernameNotFoundException("UsernameNotFound[" + username + "]");
} }
UserDetail userDetail = createUser(user); CustomUserDetails userDetail = new CustomUserDetails(user, urs);
userDetail.getAuthorities();
System.out.println(userDetail); System.out.println(userDetail);
return userDetail; return userDetail;
} }
@@ -39,17 +51,17 @@ public class CustomUserDetailsServiceImpl implements UserDetailsService {
/** /**
* User role check * User role check
* @param user * @param user
* @param userRole
* @return * @return
*/ */
private UserDetail createUser(User user) { // private CustomUserDetails createUser(User user, List<UserRole> userRole) {
UserDetail userDetail = new UserDetail(user); // CustomUserDetails userDetail =
userDetail.setRoles(Arrays.asList("ROLE_USER")); //
//// if (userDetail.getSocial_type().getVaule().equals("FACEBOOK")) {
// if (userDetail.getSocial_type().getVaule().equals("FACEBOOK")) { //// userDetail.setRoles(Arrays.asList("ROLE_FACEBOOK"));
// userDetail.setRoles(Arrays.asList("ROLE_FACEBOOK")); //// } else {
// } else { //// userDetail.setRoles(Arrays.asList("ROLE_USER"));
// userDetail.setRoles(Arrays.asList("ROLE_USER")); //// }
// } // return userDetail;
return userDetail; // }
}
} }

View File

@@ -10,6 +10,9 @@ spring.datasource.username=root
spring.datasource.password=uneed3515 spring.datasource.password=uneed3515
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.platform=schema spring.datasource.platform=schema
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MariaDB53Dialect
spring.jpa.database = MYSQL spring.jpa.database = MYSQL
spring.jpa.hibernate.ddl-auto=update spring.jpa.hibernate.ddl-auto=update

View File

@@ -1,28 +0,0 @@
<html>
<head>
</head>
<body>
<div class="container">
<form role="form" action="login" method="post">
<div class="form-group">
<label for="username">Username:</label>
<input type="text" class="form-control" id="username" name="username"/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input type="password" class="form-control" id="password" name="password"/>
</div>
<input type="hidden" id="csrf_token" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>
<div>
<a class="facebook-login-text" href="/mk-auth/oauth2/authorization/facebook">facebook 로그인</a>
</div>
<div>
<a class="google-login-text" href="/mk-auth/oauth2/authorization/google">google 로그인</a>
</div>
</body>
</html>

View File

@@ -0,0 +1,47 @@
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<head>
</head>
<body>
<div class="container">
<form role="form" th:action="@{/login}" method="post">
<div class="form-group row">
<label for="username" class="col-sm-2 col-form-label">ID</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="username" placeholder="id" name="username">
</div>
</div>
<div class="form-group row">
<label for="password" class="col-sm-2 col-form-label">Password</label>
<div class="col-sm-10">
<input type="password" class="form-control" id="password" placeholder="password" name="password">
</div>
</div>
<input type="hidden" id="csrf_token" name="${_csrf.parameterName}" value="${_csrf.token}"/>
<button type="submit" class="btn btn-primary">Sign in</button>
</form>
<div>
<a href="/mk-auth/oauth2/authorization/facebook" class="btn btn-primary btn-lg active" role="button" aria-pressed="false">Facebook</a>
</div>
<div>
<a href="/mk-auth/oauth2/authorization/google" class="btn btn-secondary btn-lg active" role="button" aria-pressed="false">Google</a>
</div>
</div>
</body>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</html>

View File

@@ -38,7 +38,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
public void configure(HttpSecurity http) throws Exception { public void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() http.authorizeRequests()
.antMatchers("/**", "/mk-auth/**", "/login").permitAll().anyRequest().authenticated() .antMatchers("/", "/mk-auth/**", "/login").permitAll().anyRequest().authenticated()
.and() .and()
// .csrf().requireCsrfProtectionMatcher(csrfRequestMatcher()).csrfTokenRepository(csrfTokenRepository()) // .csrf().requireCsrfProtectionMatcher(csrfRequestMatcher()).csrfTokenRepository(csrfTokenRepository())
// .and() // .and()

View File

@@ -2,13 +2,13 @@ server.port=8765
zuul.sensitive-headers= zuul.sensitive-headers=
zuul.routes.mk2-service.path=/service/** zuul.routes.mk2-service.path=/api/**
zuul.routes.mk2-service.url=http://127.0.0.1:8082 zuul.routes.mk2-service.url=http://127.0.0.1:8082
zuul.routes.mk2-service.sensitive-headers= zuul.routes.mk2-service.sensitive-headers=
zuul.routes.mk2-oauth.path=/mk-auth/** zuul.routes.mk2-oauth.path=/mk-auth/**
zuul.routes.mk2-oauth.url=https://59a7bc58.ngrok.io #zuul.routes.mk2-oauth.url=https://59a7bc58.ngrok.io
#zuul.routes.mk2-oauth.url=http://localhost:8081 zuul.routes.mk2-oauth.url=http://localhost:8081
zuul.routes.mk2-oauth.sensitive-headers= zuul.routes.mk2-oauth.sensitive-headers=
#zuul.routes.mk2-oauth.path=/mk2auth/** #zuul.routes.mk2-oauth.path=/mk2auth/**
@@ -17,18 +17,16 @@ zuul.add-proxy-headers=true
security.oauth2.sso.login-path=/login security.oauth2.sso.login-path=/login
security.oauth2.client.access-token-uri=http://localhost:8081/mk-auth/oauth/token
#security.oauth2.client.access-token-uri=https://59a7bc58.ngrok.io/mk-auth/oauth/token
#security.oauth2.client.access-token-uri=http://localhost:8081/mk-auth/oauth/token
security.oauth2.client.access-token-uri=https://59a7bc58.ngrok.io/mk-auth/oauth/token
# /oauth/authorize 요청은 클라이언트가 리소스 서버의 api를 사용하기 위해 사용자(리소스 소유자)에게 # /oauth/authorize 요청은 클라이언트가 리소스 서버의 api를 사용하기 위해 사용자(리소스 소유자)에게
# 권한 위임 동의를 받기 위한 페이지를 출력하는 기능을 수행 # 권한 위임 동의를 받기 위한 페이지를 출력하는 기능을 수행
#security.oauth2.client.user-authorization-uri=http://localhost:8081/mk-auth/oauth/authorize security.oauth2.client.user-authorization-uri=http://localhost:8081/mk-auth/oauth/authorize
security.oauth2.client.user-authorization-uri=https://59a7bc58.ngrok.io/mk-auth/oauth/authorize #security.oauth2.client.user-authorization-uri=https://59a7bc58.ngrok.io/mk-auth/oauth/authorize
#security.oauth2.resource.user-info-uri=http://localhost:8081/mk-auth/user security.oauth2.resource.user-info-uri=http://localhost:8081/mk-auth/user
security.oauth2.resource.user-info-uri=https://59a7bc58.ngrok.io/mk-auth/user #security.oauth2.resource.user-info-uri=https://59a7bc58.ngrok.io/mk-auth/user
security.oauth2.resource.prefer-token-info=false security.oauth2.resource.prefer-token-info=false
security.oauth2.client.client-id=system1 security.oauth2.client.client-id=system1