Skip to content

Commit

Permalink
[Docs] 7주차 발표자료 없로드 & [Feat] 스프링 시큐리티 - #62, #63
Browse files Browse the repository at this point in the history
  • Loading branch information
82everywin committed May 27, 2024
1 parent 7decaef commit d2f68b1
Show file tree
Hide file tree
Showing 59 changed files with 362 additions and 148 deletions.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
#Mon May 20 18:55:02 KST 2024
#Mon May 27 04:36:59 KST 2024
gradle.version=8.4
Binary file not shown.
Binary file not shown.
1 change: 1 addition & 0 deletions contents/todoListAPI/hyeonseung/todolist/.idea/gradle.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 9 additions & 2 deletions contents/todoListAPI/hyeonseung/todolist/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,16 @@ dependencies {
testCompileOnly 'org.projectlombok:lombok'
testAnnotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
// implementation 'com.google.code.gson:gson:2.8.8'
}
// implementation 'com.google.code.gson:gson:2.8.8'

// security
implementation 'org.springframework.boot:spring-boot-starter-security'
// jwt
implementation 'io.jsonwebtoken:jjwt-api:0.11.5'
implementation 'io.jsonwebtoken:jjwt-impl:0.11.5'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.5'

}
tasks.named('test') {
useJUnitPlatform()
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@

@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2024-05-20T17:24:02+0900",
comments = "version: 1.5.3.Final, compiler: IncrementalProcessingEnvironment from gradle-language-java-8.7.jar, environment: Java 17.0.10 (Oracle Corporation)"
date = "2024-05-27T17:08:26+0900",
comments = "version: 1.5.3.Final, compiler: IncrementalProcessingEnvironment from gradle-language-java-8.4.jar, environment: Java 17.0.10 (Oracle Corporation)"
)
public class MemberMapperImpl implements MemberMapper {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

@Generated(
value = "org.mapstruct.ap.MappingProcessor",
date = "2024-05-20T17:24:02+0900",
comments = "version: 1.5.3.Final, compiler: IncrementalProcessingEnvironment from gradle-language-java-8.7.jar, environment: Java 17.0.10 (Oracle Corporation)"
date = "2024-05-27T17:08:26+0900",
comments = "version: 1.5.3.Final, compiler: IncrementalProcessingEnvironment from gradle-language-java-8.4.jar, environment: Java 17.0.10 (Oracle Corporation)"
)
public class TodoMapperImpl implements TodoMapper {

Expand Down

This file was deleted.

Original file line number Diff line number Diff line change
@@ -1,28 +1,29 @@
spring.application.name=todolist

## DB 설정
## DB 설정

# MySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

# DB Source URL
spring.datasource.url=jdbc:mysql://localhost:3306/todolist?
spring.datasource.url=jdbc:mysql://localhost:3306/todolist
#characterEncoding=UTF-8&serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=root

# DDL(create,alter,drop)
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.ddl-auto=create

#sql 보여주기
#sql 보여주기
spring.jpa.show-sql=true

spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.format_sql=true


#DRIVER SETTING
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
#spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect

#SERVER PORT SETTING
#server.port=UR_PORT
# jwt
jwt.secret=VlwEyVBsYt9V7zq57TejMnVUyzblYcfPQye08f7MGVA9XkHa
jwt.token-validity-in-seconds=86400000
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

This file was deleted.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.

This file was deleted.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package com.todolist.todolist.config;

import com.todolist.todolist.domain.Member;
import com.todolist.todolist.security.JwtTokenProvider;
import com.todolist.todolist.service.MemberService;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.List;

@Component
@RequiredArgsConstructor
public class JwtTokenFilter extends OncePerRequestFilter {

private final MemberService memberService;

private final JwtTokenProvider jwtTokenProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
String authorizationHeader = request.getHeader(HttpHeaders.AUTHORIZATION);

// 토큰 전송 x -> 로그인 x
if(authorizationHeader == null){
filterChain.doFilter(request, response);
return;
}

// "Bearer"로 시작 x -> 잘못된 토큰
if(!authorizationHeader.startsWith("Bearer")){
filterChain.doFilter(request, response);
return;
}

String token = authorizationHeader.split(" ")[1];

if(jwtTokenProvider.isExpired(token)){
filterChain.doFilter(request, response);
return;
}

String loginId = jwtTokenProvider.getLoginIdFromToken(token);

if ( loginId != null && SecurityContextHolder.getContext().getAuthentication() == null) {

if (jwtTokenProvider.validateToken(token,loginId)) {
Member loginMember = memberService.throwFindbyLoginId(loginId);

UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
loginMember.getLoginId(), null, List.of(new SimpleGrantedAuthority(loginMember.getRole().name())));

authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
filterChain.doFilter(request, response);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.todolist.todolist.config;

import com.todolist.todolist.security.JwtTokenProvider;
import com.todolist.todolist.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Autowired
private JwtTokenFilter jwtTokenFilter;

@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// CSRF 토큰 없이 요청 처리
.csrf((csrfConfig) ->
csrfConfig.disable())
.cors((corsConfig) ->
corsConfig.disable())
.sessionManagement((sessionManagement) ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests((authorizeRequests) ->
authorizeRequests
.requestMatchers("/","/swagger-ui/**","/v3/api-docs/**").permitAll()
.requestMatchers("/api/members","api/members/login").permitAll()
.anyRequest().authenticated())
.addFilterBefore(jwtTokenFilter, UsernamePasswordAuthenticationFilter.class);

return http.build();
}


}
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
package com.todolist.todolist.controller;


import com.todolist.todolist.config.JwtTokenFilter;
import com.todolist.todolist.dto.member.MemberLoginResponseDto;
import com.todolist.todolist.dto.member.MemberResponseDto;
import com.todolist.todolist.dto.member.MemberRequestDto;
import com.todolist.todolist.security.CustomUserDetailService;
import com.todolist.todolist.security.JwtTokenProvider;
import com.todolist.todolist.service.MemberService;
import io.swagger.v3.oas.annotations.Operation;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand All @@ -20,6 +25,13 @@
public class MemberController {
private final MemberService memberService;

@Value("${jwt.secret")
private String key;

private final JwtTokenProvider jwtTokenProvider;

private CustomUserDetailService userDetailService;

@Operation(summary = "회원가입")
@PostMapping
public ResponseEntity<MemberResponseDto> createMember(@Valid @RequestBody MemberRequestDto request) {
Expand All @@ -30,9 +42,13 @@ public ResponseEntity<MemberResponseDto> createMember(@Valid @RequestBody Member

@Operation(summary = "로그인")
@PostMapping("/login")
public ResponseEntity<MemberLoginResponseDto> loginMember(@RequestBody @Valid MemberRequestDto.LoginRequestDto request){
public String loginMember(@RequestBody @Valid MemberRequestDto.LoginRequestDto request){
MemberLoginResponseDto responseDto = memberService.login(request);
return ResponseEntity.status(HttpStatus.CREATED).body(responseDto);

String jwtToken = jwtTokenProvider.createToken(request.getLoginId());

return jwtToken;
// return ResponseEntity.status(HttpStatus.CREATED).body(responseDto);
}
@Operation(summary = "회원정보 수정")
@PutMapping("/{memberId}")
Expand Down Expand Up @@ -65,5 +81,4 @@ public ResponseEntity<Void> delete(@PathVariable Long memberId){
return ResponseEntity.noContent().build();
}


}
Loading

0 comments on commit d2f68b1

Please sign in to comment.