Skip to content

Commit

Permalink
error
Browse files Browse the repository at this point in the history
  • Loading branch information
singsangssong committed Mar 19, 2024
1 parent 9a104ec commit f17f3d0
Show file tree
Hide file tree
Showing 12 changed files with 80 additions and 10 deletions.
1 change: 1 addition & 0 deletions .idea/modules.xml

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

8 changes: 8 additions & 0 deletions .idea/modules/JWTLogIn.JWT.main.iml

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

5 changes: 5 additions & 0 deletions JWT/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,11 @@ dependencies {
implementation 'io.jsonwebtoken:jjwt-impl:0.11.2'
implementation 'io.jsonwebtoken:jjwt-jackson:0.11.2'

// Swagger
implementation 'io.springfox:springfox-boot-starter:3.0.0'
implementation 'io.springfox:springfox-swagger-ui:3.0.0'
implementation 'io.springfox:springfox-swagger2:2.9.2'

// // Spring Security
testImplementation 'org.springframework.security:spring-security-test'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
Expand Down
18 changes: 12 additions & 6 deletions JWT/src/main/java/JWTLogIn/JWT/user/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,18 @@ public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Excepti
.httpBasic(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable) // 토큰 사용하기에 csrf 불가능
.cors(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(request -> {
request.requestMatchers("/tgwing.kr", "/tgwing.kr/register", "/tgwing.kr/login").permitAll();
// 3개의 url에서는 token인증없이 접근 가능.
request.anyRequest().authenticated();
// 그 외의 url에서는 token인증없이 접근 불가능.
})
.authorizeHttpRequests(request -> request
.requestMatchers("/tgwing.kr", "/tgwing.kr/register", "/tgwing.kr/login", "/swagger-ui/**", "/v3/api-docs/**", "/swagger-ui.html",
"/webjars/**", "/swagger-resources/**")
.permitAll()
.anyRequest().authenticated()
)
// .formLogin((form) -> form
// .loginPage("/tgwing.kr/login")
// .permitAll()
// )
// .logout((logout) -> logout
// .clearAuthentication(true))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// jwt를 사용하기 때문에 session을 사용하지 않음.
.addFilterBefore(new JwtFilter(userService, secretKey), UsernamePasswordAuthenticationFilter.class)
Expand Down
30 changes: 30 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/config/Swagger.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package JWTLogIn.JWT.user.config;

import org.springframework.context.annotation.Bean;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;

public class Swagger {
@Bean
public Docket api() {
return new Docket(DocumentationType.OAS_30)
.useDefaultResponseMessages(false)
.select()
.apis(RequestHandlerSelectors.basePackage("JWTLogin.JWT"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("Hello Swagger")
.description("스웨거 기능 테스트")
.version("1.0")
.build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,16 @@ public class AdminController {
private final AuthService authService;

@GetMapping("/info/user")
public ResponseEntity<List<UserDTO>> userAll(Authentication authentication) {
public ResponseEntity<List<UserDTO>> userAll(Authentication authentication, @RequestHeader("authorization") String token) {
List<UserDTO> userAll = userService.findUserAll();
String jwt = token.split(" ")[1];
String studentId = authService.extractStudentId(jwt);

if(userAll == null)
return ResponseEntity.status(HttpStatus.NOT_FOUND).build();

System.out.println("studentId = " + studentId);

return ResponseEntity.ok(userAll);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public ResponseEntity<Void> logout() {

@DeleteMapping("/profile/delete/{id}")
public ResponseEntity<Void> deleteId(@PathVariable Long id) {
if(userService.withdrawalUser(id)) {
if(userService.deleteUser(id)) {
System.out.println("회원 삭제 완료");
return ResponseEntity.ok().build();
}
Expand Down
5 changes: 5 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/security/JwtFilter.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ public class JwtFilter extends OncePerRequestFilter {
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

final String authorization = request.getHeader(HttpHeaders.AUTHORIZATION);

log.info("Authorization : {}", authorization);
// slf4j에서 log를 찍어서 확인함.

Expand All @@ -52,6 +53,7 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
if(JwtUtil.isExpired(token, secretKey)) {
log.error("토큰이 만료됨.");
filterChain.doFilter(request, response);

return;
}

Expand All @@ -60,8 +62,11 @@ protected void doFilterInternal(HttpServletRequest request, HttpServletResponse
//이를 통해 아래 UsernamePasswordAuthenticationToken에서 userName을 사용가능함.
String name = JwtUtil.getUserName(token, secretKey);
// Level level = JwtUtil.getLevel(token, secretKey);
String studentId = JwtUtil.getStudentId(token, secretKey);

log.info("name : {}", name);
log.info("studentId : {}", studentId);

// log.info("level : {}", level);

// 권한 부여
Expand Down
5 changes: 5 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/security/JwtUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public static String getUserName(String token, String secretKey) {
.getBody().get("name", String.class);
} // userName 꺼내오기.

public static String getStudentId(String token, String secretKey) {
return Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token)
.getBody().get("studentId", String.class);
}

// public static Level getLevel(String token, String secretKey) {
// return Jwts.parserBuilder().setSigningKey(secretKey).build().parseClaimsJws(token)
// .getBody().get("level", Level.class);
Expand Down
5 changes: 5 additions & 0 deletions JWT/src/main/java/JWTLogIn/JWT/user/service/AuthService.java
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,9 @@ public class AuthService {
// public Level extractLevel(String token) {
// return JwtUtil.getLevel(token, secretKey);
// }

public String extractStudentId(String token) {
return JwtUtil.getStudentId(token, secretKey);
}

}
3 changes: 2 additions & 1 deletion JWT/src/main/java/JWTLogIn/JWT/user/service/UserService.java
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ public class UserService {

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

private final UserRepository userRepository;

public void userSave(UserDTO userDTO) throws Exception {
Expand Down Expand Up @@ -60,7 +61,7 @@ public String login(LogInDTO logInDTO){
}// login. null일 경우 회원정보 불일치함. 아닐 경우, 회원정보 일치. 회원 정보 return.


public Boolean withdrawalUser(Long id) {
public Boolean deleteUser(Long id) {
Optional<UserEntity> find = userRepository.findById(id);
if(find != null) { // 회원이 있으면 null이 아님. 이를 삭제하고 true보내서 삭제 완료를 보냄.
userRepository.deleteUser(id);
Expand Down
2 changes: 1 addition & 1 deletion JWT/src/main/resources/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ spring.datasource.password=tgwing
spring.jpa.hibernate.naming.implicit-strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create
spring.jpa.hibernate.ddl-auto=update
spring.jpa.open-in-view=false
spring.jpa.generate-ddl=true
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
Expand Down

0 comments on commit f17f3d0

Please sign in to comment.