본문 바로가기
개발/Spring

Spring Security Config

by BellOne4222 2024. 3. 1.

Spring Security Config 설정

  • 필터 Off
    • Spring Security 의 특정 필터를 disable하여 동작하지 않게 합니다.
// Basic Authentication을 비활성화합니다.
		http.httpBasic().disable();

 

  • 로그인, 로그아웃 페이지 관련 기능

  • 폼 로그인의 로그인 페이지를 지정하고 로그인에 성공했을 때 이동하는 URL 지정
// 로그인 페이지 및 성공 후 이동할 URL을 설정합니다.
http.formLogin()
    .loginPage("/login")
    .defaultSuccessUrl("/")
    .permitAll(); // 모든 사용자에게 로그인 페이지를 허용합니다.
  • 로그아웃 URL을 지정하고 로그아웃에 성공했을때 이동하는 URL을 지정
// 로그아웃을 처리하는 URL 및 로그아웃 후 이동할 URL을 설정합니다.
		http.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
			.logoutSuccessUrl("/");



  • Url Matchers 관련 기능

  • antMatchers
    • “/signup” 요청을 모두에게 허용
// URL에 대한 인가 규칙을 설정합니다.
		http.authorizeRequests()
			// "/"와 "/home", "/signup" 경로는 모든 사용자에게 허용합니다.
			.antMatchers("/", "/home", "/signup").permitAll()
  • mvcMatchers
    • “/signup”, “/signup/“, “/signup.html” 와 같은 유사 signup 요청을 모두에게 허용
http.authorizeRequests()
        .mvcMatchers("/signup").permitAll()
  • regexMatchers
    • 정규표현식으로 매칭
  • requestMatchers
    • 명확하게 요청 대상을 지정하는 경우에는 requestMatchers를 사용
    • antMatchers, mvcMatchers, regexMatchers는 결국에 requestMatchers로 이루어져있다.
PathRequest.toStaticResources().atCommonLocations()



  • 인가 관련 설정(경로별로 설정)
  • authorizeRequests()
    • 인가를 설정
authorizeRequests()



  • permitAll()
    • “/home” 요청을 모두에게 허용
http.authorizeRequests()
        .antMatchers(“/home").permitAll()



  • hasRole()
    • 권한을 검증
http.authorizeRequests()
        .antMatchers(HttpMethod.POST, "/notice").hasRole("ADMIN")
  • authenticated()
    • 인증이 되었는지를 검증
http.authorizeRequests()
        .anyRequest().authenticated()



  • Ignoring
    • 특정 리소스에 대해서 SpringSecurity자체를 적용하지 않고 싶을 때 사용
    • 예를 들어 css와 png 파일은 굳이 인증 없이 외부에 공개되어있다고 할 떼, 이럴때는 ignoring을 사용
    • 어떤 필터도 실행되지 않기 때문에 성능적으로 우수
// Spring Security가 정적 리소스를 무시하도록 설정합니다.
	@Override
	public void configure(WebSecurity web) {
		web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
	}

 

package org.example.personal_note.config;

import org.example.personal_note.user.User;
import org.example.personal_note.user.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
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.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.boot.autoconfigure.security.servlet.PathRequest;


import lombok.RequiredArgsConstructor;

@Configuration
@EnableWebSecurity // WebSecurityConfigurerAdapter 클래스를 상속받은 설정 클래스에 사용하여 Spring Security를 활성화합니다.
@RequiredArgsConstructor
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

	private final UserService userService;

	// HTTP 보안 설정을 구성하는 메서드입니다.
	@Override
	protected void configure(HttpSecurity http) throws Exception {
		// Basic Authentication을 비활성화합니다.
		http.httpBasic().disable();
		// Basic Authentication을 활성화합니다.
		// http.httpBasic();
		// CSRF 보호를 활성화합니다.
		http.csrf();
		// Remember-Me를 활성화합니다.
		http.rememberMe();
		// URL에 대한 인가 규칙을 설정합니다.
		http.authorizeRequests()
			// "/"와 "/home", "/signup" 경로는 모든 사용자에게 허용합니다.
			.antMatchers("/", "/home", "/signup").permitAll()
			// "/note" 페이지는 USER 역할을 가진 사용자에게만 허용합니다.
			.antMatchers("/note").hasRole("USER")
			// "/admin" 페이지는 ADMIN 역할을 가진 사용자에게만 허용합니다.
			.antMatchers("/admin").hasRole("ADMIN")
			// "/notice" 페이지에 대한 POST 요청은 ADMIN 역할을 가진 사용자에게만 허용합니다.
			.antMatchers(HttpMethod.POST, "/notice").hasRole("ADMIN")
			// "/notice" 페이지에 대한 DELETE 요청은 ADMIN 역할을 가진 사용자에게만 허용합니다.
			.antMatchers(HttpMethod.DELETE, "/notice").hasRole("ADMIN")
			// 그 외의 모든 요청은 인증된 사용자에게만 허용합니다.
			.anyRequest().authenticated();
		// 로그인 페이지 및 성공 후 이동할 URL을 설정합니다.
		http.formLogin()
			.loginPage("/login")
			.defaultSuccessUrl("/")
			.permitAll(); // 모든 사용자에게 로그인 페이지를 허용합니다.
		// 로그아웃을 처리하는 URL 및 로그아웃 후 이동할 URL을 설정합니다.
		http.logout()
			.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
			.logoutSuccessUrl("/");
	}

	// Spring Security가 정적 리소스를 무시하도록 설정합니다.
	@Override
	public void configure(WebSecurity web) {
		web.ignoring().requestMatchers(PathRequest.toStaticResources().atCommonLocations());
	}

	// 사용자 정보를 로드하는 UserDetailsService 빈을 설정합니다.
	@Bean
	@Override
	public UserDetailsService userDetailsService() {
		return username -> {
			User user = userService.findByUsername(username);
			if (user == null) {
				throw new UsernameNotFoundException(username);
			}
			return user;
		};
	}
}

'개발 > Spring' 카테고리의 다른 글

Spring MVC 구현  (0) 2024.03.02
JWT(Json Web Token)  (0) 2024.03.01
Spring security Architecture, Filter  (0) 2024.02.29
Spring security Test  (0) 2024.02.28
Spring Security 구현  (0) 2024.02.27