개발 기록/Java

[Springboot] 기본작업 #3 - WebSecurityConfig 구성과 접속 확인

JasonM 2023. 5. 25. 18:07
반응형

Springboot 프로젝트 생성을 마쳤다면 가장 먼저 하고 싶은 일은 아마도 내가 만든 앱이 일단 접속이 되는지 확인하는 것일 것 같다. 브라우저에 localhost:8080을 쳐서 뭐라도 떠야 안심이 되지 않을까?
 
접속이 잘 되는지 확인이 되기 전에 전체적인 어플리케이션의 구조가 만들어지고 Framework 환경 안에서 잘 돌아가려면 몇 가지 작업은 필요하다. 
 
그중에 가장 처음 할 일은 WebSecurityConfig를 설정하는 것이다.
 
Spring Framework의 security에 해당하며, 이 설정 파일 하나로 모든 보안 통제를 다 설정할 수 있어서 Spring Security는 Spring Framework 의 수많은 클래스 중에서도 Spring이 추구하고자 하는 방향이 가장 매력적으로 나타나는 부분이 아닐까 싶다.
 

[참고] 시작하기 전에

예전에는 WebSecurityConfigurerAdapter 클래스를 extend 해서 구성을 했었는데, Spring의 공지에 따라 
Spring Security 5.7.0-M2에서는 사용자가 구성 요소 기반 보안 구성으로 이동하도록 권장하므로 WebSecurityConfigurerAdapter를 더 이상 사용하지 않는다고 한다.
 

예전 WebSecurityConfigurerAdapter를 사용하던 방식

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		/*
		*
		*
		*/
	}
}

 
상세 내용은 아래 Spring 웹사이트 참조

https://spring.io/blog/2022/02/21/spring-security-without-the-websecurityconfigureradapter

 

Spring | Home

Cloud Your code, any cloud—we’ve got you covered. Connect and scale your services, whatever your platform.

spring.io

 


반응형

 

접속 테스트 준비

 

1. 폴더 생성

다시 본론으로 들어가서, 우선 폴더를 몇 개 만들어야 하는데 Security 설정해야 하니 일단 security와 누군가 브라우저를 통해 웹 페이지를 요청했을 때 받아줄 controller 폴더를 만들고, 어차피 만들 테니 model, repository, service, util 등도 미리 그냥 만들었다.
 
지금 단계에서는 security와 controller 폴더만 있어도 무방하다.
 

신규 프로젝트에 폴더 생성 한 화면

 

2. WebSecurityConfig.java 생성

security 폴더에 WebSecurityConfig.java 를 만들고 아래 코드를 복사

package com.jsonm.dev.demo.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
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.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import nz.net.ultraq.thymeleaf.LayoutDialect;


@Configuration
@EnableWebSecurity
public class WebSecurityConfig {
    @Bean
    public SecurityFilterChain filterChain (final HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/**").permitAll()
            .and()
            	.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
            	.formLogin().disable()
                .csrf().disable();
                
        return http.build();
        
    }
}

antMatchers("/**").permitAll() 은 localhost:8080/ 아래 모든 경로를 전부 접근 허용하겠다는 의미임.
나머지는 추후 설명하는 것으로...
 
 

3. MainViewController.java 생성

별다른 에러가 없었다면 다음으로는 controller 폴더에 MainViewController.java 파일을 만든 뒤에 아래 코드를 복사

package com.jsonm.dev.demo.controller;

import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class MainViewController {

    @GetMapping("/test")
    public String userListView(HttpServletRequest req) {
        return "test";
    }
    
}

return "test"를 통해 resources/templates 폴더에 있는 test.html을 브라우저로 내려준다.
 
 

4. test.html 생성

다음으로는 resources/templates 폴더에 test.html 파일을 만든 뒤에 아래 코드를 복사

<!DOCTYPE html>
<html>
<head>
	<title>jsonm demo</title>
	<meta name="description" content="jsonm demo 페이지 입니다"/>
	<meta property="og:description" content="jsonm demo 페이지 입니다"/>
	<meta property="og:title" content="jsonm demo"/>
</head>
<body>
	<h1>접속에 성공했습니다.</h1>
</body>
</html>

정석은 HelloWorld를 찍는 거 같은데 정석은 모르고 또 찾아보기도 귀찮아서 그냥 마음대로 test html 작성. 접속해서 화면만 보이면 되는 거 아닌가? ^^;
 
 

파일 3개를 만든 후 프로젝트 구조

[파일 3개 만든 후 프로젝트 모습]

 
이렇게 파일 3개 생성이 완료되면 기본 접속 테스트를 위한 준비는 모두 끝났다.
 
 
 
[주의 사항]
파일 생성할 때 여기저기서 복사하다보면 MS949로 인코딩이 되어있는 경우가 있는데, 파일명 우클릭 Properties에서 UTF-8로 반드시 바꿔줘야 한다. 

이클립스 파일 인코딩 MS949 to UTF-8

 

 

5. Spring Boot 실행

이제 Spring Boot 앱을 실행시켜 보자.
[프로젝트명 우클릭] → [Run As] → [3 Spring Boot App] 을 하면 Spring Boot App 실행! 
 

Spring Boot App 실행 메뉴
Spring Boot App 실행 메뉴

 
 
 
실행 후 콘솔에 Tomcat started on port(s): 8080 (http) with context path '' 이런 내용이 찍혔으면 서버 기동 성공이다.

tomcat 기동 완료 로그
Tomcat 정상실행 로그

 
 
Tomcat 기동에 성공했다면, 브라우저를 열고 http://localhost:8080/test 으로 가보자. 무엇이 보이는지...
 


정리

결론적으로 최소한으로 셋업 된 상태의 Springboot 앱을 보면 아래와 같다. 
 

  • SecurityConfiguration: 접속 권한을 설정한다. 
  • Controller: 주소에 해당하는 요청이 들어올 경우 정의된 화면을 응답으로 내려준다.
  • HTML: Controller에 의해 호출된 페이지를 사용자 브라우저에 출력해 준다.

본격적으로 어플리케이션을 개발하기 전, 위 3가지만 정확하게 알면 이 기본 세팅 위에 얼마든지 원하는 로직을 구현할 수 있다. 개발자는 오로지 비즈니스 로직 구현에 집중을 할 수 있게 구조를 잡아주는 것이 가장 직접적으로 Spring이 가진 사상을 느끼게 해 주는 부분이다. 물론 Spring을 Pedal to the metal로 파고들어서 Spring Master가 되는 것도 좋은 경험이 되겠지만, 공장 돌리듯 빠른 개발을 통해 빠르게 Output을 만들어 내는 것에 초첨을 맞추고 있기 때문에 Spring에 대한 공부는 시간이 허락할 때 차근차근 알아 보면 좋을 것 같다  :D
 
 
Web Application 하나를 스크래치부터 구현하려면 정말 많은 시간과 노력이 필요한데, 접근 권한, 사용자 요청 URL, 화면만 정의해 주면 나머지는 Spring이 알아서 다 해주니 웹 어플리케이션 개발이 얼마나 쉬워졌는지 정말 놀라울 따름이다. Thank you Spring!
 
 

 


 

 

 

[Springboot] 기본작업 #2 - 이클립스에서 프로젝트 생성과 의존성 설정

이클립스에서 개발환경 세팅이 완료되면 Spring Boot Project를 생성할 수 있다. 여기서는 이클립스에서 신규 프로젝트 생성하는 방법과 gradle.build 파일을 통해 Java 기반 프로그램의 의존성을 설정하

jsonm.tistory.com

 

 

[SpringBoot] 스프링부트 기초 #4 - applicaion.yml 환경 분리

application.yml 파일 하나로 로컬, 개발 및 운영서버 각각의 환경 설정이 가능하다. 여기서는 단일 yml 파일과 Tomcat의 setenv.sh 파일을 이용해서 구성하는 방법을 사용했다. 공부차원에서 로컬에서만

jsonm.tistory.com

 

 

 

반응형