로그인 페이지 만들기

ttaho·2023년 2월 25일
0

Project-board

목록 보기
9/16

로그인 페이지를 만들기 위해
우선, 보안관련 디펜던시를 추가해주자.

디펜던시 추가 후, localhost:8080/articles를 요청하게되면

기존의 게시판 페이지가 아닌, 로그인 페이지가 나오게된다.
다만 이대로 두면 Security기능 때문에 아무것도 할 수가 없다.
로그인을 누르면 데이터베이스에서 정보를 조회해서 인증하는 로직을 구현하지 않았기때문에, 미리 securityconfig를 잡아서 해결해야한다.
SecurityConfig를 생성하자.

package com.fastcampus.projectboard.config;

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.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        return http
                .authorizeHttpRequests(auth -> auth.anyRequest().permitAll())
                .formLogin().and()
                .build();
    }
}

다시 localhost:8080/articles를 요청하게되면, 게시판 페이지를 확인할 수 있다.

이로써, login 페이지와 logout 페이지를 localhost:8080/login, localhost:8080/logout으로 요청할 수 있다.

추가적으로 테스트를 해보기 위해,
AuthControllerTest.java를 생성해주었다.

package com.fastcampus.projectboard.controller;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;

@DisplayName("View 컨트롤러 - 인증")
@Import(SecurityConfig.class) //SecurityConfig를 읽게만들어줌. 안하니까 로그인페이지 테스트가 안돌아간다.
@WebMvcTest
public class AuthControllerTest {

    private final MockMvc mvc;

    public AuthControllerTest(@Autowired MockMvc mvc) {
        this.mvc = mvc;
    }

    @DisplayName("[view] [GET] 로그인 페이지 - 정상 호출")
    @Test
    public void givenNothing_whenTryingToLogIn_thenReturnsLogInView() throws Exception {

        //Given

        //When & Then
        mvc.perform(get("/login"))
                .andExpect(status().isOk())
                .andExpect(content().contentTypeCompatibleWith(MediaType.TEXT_HTML)); //exactmatch를 피하기위해 CompatibleWith를 사용
                //.andExpect(view().name("")) //이건 안해준다 자동생성이기때문에!
                //.andExpect(model().attributeExists(""));// 이것도 안해준다. 따로 attribute없어서.

    }
}

기존의 게시글,댓글 테스트와는 달리 자동으로 생성해준 페이지 이기 때문에, view().name과, model().attribute존재 확인은 해주지 않는다.

profile
백엔드 꿈나무

0개의 댓글