Web Programming/Java Spring

Spring Security 사용하기 - WebSecurityConfig 파일 구성하기

jinmc 2021. 1. 12. 18:38
반응형

Spring Security를 활용해서 custom login page를 만드는 법을 배웠는데, 

webSecurityConfig file에 대해서 알아보겠습니다.

 

package com.myBoard.demo;

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;

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
	
	// 디폴트 로그인 페이지를 변환하는 곳
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http	
				.authorizeRequests()
				.anyRequest().authenticated()
				.and()
				.formLogin()
				.loginPage("/login")
				.permitAll();
	}
}

저번 포스트에서 사용했던 코드인데, 한줄 한줄 살펴보도록 하겠습니다.

 

  • authorizeRequests()는 시큐리티 처리에 HttpServletRequest를 이용한다는 것을 의미합니다. 또한, 이로 인해 요청에 의한 권한을 지정할 수 있게 됨을 의미합니다. 
  • anyRequests().authenticated() 는 모든 사용자, 모든 접속에 대해서 인증이 필요하다는 걸 의미합니다.
  • and() 같은 경우 당연히 연결해주는 역할을 합니다
  • formLogin()같은 경우 html form을 이용해서 login을 해줄수 있게 해 줍니다.
  • loginPage('/login') 같은 경우 이 url을 통해서 custom login page 를 만들 수 있게 해줍니다.
  • permitall() 은 모든 request에 대해서 열어 있는 것을 말합니다.

즉, 요약하면, 모든 접속에 대해서 인증이 필요하다고 하고, 인증이 안되는 접속에는 무조건적으로 

/login으로 리디렉트되게 하기로 합니다.

 

그럼 혹시 모든 리퀘스트를 허용하려면 어떻게 하면 될까요?

 

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
				.authorizeRequests()
				.anyRequest()
				.permitAll();
	}

 

그럼 만약 하나의 페이지만 허용하고 싶다면 어떻게 할까요?

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		
		http
				.authorizeRequests()
				.antMatchers("/home").permitAll()
				.anyRequest().authenticated()
				.and()
				.formLogin()
				.loginPage("/login")
				.permitAll();
	}

이렇게 되면 /home의 웹페이지는 아무나 접속 가능하게 되고, 다른 페이지들은 접속 못하게 되어서 

로그인 페이지로 리디렉팅 되게 됩니다.

하지만 문제가 있습니다. 우리가 쓰려고 했었던 CSS, JS 가 모조리 막히면서, 말그대로 html만 넘어가게 되었습니다.

 

이를 해결하기 위해선, css, js, 관련된 디렉토리를 열어 주어야 합니다.

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

이 이외에도, 특정 롤에 맞춰서 할 수 있게 할 수도 있습니다.

 

참고 블로그 : velog.io/@jayjay28/2019-09-04-1109-%EC%9E%91%EC%84%B1%EB%90%A8  

okky.kr/article/382738 

blog.naver.com/tjddydgkfao/222199416013

반응형