솔적솔적

SpringBoot기반으로 Security 개발(자세히 파해쳐보자)_1 본문

Back-end/Spring Boot Security

SpringBoot기반으로 Security 개발(자세히 파해쳐보자)_1

솔솔봄향기 2022. 2. 21. 23:42

스프링시큐리티를 공부하다가

어떤 API를 사용하는지, 모르는 코드구문도 하나씩 나오고, 

구현은 했다지만 하나씩 확실히 알아야겠다.라는 생각이 들어서 이번에는 

코딩할 때 그 코드가 어떤 기능을 구현할 수 있는지 좀 더 자세히 알기 위한 기록과 공유를 하고자하는 목적으로 페이지를 시작한다.

 

목표는 스프링 부트를 이용해 개발하는 시큐리티를 더 자세히 파해져보기!이다.

 

✊ 학습목표

 1) 프로젝트 구성 및 의존성 추가

 2) 사용자 정의보안 기능 구현

 3) Form Login 인증

 

1) 프로젝트 구성 및 의존성 추가

  1. 프로젝트 생성
  2. 의존성 주입
    <!-- 주입 시 보안설정 작동 -->
    		<dependency>
    			<groupId>org.springframework.boot</groupId>
    			<artifactId>spring-boot-starter-security</artifactId>
    		</dependency>​
  3.  내용
    • 스프링 시큐리티 의존성 추가 시 일어나는 일들
    • 서버가 기동되면 스프링 시큐리티의 초기화 작업 및 보안 설정이 이루어진다
    • 별도의 설정이나 구현을 안해도 기본적인 웹 보안 기능이 현재 시스템에 연동되어 작동함
      • 인증 방식은 폼 로그인 방식과 httpBasic 로그인 방식을 제공함

2) 사용자 정의보안 기능 구현

문제점 :

보안 시 문제점은 계정이 하나밖에 없다는 것

추가, 변경 기능도 없음

해커 침입에 보안옵션없음

우리의 보안시스템은 최소한의 기능만 가지고 있는 것임

 

인증 API - 사용자 정의 보안 기능 구현

  • WebSecurtiyConfigurerAdapter 안에 있는 메소드 중에서 HttpSecurity http를 파라미터로 전달받는 오버라이딩을 하고 그 안에 보안기능들을 설정할 것이다.
    package com.sole.security.config;
    
    import org.springframework.security.config.annotation.web.builders.HttpSecurity;
    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
    		.authorizeRequests()
    		.anyRequest().authenticated()
    		.and()
    		.formLogin();
    	}
    }​
    spring.security.user.name=user
    spring.security.user.password=1111​

3) Form Login 인증

http.formLogin() : Form 로그인 인증 기능이 작동함

 

SecurityConfig

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http
		.authorizeRequests()
		.anyRequest().authenticated();
		http
		.formLogin()
		.loginPage("/loginPage")
		.defaultSuccessUrl("/")
		.failureUrl("/loginPage")
		.usernameParameter("userId")
		.passwordParameter("passwd")
		.loginProcessingUrl("/login_proc")
		.successHandler(new AuthenticationSuccessHandler() {
			
			@Override
			public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
					Authentication authentication) throws IOException, ServletException {
				System.out.println("authentication"+ authentication.getName());
				response.sendRedirect("/");
			}
		})
		.failureHandler(new AuthenticationFailureHandler() {
			
			@Override
			public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
					org.springframework.security.core.AuthenticationException exception) throws IOException, ServletException {

				System.out.println("excception"+ exception.getMessage());
				response.sendRedirect("/login");
			}
		}).permitAll();
	}
	
}

 Contorller

package com.sole.security;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class securityController {

	@GetMapping("/")
	public String index() {
		return "home";
	}
	
	@GetMapping("loginPage")
	public String loginPage() {
		return "loginPage";
	}
	
	
}

[참고 강의] 인프런 -  스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security