77일 차 - 스프링 시큐리티 커스터마이징 (23.04.18)

yvonne·2023년 4월 18일
0

📂Spring

목록 보기
9/18
post-thumbnail

📝 스프링 시큐리티

  • 인증(Authentication)과 권한(Authorization)

      *인증: 로그인 / 권한(인가): 리소스 접근 제어 (로그인 시 확인)
  • 접근 주체(Principal): user, 접근하는 대상

  • 보안과 관련하여 체계적으로 많은 옵션을 제공하여 편리하게 사용 가능

  • Filter 기반으로 동작하여 MVC와 분리하여 관리 및 동작

  • 애너테이션을 통한 간단한 설정

✔ view파일 생성하기

✔ HomeController.java

package edu.global.ex.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Controller
public class HomeController {

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

	@GetMapping("/user/userHome")
	public void userHome() {
		log.info("userHome ...");
	}

	@GetMapping("/admin/adminHome")
	public void adminHome() {
		log.info("adminHome ...");
	}

}

✔ SecurtiyConfig.java

package edu.global.ex.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
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// @Component + 의미(설정할수 있는 파일)
@EnableWebSecurity //스프링 시큐리티 필터가 스프링 필터체인에 등록됨 = 스프링 시큐리티를 작동 시키는 파일 이라는걸 알려줌 - 스프링 한테. 
public class SecurityConfig extends WebSecurityConfigurerAdapter {

   @Override
   protected void configure(HttpSecurity http) throws Exception {
      //우선 CSRF설정을 해제한다. 
      //초기 개발시만 해주는게 좋다.
      http.csrf().disable();
      http.authorizeRequests()
     .antMatchers("/user/**").hasAnyRole("USER") // /user/userHome 치고 들어오면 유저권한으로 로그인 창 띄움
     .antMatchers("/admin/**").hasAnyRole("ADMIN") // /admin/adminHome 치고 들어오면 관리자권한으로 로그인 창 띄움
      .antMatchers("/**").permitAll(); // 그 외로 치고 들어오면 권한 체크 없이 전부 허가 
     
      http.formLogin(); //스프링 시큐리티에 있는 기본 로그인 폼을 사용하겠다.
     
   }
  
   @Override
   protected void configure(AuthenticationManagerBuilder auth) throws Exception {
      
      auth.inMemoryAuthentication()
           .withUser("user").password("{noop}user").roles("USER").and()
           .withUser("admin").password("{noop}admin").roles("ADMIN");
  
   }

}

✔ adminHome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>관리자(어드민) 페이지입니다.</h1>
</body>
</html>

✔ userHome.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
		<h1>유저(user) 페이지입니다.</h1>
	</body>
</html>



📌 jUnit 테스트

✔ UserMapperTest.java

package edu.global.ex.mapper;

import static org.junit.jupiter.api.Assertions.*;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import edu.global.ex.vo.UserVO;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@SpringBootTest
class UserMapperTest {

	@Autowired
	private UserMapper userMapper;

	@Test 
	void testInsertUser() { 

//      @Insert("insert into users(username,password,enabled) values(#{username},#{password},#{enabled})")
//      public int insertUser(UserVO userVO);
// 		
//      @Insert("insert into AUTHORITIES (username,AUTHORITY) values(#{username},'ROLE_USER')")
//      public void insertAuthorities(UserVO UserVO);

		UserVO user = new UserVO();
		user.setUsername("kim4");
		user.setPassword(new BCryptPasswordEncoder().encode("1234"));
		user.setEnabled(1);

		userMapper.insertUser(user);
		userMapper.insertAuthorities(user);
	}

}
profile
개발 연습장

0개의 댓글