솔적솔적

Spring Boot Security - 환경설정 & 시큐리티 설정 본문

Back-end/Spring Boot Security

Spring Boot Security - 환경설정 & 시큐리티 설정

카드값줘체리 2022. 2. 7. 10:09

사용 DB : MySQL

사용 tool : Spring Boot (sts-4.11.0.RELEASE)

먼저 프로젝트를 만들 때 

 

MySQL에 들어가서 

프로젝트 셋팅이 다 이뤄지면 src/main/resources안에 application.proerties를 yml파일로 변경

application.yml안에 넣은 코드들

 

com.sol.security2안에 Config 패키지 생성,

 

com.sol.security2안에 Controller 패키지 생성하고 IndexController생성 

그리고 코드를 짤 때  템플릿엔진을 mustach를 설정파일을 안에 넣어 사용

머스테치 기본폴더 src/main/resources/
뷰리졸버 설정 시 : templates를 prefix로 잡고 , .mustache를 suffix로 잡아 세팅한다.

 

원래 application.yml부분에 

입력하여 놨었으나 이건 없어도 괜찮다. 왜 없어도 가능할까? 

그건 아까 보여줬듯이 우리가 머스터치를 사용하겠다고 의존성 등록을 해줬기 때문이다.

 

웹브라우저로 보여줄 html파일 만들기

 

temlates안에 index.html 생성

 

config패키지 안에 WebMvcConfig.java 생성

 

오버라이딩 후 내부 구성짜기

 

해당 뷰리졸버, Mustache를 재설정하기 위한오버라이딩

resolver.setCharset("UTF-8"); → 내가 만든 view에 인코딩은 기본적으로 UTF-8로 설정한다.

resolver.setContentType("text/html; charset=UTF-8"); → 너한테 던지는 데이터는 html 파일이고 이 파일이 UTF-8이다.

resolver.setSuffix(".html"); → html으로 바꾸면 머스터치가 인식을 한다. 

 

실행 후

 

console에 

Using generate security password가 나온다. 

 

localhost:8080을 검색하면 

이런 화면의 로그인 페이지로 이동하게된다.

어? 아까 html파일에 <h2>첫 페이지</h2> 라고 해서 작성한 것이 떠야하는거 아닌가?

하지만, 

시큐리티로 의존성을 설정하게되면 홈페이지로 들어가는 모든 주소가 바뀌어 인증하는 홈페이지가 된다.

아이디와 비밀번호를 입력할 때 아까 console에 나온 (Using generate security password)을 비밀번호에 넣는다면 아까 만든 index.html에 써 놓았던 '첫 페이지'라는 글자가 보이게된다. 이게 정상작동.

 

| 시큐리티 설정

 

indexController에 들어가서 

	
	@GetMapping("/user")
	public @ResponseBody String user() {
		return "user";
	}

이런 식으로 admin, manager, login, join 각 웹 브라우저로 이동하는 경로화면들을 작성한 후 확인해본다.

 

config패키지에 SecurityConfig라는 이름의 클래스를 생성한다.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.authorizeRequests()
		.antMatchers("/user/**").authenticated()
		.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")//이 권한이 있는 사람만 들어올 수 있게한다.
		.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
		.anyRequest().permitAll()

여기서 @EnableWebSecurtiy → 스프링 시큐리티 필터가 스프링 필터 체인에 등록이된다.

 

manager와 admin쪽으로 들어오게되면 

hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER') 이 권한이 있는 사람만 들어올 수 있도록 설정한다.  

 

 

403 권한이 없는 페이지에가 나올 시 login 페이지로 이동되도록하기 위한 코드 

package com.sol.security2.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.csrf().disable();
		http.authorizeRequests()
		.antMatchers("/user/**").authenticated()
		.antMatchers("/manager/**").access("hasRole('ROLE_ADMIN') or hasRole('ROLE_MANAGER')")//이 권한이 있는 사람만 들어올 수 있게한다.
		.antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
		.anyRequest().permitAll()
		.and()
		.formLogin()
		.loginPage("/login");
	}
}

이제 어디로 가든(admin의 경로를 찍든, manager로 경로를 찍든) login 경로로 이동되어 웨브라우저에 보여지게된다.

 

[참고] - 인프런 시프링 부트 시큐리티& JWT 강의