This repository has been archived by the owner on Aug 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
#1 인증 토큰 spring security, JWT #5
Open
junshock5
wants to merge
4
commits into
master
Choose a base branch
from
feature/1
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,13 +1,41 @@ | ||
package com.pay.billing; | ||
|
||
import com.pay.billing.domain.model.Role; | ||
import com.pay.billing.domain.model.User; | ||
import com.pay.billing.service.UserService; | ||
import org.modelmapper.ModelMapper; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.boot.CommandLineRunner; | ||
import org.springframework.boot.SpringApplication; | ||
import org.springframework.boot.autoconfigure.SpringBootApplication; | ||
import org.springframework.context.annotation.Bean; | ||
|
||
import java.util.ArrayList; | ||
import java.util.Arrays; | ||
|
||
@SpringBootApplication | ||
public class BillingApplication { | ||
public class BillingApplication implements CommandLineRunner { | ||
|
||
public static void main(String[] args) { | ||
SpringApplication.run(BillingApplication.class, args); | ||
} | ||
|
||
@Bean | ||
public ModelMapper modelMapper() { | ||
return new ModelMapper(); | ||
} | ||
|
||
@Autowired | ||
UserService userService; | ||
|
||
public static void main(String[] args) { | ||
SpringApplication.run(BillingApplication.class, args); | ||
} | ||
@Override | ||
public void run(String... params) throws Exception { | ||
User admin = new User(); | ||
admin.setUsername("admin"); | ||
admin.setPassword("admin"); | ||
admin.setEmail("admin@email.com"); | ||
admin.setRoles(new ArrayList<Role>(Arrays.asList(Role.ROLE_ADMIN))); | ||
|
||
userService.signup(admin); | ||
} | ||
} |
67 changes: 67 additions & 0 deletions
67
src/main/java/com/pay/billing/common/config/SwaggerConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,67 @@ | ||
package com.pay.billing.common.config; | ||
|
||
import com.google.common.base.Predicates; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import springfox.documentation.builders.ApiInfoBuilder; | ||
import springfox.documentation.builders.PathSelectors; | ||
import springfox.documentation.builders.RequestHandlerSelectors; | ||
import springfox.documentation.service.ApiInfo; | ||
import springfox.documentation.service.ApiKey; | ||
import springfox.documentation.service.AuthorizationScope; | ||
import springfox.documentation.service.SecurityReference; | ||
import springfox.documentation.service.Tag; | ||
import springfox.documentation.spi.DocumentationType; | ||
import springfox.documentation.spi.service.contexts.SecurityContext; | ||
import springfox.documentation.spring.web.plugins.Docket; | ||
import springfox.documentation.swagger2.annotations.EnableSwagger2; | ||
|
||
import java.util.Arrays; | ||
import java.util.Collections; | ||
import java.util.List; | ||
import java.util.Optional; | ||
|
||
@Configuration | ||
@EnableSwagger2 | ||
public class SwaggerConfig { | ||
@Bean | ||
public Docket swaggerApi() { | ||
return new Docket(DocumentationType.SWAGGER_2) // Swagger 설정의 핵심이 되는 Bean, API 자체에 대한 스펙은 컨트롤러에서 작성 | ||
.select() // ApiSelectorBuilder를 생성 | ||
.apis(RequestHandlerSelectors.any()) // GetMapping, PostMapping ... 이 선언된 API를 문서화 | ||
.paths(Predicates.not(PathSelectors.regex("/error"))) // apis()로 선택되어진 API중 특정 path 조건에 맞는 API들을 다시 필터링하여 문서화 | ||
.build() | ||
.apiInfo(swaggerInfo()) // 제목, 설명 등 문서에 대한 정보들을 보여주기 위해 호출 | ||
.useDefaultResponseMessages(false) // false로 설정하면, swagger에서 제공해주는 응답코드 ( 200,401,403,404 )에 대한 기본 메시지를 제거 | ||
.securitySchemes(Collections.singletonList(apiKey())) // securitySchemesAPI가 지원하는 모든 보안 체계를 정의 하는 데 사용 security하고 전체 API 또는 개별 작업에 특정 체계를 적용 | ||
.securityContexts(Collections.singletonList(securityContext())) // SecurityScheme 및 SecurityContext 지원을 사용하여 보안 API에 액세스하도록 Swagger를 구성 | ||
.tags(new Tag("users", "Operations about users")) // 여러 개의 태그를 정의할 수도 있습니다. | ||
.genericModelSubstitutes(Optional.class); // 각 제네릭 클래스를 직접 매개 변수화 된 유형으로 대체합니다. | ||
} | ||
|
||
private ApiInfo swaggerInfo() { | ||
return new ApiInfoBuilder().title("빌링 시스템 개발") | ||
.description("카드결제 / 결제취소 / 결제정보 조회 REST API 개발 문서입니다").build(); | ||
} | ||
|
||
// 보안 체계(Authorization)를 jwt를 header에 삽입하여 사용 | ||
private ApiKey apiKey() { | ||
return new ApiKey("Authorization", "Authorization", "header"); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 이런것들은 어떤 의도로 추가하신건지 주석이 필요하네요 |
||
} | ||
|
||
// 보안 컨텍스트를 API에 적용 | ||
private SecurityContext securityContext() { | ||
return SecurityContext.builder() | ||
.securityReferences(defaultAuth()) | ||
.forPaths(PathSelectors.any()) | ||
.build(); | ||
} | ||
|
||
// 인증 범위 및 참조 이름 설정 | ||
private List<SecurityReference> defaultAuth() { | ||
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything"); | ||
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1]; | ||
authorizationScopes[0] = authorizationScope; | ||
return Arrays.asList(new SecurityReference("Authorization", authorizationScopes)); | ||
} | ||
} |
87 changes: 87 additions & 0 deletions
87
src/main/java/com/pay/billing/common/config/WebSecurityConfig.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
package com.pay.billing.common.config; | ||
|
||
import com.pay.billing.common.security.JwtTokenFilterConfigurer; | ||
import com.pay.billing.common.security.JwtTokenProvider; | ||
import org.springframework.beans.factory.annotation.Autowired; | ||
import org.springframework.context.annotation.Bean; | ||
import org.springframework.context.annotation.Configuration; | ||
import org.springframework.security.authentication.AuthenticationManager; | ||
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; | ||
import org.springframework.security.config.annotation.web.builders.HttpSecurity; | ||
import org.springframework.security.config.annotation.web.builders.WebSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; | ||
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; | ||
import org.springframework.security.config.http.SessionCreationPolicy; | ||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; | ||
import org.springframework.security.crypto.password.PasswordEncoder; | ||
|
||
@Configuration | ||
@EnableWebSecurity | ||
@EnableGlobalMethodSecurity(prePostEnabled = true) | ||
/* | ||
WebSecurityConfigurerAdapter는 사용자 지정 보안 구성을 제공하도록 확장 됩니다. | ||
이 클래스에서 아래 Bean이 구성되고 인스턴스화됩니다. | ||
- JwtTokenFilter | ||
- PasswordEncoder | ||
*/ | ||
public class WebSecurityConfig extends WebSecurityConfigurerAdapter { | ||
|
||
@Autowired | ||
private JwtTokenProvider jwtTokenProvider; | ||
|
||
@Override | ||
// 메서드 내에서 보호, 비보호 API 엔드 포인트를 정의하는 패턴을 구성합니다. | ||
// 쿠키를 사용하지 않기 때문에 CSRF 보호를 비활성화했습니다. | ||
protected void configure(HttpSecurity http) throws Exception { | ||
|
||
http.csrf().disable(); | ||
|
||
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS); | ||
|
||
http.authorizeRequests() | ||
.antMatchers("/users/signin").permitAll() | ||
.antMatchers("/users/signup").permitAll() | ||
.antMatchers("/h2-console/**/**").permitAll() | ||
// 다른것들은 모두 비활성화 | ||
.anyRequest().authenticated() | ||
.and() | ||
.formLogin() | ||
.defaultSuccessUrl("/swagger-ui.html"); | ||
|
||
// 인증 오류 처리시 accessDenied.jsp 페이지 지정 | ||
http.exceptionHandling().accessDeniedPage("/login?error"); | ||
|
||
// Security에 JWT 적용 | ||
http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider)); | ||
|
||
} | ||
|
||
@Override | ||
public void configure(WebSecurity web) throws Exception { | ||
// 인증없이 swagger에는 사용하게 설정 | ||
web.ignoring().antMatchers("/v2/api-docs") | ||
.antMatchers("/swagger-resources/**") | ||
.antMatchers("/swagger-ui.html") | ||
.antMatchers("/configuration/**") | ||
.antMatchers("/webjars/**") | ||
.antMatchers("/public") | ||
|
||
// Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production) | ||
.and() | ||
.ignoring() | ||
.antMatchers("/h2-console/**/**"); | ||
; | ||
} | ||
|
||
@Bean | ||
public PasswordEncoder passwordEncoder() { | ||
return new BCryptPasswordEncoder(12); | ||
} | ||
|
||
@Override | ||
@Bean | ||
public AuthenticationManager authenticationManagerBean() throws Exception { | ||
return super.authenticationManagerBean(); | ||
} | ||
|
||
} |
26 changes: 26 additions & 0 deletions
26
src/main/java/com/pay/billing/common/exception/token/validateTokenException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
package com.pay.billing.common.exception.token; | ||
|
||
import org.springframework.http.HttpStatus; | ||
|
||
public class validateTokenException extends RuntimeException { | ||
|
||
private static final long serialVersionUID = 1L; | ||
|
||
private final String message; | ||
private final HttpStatus httpStatus; | ||
|
||
public validateTokenException(String message, HttpStatus httpStatus) { | ||
this.message = message; | ||
this.httpStatus = httpStatus; | ||
} | ||
|
||
@Override | ||
public String getMessage() { | ||
return message; | ||
} | ||
|
||
public HttpStatus getHttpStatus() { | ||
return httpStatus; | ||
} | ||
|
||
} |
9 changes: 9 additions & 0 deletions
9
src/main/java/com/pay/billing/common/exception/user/UserDeleteException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package com.pay.billing.common.exception.user; | ||
|
||
public class UserDeleteException extends RuntimeException { | ||
|
||
public UserDeleteException(String msg) { | ||
super(msg); | ||
} | ||
|
||
} |
13 changes: 13 additions & 0 deletions
13
src/main/java/com/pay/billing/common/exception/user/UserInsertException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
package com.pay.billing.common.exception.user; | ||
|
||
import org.springframework.http.HttpStatus; | ||
import org.springframework.web.bind.annotation.ResponseStatus; | ||
|
||
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) | ||
public class UserInsertException extends RuntimeException { | ||
|
||
public UserInsertException(String msg) { | ||
super(msg); | ||
} | ||
|
||
} |
14 changes: 14 additions & 0 deletions
14
src/main/java/com/pay/billing/common/exception/user/UserLoginException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
package com.pay.billing.common.exception.user; | ||
|
||
import org.springframework.http.HttpStatus; | ||
import org.springframework.web.bind.annotation.ResponseStatus; | ||
|
||
// Unprocessable Entity | ||
@ResponseStatus(value = HttpStatus.UNPROCESSABLE_ENTITY) | ||
public class UserLoginException extends RuntimeException { | ||
|
||
public UserLoginException(String msg) { | ||
super(msg); | ||
} | ||
|
||
} |
15 changes: 15 additions & 0 deletions
15
src/main/java/com/pay/billing/common/exception/user/UserNotFoundException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,15 @@ | ||
package com.pay.billing.common.exception.user; | ||
|
||
import lombok.Getter; | ||
import org.springframework.http.HttpStatus; | ||
import org.springframework.web.bind.annotation.ResponseStatus; | ||
|
||
@Getter | ||
@ResponseStatus(value = HttpStatus.NOT_FOUND) | ||
public class UserNotFoundException extends RuntimeException { | ||
private String memberId; | ||
|
||
public UserNotFoundException(String memberId) { | ||
super("Member not found : " +memberId); | ||
} | ||
} |
9 changes: 9 additions & 0 deletions
9
src/main/java/com/pay/billing/common/exception/user/UserUpdateException.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
package com.pay.billing.common.exception.user; | ||
|
||
public class UserUpdateException extends RuntimeException { | ||
|
||
public UserUpdateException(String msg) { | ||
super(msg); | ||
} | ||
|
||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
특정 환경에 종속적인 이 코드가 왜 필요한지 모르겠네요~
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
테스트 시에만 넣고 배포전에 빼려고 하는데 안좋은 습관일까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
아니면 초기 db insert 스크립트에 넣는게 더 좋은 방식일까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
말씀하신대로 진행하게되면 테스트환경과 배포환경의 소스코드가 달라질텐데 좋은 방식일까요?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
심지어 관리자 비밀번호까지 소스코드에 노출되고있네요~