Skip to content
This repository has been archived by the owner on Aug 13, 2022. It is now read-only.

#1 인증 토큰 spring security, JWT #5

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,25 @@
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<groupId>com.pay</groupId>
<artifactId>billing</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>billing</name>
<description>billing project for Spring Boot</description>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<start-class>com.pay.billing.BillingApplication</start-class>
</properties>

<dependencies>
Expand All @@ -29,11 +34,74 @@
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>

<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>

<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

<!-- Starter for using Spring Security -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

<!-- Make method based security testing easier -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>

<!-- JSON Web Token Support -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>

<!-- JPA Data (Repositories, Entities, Hibernate, etc..) -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>

<!-- Model Mapper -->
<dependency>
<groupId>org.modelmapper</groupId>
<artifactId>modelmapper</artifactId>
<version>2.3.5</version>
</dependency>

<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>

</dependencies>

<build>
Expand Down
36 changes: 32 additions & 4 deletions src/main/java/com/pay/billing/BillingApplication.java
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 {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

특정 환경에 종속적인 이 코드가 왜 필요한지 모르겠네요~

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

테스트 시에만 넣고 배포전에 빼려고 하는데 안좋은 습관일까요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아니면 초기 db insert 스크립트에 넣는게 더 좋은 방식일까요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

말씀하신대로 진행하게되면 테스트환경과 배포환경의 소스코드가 달라질텐데 좋은 방식일까요?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

심지어 관리자 비밀번호까지 소스코드에 노출되고있네요~

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 src/main/java/com/pay/billing/common/config/SwaggerConfig.java
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");
Copy link
Member

Choose a reason for hiding this comment

The 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 src/main/java/com/pay/billing/common/config/WebSecurityConfig.java
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();
}

}
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;
}

}
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);
}

}
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);
}

}
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);
}

}
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);
}
}
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);
}

}
Loading