[인스타그램 클론 코딩][Spring boot] 2. Security 설정

2024. 2. 16. 14:52·프로젝트/인스타그램 클론 코딩
728x90
반응형
  • Security 라이브러리를 등록하면 인증되지 않은 모든 사용자를 /login 으로 redirection 됨 
    • 상태 코드 302 = redirect
  • SecurityConfig를 통해 설정해줌

📌 SecurityConfig 세팅

package yerong.InstagramCloneCoding.config;

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.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@EnableWebSecurity
@Configuration
public class SecurityConfig{
    @Bean
    public SecurityFilterChain filterChain (HttpSecurity http) throws Exception{
        return http
                .authorizeHttpRequests(authorizationRequest ->
                        authorizationRequest
                                .requestMatchers(
                                        AntPathRequestMatcher.antMatcher("/"),
                                        AntPathRequestMatcher.antMatcher("/user/**"),
                                        AntPathRequestMatcher.antMatcher("/image/**"),
                                        AntPathRequestMatcher.antMatcher("/subscribe/**"),
                                        AntPathRequestMatcher.antMatcher("/comment/**")
                                ).authenticated()
                                .anyRequest().permitAll()
                )
                .formLogin(formConfig ->
                        formConfig.loginPage("/auth/signin")
                                .defaultSuccessUrl("/"))
                .build();
    }
}

 

1.  @EnableWebSecurity 

  • 해당 파일로 Security를 활성화해줄 것임을 나타냄

2.  @Configuration

  • IoC에 등록 ➡️ 메모리에 뜸

3.  Security6 부터는 이런 형식으로 변경됨

@Bean
public SecurityFilterChain filterChain (HttpSecurity http) throws Exception{
        return http.build();
}

4. url에 권한을 줌

.authorizeHttpRequests(authorizationRequest ->
                        authorizationRequest
                                .requestMatchers(
                                        AntPathRequestMatcher.antMatcher("/"),
                                        AntPathRequestMatcher.antMatcher("/user/**"),
                                        AntPathRequestMatcher.antMatcher("/image/**"),
                                        AntPathRequestMatcher.antMatcher("/subscribe/**"),
                                        AntPathRequestMatcher.antMatcher("/comment/**")
                                ).authenticated()
                                .anyRequest().permitAll()
                )
  • authenticated() : 인증이 필요함(403 error)
  • anyRequest().permitAll() : 그 외의 모든 요청은 모두 허용

5.  인증이 필요한 페이지에 들어가면(403) 로그인 창으로 redirect 해줘야 함

.formLogin(formConfig ->
	formConfig.loginPage("/auth/signin")
		.defaultSuccessUrl("/"))

 

  • 권한이 없는 페이지들은 로그인 페이지로 넘겨줌
  • 로그인에 성공했다면 "/" 로 redirect 

 

 


PREV

 

[인스타그램 클론코딩] 1. 프로젝트 설정

📌 프로젝트 환경 설정 java 17, spring boot 3.2.2 mariaDB dependency : Spring Data JPA, lombok, web, security, mariaDB 💡 CSS 등 프론트 부분은 강의에서 제공된 자료를 사용했습니다! ✅ 화면 소개 📌 회원가입 화면

nyeroni.tistory.com

NEXT

 

[인스타그램 클론코딩] 3. 회원 가입 구현

더보기 ✔️ username, password, email, name을 입력 받고 회원 가입을 진행하도록 하겠음! 📌 User 엔티티 구현 package yerong.InstagramCloneCoding.domain.user; import jakarta.persistence.*; import lombok.*; import yerong.Instagram

nyeroni.tistory.com

 

728x90
반응형
저작자표시 비영리 변경금지 (새창열림)

'프로젝트 > 인스타그램 클론 코딩' 카테고리의 다른 글

[인스타그램 클론 코딩][Spring boot] 6. 구독하기  (1) 2024.02.19
[인스타그램 클론 코딩][Spring boot] 5. 회원 정보 수정  (1) 2024.02.19
[인스타그램 클론 코딩][Spring boot] 4. 로그인 구현  (2) 2024.02.18
[인스타그램 클론 코딩][Spring boot] 3. 회원 가입 구현  (3) 2024.02.17
[인스타그램 클론 코딩][Spring boot] 1. 프로젝트 설정  (2) 2024.02.14
'프로젝트/인스타그램 클론 코딩' 카테고리의 다른 글
  • [인스타그램 클론 코딩][Spring boot] 5. 회원 정보 수정
  • [인스타그램 클론 코딩][Spring boot] 4. 로그인 구현
  • [인스타그램 클론 코딩][Spring boot] 3. 회원 가입 구현
  • [인스타그램 클론 코딩][Spring boot] 1. 프로젝트 설정
예롱메롱
예롱메롱
  • 예롱메롱
    예롱이의 개발 블로그
    예롱메롱
  • 전체
    오늘
    어제
    • 전체보기 (274)
      • 프로젝트 (35)
        • Wedle (12)
        • 인스타그램 클론 코딩 (13)
        • 스프링 부트와 AWS로 혼자 구현하는 웹 서비스 (10)
      • 인프런 Spring 강의 정리 (79)
        • 스프링 입문 - 코드로 배우는 스프링 부트, 웹 .. (7)
        • Spring 핵심 원리 - 기본편 (9)
        • 모든 개발자를 위한 HTTP 웹 기본 지식 (8)
        • 자바 ORM 표준 JPA 프로그래밍 - 기본편 (11)
        • 실전! 스프링 부트와 JPA 활용1 - 웹 애플리.. (6)
        • 실전! 스프링 부트와 JPA 활용2 - API 개.. (5)
        • 실전! 스프링 데이터 JPA (7)
        • 스프링 MVC 1편 - 백엔드 웹 개발 핵심 기술 (7)
        • 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술 (11)
        • 실전! Querydsl (8)
      • Cloud (3)
      • Spring (6)
        • spring boot (5)
        • 소셜로그인 (1)
      • Docker (2)
      • DevOps (0)
      • Coding Test (114)
        • Programmers (37)
        • Baekjoon (76)
      • KB It's Your Life 6기 (1)
      • CS (18)
        • 알고리즘 (13)
        • 컴퓨터 구조 (1)
        • Operating System (0)
        • Network (0)
        • Database (4)
      • git (1)
      • Language (15)
        • Java (5)
        • C++ (6)
        • Python (4)
    • GITHUB GITHUB
    • INSTAGRAM INSTAGRAM
  • hELLO· Designed By정상우.v4.10.3
예롱메롱
[인스타그램 클론 코딩][Spring boot] 2. Security 설정
상단으로

티스토리툴바