JWT_Juniter_Testing backend done

This commit is contained in:
xigmaz
2024-07-12 07:56:49 +09:00
parent dd9f288c59
commit 59078762b5
7 changed files with 155 additions and 4 deletions

View File

@@ -62,12 +62,13 @@ xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/
</dependency> </dependency>
<!-- 메모리 DB 테스트목적 <!-- 메모리 DB 테스트목적 -->
<dependency> <dependency>
<groupId>com.h2database</groupId> <groupId>com.h2database</groupId>
<artifactId>h2</artifactId> <artifactId>h2</artifactId>
<scope>runtime</scope> <scope>test</scope>
</dependency </dependency>
<!--
<dependency> <dependency>
<groupId></groupId> <groupId></groupId>
<artifactId></artifactId> <artifactId></artifactId>

View File

@@ -0,0 +1,32 @@
package com.packt.cardatabase;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.MediaType;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;
@Component
public class AuthEntryPoint implements AuthenticationEntryPoint {
@Override
public void commence(
HttpServletRequest request,
HttpServletResponse response,
AuthenticationException authException)
throws IOException, ServletException{
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
PrintWriter writer = response.getWriter();
writer.println("Errorrr: " + authException.getMessage() );
}
}

View File

@@ -1,5 +1,7 @@
package com.packt.cardatabase; package com.packt.cardatabase;
import java.util.Arrays;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
@@ -19,6 +21,9 @@ import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import com.packt.cardatabase.service.UserDetailsServiceImpl; import com.packt.cardatabase.service.UserDetailsServiceImpl;
@@ -30,6 +35,10 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired @Autowired
private AuthenticationFilter authenticationFilter; private AuthenticationFilter authenticationFilter;
@Autowired
private AuthEntryPoint exceptionHandler;
/* /*
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
@Bean @Bean
@@ -56,7 +65,7 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override @Override
protected void configure(HttpSecurity http) throws Exception { protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable() http.csrf().disable().cors().and()
.sessionManagement() .sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS).and() .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests() .authorizeRequests()
@@ -64,8 +73,43 @@ public class SecurityConfig extends WebSecurityConfigurerAdapter {
.antMatchers(HttpMethod.POST, "/login").permitAll() .antMatchers(HttpMethod.POST, "/login").permitAll()
// 다른 모든 요청은 보호됨 // 다른 모든 요청은 보호됨
.anyRequest().authenticated().and() .anyRequest().authenticated().and()
.exceptionHandling()
.authenticationEntryPoint(exceptionHandler).and()
.addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class); .addFilterBefore(authenticationFilter, UsernamePasswordAuthenticationFilter.class);
} }
@Bean
CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Arrays.asList("*"));
config.setAllowedMethods(Arrays.asList("*"));
config.setAllowedHeaders(Arrays.asList("*"));
config.setAllowCredentials(false);
config.applyPermitDefaultValues();
//출처 http://localhost:3000 를 명시적으로 허용하려면
//config.setAllowedOrigins(Arrays.asList("http://localhost:3000"));
source.registerCorsConfiguration("/**", config);
return source;
}
} }

View File

@@ -1,7 +1,11 @@
package com.packt.cardatabase.domain; package com.packt.cardatabase.domain;
import java.util.Optional;
import org.springframework.data.repository.*; import org.springframework.data.repository.*;
public interface OwnerRepository extends CrudRepository<Owner, Long>{ public interface OwnerRepository extends CrudRepository<Owner, Long>{
Optional<Owner> findByFirstname(String firstName);
} }

View File

@@ -0,0 +1,28 @@
package com.packt.cardatabase;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultHandlers.print;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.HttpHeaders;
import org.springframework.test.web.servlet.MockMvc;
@SpringBootTest
@AutoConfigureMockMvc
public class CarRestTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testAuthentication() throws Exception {
// Testing authentication with correct credentials
this.mockMvc.perform(post("/login").content("{\"username\":\"admin\", \"password\":\"admin\"}").
header(HttpHeaders.CONTENT_TYPE, "application/json")).
andDo(print()).andExpect(status().isOk());
}
}

View File

@@ -1,13 +1,24 @@
package com.packt.cardatabase; package com.packt.cardatabase;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import com.packt.cardatabase.web.CarController;
@SpringBootTest @SpringBootTest
class CardatabaseApplicationTests { class CardatabaseApplicationTests {
@Autowired
private CarController controller;
@Test @Test
@DisplayName("First example test case")
void contextLoads() { void contextLoads() {
assertThat(controller).isNotNull();
} }
} }

View File

@@ -0,0 +1,31 @@
package com.packt.cardatabase;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import com.packt.cardatabase.domain.Owner;
import com.packt.cardatabase.domain.OwnerRepository;
@DataJpaTest
public class OwnerRepositoryTest {
@Autowired
private OwnerRepository repository;
@Test
void saveOwner() {
repository.save(new Owner("Lucy", "Smith"));
assertThat(repository.findByFirstname("Lucy").isPresent()).isTrue();
}
@Test
void deleteOwners() {
repository.save(new Owner("Lisa", "Morrison"));
repository.deleteAll();
assertThat(repository.count()).isEqualTo(0);
}
}