본문 바로가기

Back-end (Spring Boot , JPA, JSP)/필기일지

240121 [Back-end] Spring Security스프링 시큐리티 (인증 / 접근제한)

반응형

[24.01.21]  112차

 

<<진도>>

[Back-end] Spring Security

스프링 시큐리티 (인증 / 접근제한)

 

 

스프링 시큐리티

https://spring.io/projects/spring-security/

 

Spring Security

Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authoriz

spring.io

https://docs.spring.io/spring-security/reference/servlet/architecture.html

 

Architecture :: Spring Security

The Security Filters are inserted into the FilterChainProxy with the SecurityFilterChain API. Those filters can be used for a number of different purposes, like authentication, authorization, exploit protection, and more. The filters are executed in a spec

docs.spring.io

 


실습

Spring Boot 프로젝트생성

 

생성 시 의존성 추가

 

DevTools <= 저장만해도 자동 재시작

 

Spring Boot Folder Structure (Best Practices)
https://malshani-wijekoon.medium.com/spring-boot-folder-structure-best-practices-18ef78a81819

 

Spring Boot Folder Structure (Best Practices)

What is Spring Boot — If you don’t know what spring boot is, I’m happy to share my previous article which is related to spring boot setup…

malshani-wijekoon.medium.com

 

(**Spring Boot model 패키지에는DB와관련된 entity등이들어감)

 

JPA, MySQL 의존성을 추가했으므로 DB설정필요

 

## DB
spring.datasource.dbcp2.connection-factory-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ver2
spring.datasource.username=root
spring.datasource.password=1111

mysql ver2 DB 생성후 연결

 

devtool추가 시 저장할때 서버재실행 자동

 

security 의존성 추가후 실행 시 

패스워드가 서버실행 시 부여되고 

 

default id는 user

password는 위의 부여코드

 

로그인 시 모든 페이지 접근 가능

 

 

localhost:8080/logout

로그아웃 시

 

모든 페이지 접근불가

 

부분적으로 접근 인가 설정하기

security 3버전이 후로는 java의 설정파일로 가능

 

 

설정 파일이란 것을 알려주는 @Configuration

웹 시큐리티설정파일이다 @EnableWebSecurity

 

spring-security 6 버전 (5버전과 설정법이 조금 다름)

 

 

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {


	// 이 메서드가 실행이돼서 리턴되는 SecurityFilterChain 객체를 Bean으로 등록
	// 이 Bean은 내부적으로 써야하므로 protected
	@Bean
	protected SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
		http
			.csrf((csrf) -> csrf.disable()) // security는 기본적으로 csrf(보안 공격) 공격에 대한 방어 세팅이 있다. (disable로 해제도 가능)
			.authorizeHttpRequests((authorizeRequests) -> 
					authorizeRequests
						.requestMatchers("/", "/info").permitAll() // "/","info" 해당 리소스(URI) 접근을 인증 절차없이 모두 허용
						.requestMatchers("/admin").hasRole("ADMIN") // "/admin" 리소스(URI)로의 접근은 ADMIN 롤role만 허용
						.anyRequest().authenticated()) // 나머지 리소스는 인증절차 필요
			.formLogin(Customizer.withDefaults()); // 기본 form 로그인뷰 쓰겠다. 커스텀 파일지정가능
		
		return http.build(); //이렇게 반환하는 객체로 Bean을 생성(Build)		
	}
}

 

index, info는 로그인 없이

dashboard는 로그인 후 접근이 가능하고

admin은 로그인 후에도 ADMIN 롤 부여가 안됐으므로 접근 불가

 

 

사용자를 추가 할 수 있다. 

 

 

 

UserDetailsServiceAutoConfiguration

properties 파일에서 

## admin
spring.security.user.name=admin
spring.security.user.password=1111
spring.security.user.roles=ADMIN

 

이제 /admin에서 admin, 1111으로 로그인 접근가능 (dashboard도 가능)

대신 이렇게 유저를 생성할 시** 기본 user는 생성되지 않는다.

 

 

 

localhost:8080/login 은

파라미터가 아닌 body에 담아 form 데이터 전송

 

아래 이름으로

 

반응형