BACK

스프링부트 시큐리티 설정

코딩두통 2023. 2. 12. 19:39
728x90
  • authenticated() ;  인증된 사용자의 접근을 허용
  • fullyAuthenticated(): 인증된 사용자의 접근을 허용,  rememberMe인증 제외
  • permitAll(): 무조건 허용
  • denyAll(): 무조건 차단
  • anonymous(): 익명사용자 허용
  • rememberMe(): rememberMe 인증 사용자 접근 허용
  • access(String): 주어진 SpEL표현식의 평가 결과가 true 이면 접근허용
  • hasRole(String): 사용자가 주어진 역할이 있다면 접근을 허용
  • hasAuthority(String): 사용자가 주어진 권한이 있다면 허용
  • hasAnyRole(String...): 사용자가 주어진 어떤권한이라도 있으면 허용
  • hasAnyAuthority(String...): 사용자가 주어진 권한중 어떤 것이라도 있다면 허용
  • hasIpAddress(String): 주어진 IP로 부터 요청이 왔다면 접근을 허용

그래들이 아닌 메이븐이기때문에 dependency 로 잡아줘야함

<!-- ... other dependency elements ... -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

시큐리티 공식문서에 나와있는 내용,

https://spring.io/guides/gs/securing-web/

 

Spring | Home

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

spring.io

최신문서에 있는것

package com.example.securingweb;

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.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

	@Bean
    //파라메타로 HttpSecurity 전달을 받아서 어떤 보안설정을 할것인지 설정해주면 됨
	public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.authorizeHttpRequests((requests) -> requests
				.requestMatchers("/", "/home").permitAll()  //url정의 permitAll 로그인없이도 접근가능
				.anyRequest().authenticated() //("/", "/home") 그밖에 어떤 요청이 와도 .authenticated() 반드시 로그인을 해야만 볼 수 있음
				.and()
            )
			.formLogin((form) -> form
				.loginPage("/login") //("/", "/home")외에 들어왔을때 이 페이지로 자동으로 페이지 이동함
				.permitAll() //로그인 되지 않은 사용자도 ("/login") 에 접근 할 수 있게permitAll() 해줌
			)
			.logout((logout) -> logout.permitAll()); //permitAll() 누구나 로그아웃 할 수 있도록

		return http.build();
	}
    
//@Bean 을 설정해줄 수 있는데 UserDetailsService 클래스가 스프링에서 관리를 해주는 bean이 되는것(의존성 주입)
	@Bean
	public UserDetailsService userDetailsService() {
		UserDetails user =
			 User.withDefaultPasswordEncoder()
				.username("user")
				.password("password")
				.roles("USER") //권한
				.build();

		return new InMemoryUserDetailsManager(user);
	}
}

구문서에 있는것

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    //파라메타로 HttpSecurity 전달을 받아서 어떤 보안설정을 할것인지 설정해주면 됨
    public void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers("/", "/home").permitAll()  //url정의 permitAll 로그인없이도 접근가능
                .anyRequest().authenticated() //("/", "/home") 그밖에 어떤 요청이 와도 .authenticated() 반드시 로그인을 해야만 볼 수 있음
                .and()
                .formLogin()
                .loginPage("/login") //("/", "/home")외에 들어왔을때 이 페이지로 자동으로 페이지 이동함
                .permitAll() //로그인 되지 않은 사용자도 ("/login") 에 접근 할 수 있게permitAll() 해줌
                .and()
                .logout() //permitAll() 누구나 로그아웃 할 수 있도록
                .permitAll();
    }
    // js 와 css 등 맵핑이 안되서 당황했는데 이거 넣어주면 됨
  @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        return (web) -> web.ignoring().antMatchers("/static/js/**", "/static/img/**", "/static/css/**", "/static/scss/**").anyRequest();
    }
//@Bean 을 설정해줄 수 있는데 UserDetailsService 클래스가 스프링에서 관리를 해주는 bean이 되는것(의존성 주입)
//하지만 다 지우고 사용할것 (쓰지않을거라서)
	@Bean
	public UserDetailsService userDetailsService() {
		UserDetails user =
			 User.withDefaultPasswordEncoder()
				.username("user")
				.password("password")
				.roles("USER") //권한
				.build();

		return new InMemoryUserDetailsManager(user);
	}
}
}

 

 

jdbc 인증

https://www.baeldung.com/spring-security-jdbc-authentication

 

 
728x90