hubring

Spring boot - Security 본문

Spring Boot

Spring boot - Security

Hubring 2020. 7. 23. 00:53

 

 

Security dependencies 

spring boot starter security 의존성 추가

maven

<dependency>
 	<groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

 

Gradle

implementation 'org.springframework.boot:spring-boot-starter-security'

 

 

이후 spring을 실행시켜 localhost로 접속하면 아래와 같이 로그인 화면으로 접근한다.

 

 

 

기본적으로 접근 가능한 계정은

ID : user

Password : 디버그 창에 표시된 password

 

 

Spring Boot Security 사용시 추가되는 기능

 

1. 서버 기동 시 시큐리트 초기화 작업 및 보안 설정

2. 별도의 설정 및 구현 없이 기본적 웹 보안 기능이 연동되어 작동

- 모든 요청은 인증 후 접근 가능

- 인증 방식은 폼 로그인 방식 httpBasic 로그인 방식을 제공

- 기본 로그인 페이지 제공 

- 기본 계정 제공 ( username : user / password : 랜덤 password )

 

 

사용자 정의 보안 기능 구현

 

참고 - 스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security

 

SecurityConfig 설정

사용자 정의 Config

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.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(); //인증정책
    }
}

 

기본 자동으로 설정된 Default Config 설정은 아래와 같다

이 설정으로 인하여 의존성만 추가하더라도 인증요청하는 login 화면이 표시된 것이다. 

protected void configure(HttpSecurity http) throws Exception {
        this.logger.debug("Using default configure(HttpSecurity). If subclassed this will potentially override subclass configure(HttpSecurity).");
        ((HttpSecurity)((HttpSecurity)((AuthorizedUrl)http.authorizeRequests().anyRequest()).authenticated().and()).formLogin().and()).httpBasic();
    }

 

사용자 계정 설정

기본 계정이 아닌 지정된 사용자 계정을 설정할 경우
application.properties 파일에 사용자 계정 정보를 작성하여 설정할 수 있다.

 

 

http.formLogin()

From 로그인 인증 기능 제공

https://docs.spring.io/spring-security/site/docs/4.2.15.RELEASE/apidocs/org/springframework/security/config/annotation/web/configurers/FormLoginConfigurer.html

 

FormLoginConfigurer (Spring Security 4.2.15.RELEASE API)

Specifies the URL to send users to if login is required. If used with WebSecurityConfigurerAdapter a default login page will be generated when this attribute is not specified. If a URL is specified or this is not being used in conjuction with WebSecurityCo

docs.spring.io

 

formLogin 상세 설정 예시

 @Override
    protected void configure(HttpSecurity http) throws Exception{
        http.authorizeRequests()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage("/loginPage")
                .defaultSuccessUrl("/")
                .usernameParameter("userId")
                .passwordParameter("passwd")
                .loginProcessingUrl("/login_proc")
                .successHandler(new AuthenticationSuccessHandler() {
                    @Override
                    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
                        System.out.println(authentication.getName());
                        httpServletResponse.sendRedirect("/");
                    }
                })
                .failureHandler(new AuthenticationFailureHandler(){
                    @Override
                    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
                        System.out.println(e.getMessage());
                        httpServletResponse.sendRedirect("/login");
                    }
                })
                .permitAll();;
    }

 

 

참고

본 내용은 아래 인프런 강의 내용을 간략히 정리한 것입니다.
인프런 - 스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security

 

스프링 시큐리티 - Spring Boot 기반으로 개발하는 Spring Security - 인프런

스프링 시큐리티의 기본 개념부터 API 사용법과 내부 아키텍처를 학습하게 되고 이를 바탕으로 실전 프로젝트를 완성해 나감으로써 스프링 시큐리티의 인증과 인가와 관련된 핵심적인 기술들을

www.inflearn.com

https://www.baeldung.com/spring-security-login

 

Spring Security Form Login | Baeldung

A Spring Login Example - How to Set Up a simple Login Form, a Basic Security XML Configuration and some more Advanced Configuration Techniques.

www.baeldung.com

 

'Spring Boot' 카테고리의 다른 글

직접 빌드하기  (0) 2020.08.04
Spring Boot Documentation  (0) 2020.08.04
IntelliJ Gradle 대신 자바 직접 실행  (0) 2020.08.04
Spring boot - properties 분리  (0) 2020.07.14
Spring Boot - Swagger 적용  (0) 2020.07.11