반응형

 

 

스프링프레임워크 태그 사용법

스프링프레임워크의 JSP 기술중에 form taglib 가 있습니다. form 태그라이브러리를 사용하면 HTML 폼에 데이터를 바인딩하거나 에러메세지 처리등을 간편하게 할 수 있습니다. 스프링프레임워크 form

offbyone.tistory.com

 

 

스프링 폼태그와 벨리데이션 체크

회원가입에서 많이 사용되는 …

seonhyungjo.github.io

반응형
반응형

build.gradle에 의존성 추가

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
    implementation 'org.springframework.boot:spring-boot-starter-security'
    implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.thymeleaf.extras:thymeleaf-extras-springsecurity5'
    compileOnly 'org.projectlombok:lombok'
    runtimeOnly 'org.mariadb.jdbc:mariadb-java-client'
    annotationProcessor 'org.projectlombok:lombok'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testImplementation 'org.springframework.security:spring-security-test'
}

 

ORM 기술로 JPA, 보안을 위한 스프링 시큐리티, View 템플릿 타임리프와 롬복, MariaDB 등을 추가했습니다.

 

Config 패키지 생성 후 Sring Security 관리 클래스 생성

package com.sh.springsec.config;

import com.sh.springsec.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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.crypto.bcrypt.BCryptPasswordEncoder;

@RequiredArgsConstructor
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final UserService userService;

    @Override
    public void configure(WebSecurity web) {
        web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/login", "/signup", "/user").permitAll()
                .antMatchers("/").hasRole("USER")
                .antMatchers("/admin").hasRole("ADMIN")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .loginPage("/login") // 로그인 페이지 링크
                .defaultSuccessUrl("/") // 로그인 성공 후 리다이렉트 주소
                .and()
                .logout()
                .logoutSuccessUrl("/login") // 로그아웃 성공시 리다이렉트 주소
                .invalidateHttpSession(true); // 세션 날리기
    }

    @Override
    public void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

 

Spring Security를 사용하기 위해 WebSecurityConfigurerAdater를 상속받은 Security Config 클래스를 만들었습니다. Spring Security 사용을 위해서는 @EnableWebSecurity 어노테이션을 달아줘야 합니다. 위에서 오버라이딩한 메소드는 configure 메소드는 각각 WebSecurity, HttpSecurity와 AuthenticationManagerBuilder를 매개변수로 받습니다.

 

메소드 역할

public void configure(WebSecurity web) {

    web.ignoring().antMatchers("/css/**", "/js/**", "/img/**");

}

 

스프링 시큐리티 인증 없이도 접근 가능하게 할 경로를 설정합니다.

 

protected void configure(HttpSecurity http) throws Exception {
    http
        .authorizeRequests()
        .antMatchers("/login", "/signup", "/user").permitAll()
        .antMatchers("/").hasRole("USER")
        .antMatchers("/admin").hasRole("ADMIN")
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .loginPage("/login")
        .defaultSuccessUrl("/")
        .and()
        .logout()
        .logoutSuccessUrl("/login")
        .invalidateHttpSession(true);
}

 

권한에 따라 접근할 수 있는 경로를 지정합니다.

 

메소드 역할
.authorizeRequests() 시큐리티 처리에 HttpServletRequest를 사용
.antMatchers(String) 특정 경로를 지정
.hasRole(String) 지정된 경로에 특정 권한을 가진 사용자만 접근 가능
.permitAll() 지정된 경로에 모든 사용자가 접근 가능
.anyRequest() 위에서 지정되지 않은 경로
.authenticated() 권한을 갖지 않은 사용자를 로그인 페이지로 리다이렉트
.formLogin() 커스텀 로그인 페이지에 관한 설정
.loginPage(String) 로그인 페이지 지정
.defaultSuccessUrl(String) 로그인 성공 시 리다이렉트 할 페이지 지정
.logout() 로그아웃 설정
.logoutSuccessUrl(String) 로그아웃 성공 시 리다이렉트 할 페이지 지정
.invalidateHttpSession(boolean) 로그아웃 후 사용자 권한과 세션의 제거 여부 설정

 

반응형
반응형

Spring에서 테스트 클래스 사용을 위한 두 가지 어노테이션들에 대해 알아봅시다.

 

우선, Mokito를 사용하기 위해서는 아래와 같은 코드 작성을 해줘야 합니다. 테스트클래스 위에 @RunWith 어노테이션을 작성하여 Mock 객체를 사용하거나, @RunWith 어노테이션을 작성하지 않을 경우 setUp() 메소드를 아래처럼 만들어줍니다. 

 

@RunWith(MokitoJunitRunner.class)
public class TestClass {

}

public class TestClass {

    @BeforeEach
    public void setUp() {
        MokitoAnnotations.initMocks(this);
    }
}

 

@Mock

 

실제 인스턴스가 없는 가상의 Mock 인스턴스를 만들어 반환합니다.

 

@MockBean

 

ApplicationContext에 Mock 객체를 추가합니다.

 

@InjectMock

 

@Mock이나 @Spy 객체를 자신의 멤버 클래스와 일치하면 주입합니다.

 

@SpyBean

 

ApplicationContext에 Spy 객체를 추가합니다.

 

 

@Mock, @MockBean의 차이

 

@MockBean은 @Mock과 달리 spring-boot-test에서 제공하는 어노테이션으로, Spring이 관리하는 Bean들 중에서 하나 이상을 Mock 객체로 사용하고 싶을 때 사용합니다.

반응형
반응형

Dependency Injection

 

의존성 주입이란 말 그대로 A가 B에 의존할 때 A에 B를 주입한다는 것을 의미합니다. 즉, A가 B에 의존한다는 말은 A가 B를 사용한다는 의미와 같습니다.

 

이러한 의존 관계에서 A가 B에 의존하고 있을 때, B에 변화가 생기면 A가 영향을 받게 되고 B를 효과적으로 관리하기 위한 코드 생성이 필요합니다.

 

Spring 주입에 관한 글

 

[Spring] 생성자(Constructor) 주입, 필드(Field) 주입, 수정자(Setter) 주입

생성자 주입(Constructor Injection) 스프링에서 가장 권장하는 방식입니다. 단일 생성자인 경우에는 @Autowired 어노테이션을 붙이지 않아도 되지만 생성자가 2개 이상인 경우에는 생성자에 어노테이션

developer-rooney.tistory.com

 

반응형

+ Recent posts