[Spring] 인증과 인가

yoon·2024년 3월 15일

spring-boot

목록 보기
19/41
post-thumbnail

✅ 개념

✔ 인증(Authentication)

사용자의 신원을 입증하는 과정으로 사이트에 로그인할 때 누구인지 확인하는 작업을 말한다.

✔ 인가(Authorization)

사용자의 권한을 확인하는 작업

✅ session

✔ 세션이란?

  • 서버에서 일정시간 동안 클라이언트의 상태를 유지하기 위해 사용
  • 클라이언트 별로 SESSIONID를 부여하여 서버에 클라이언트 정보 저장
  • 서버에서 생성한 SESSIONID는 클라이언트의 쿠키값(세션쿠키)으로 저장되어 클라이언트 식별에 사용

✔ 세션 다루기

  • 세션 생성
@GetMapping("/create-session")
public String createSession(HttpServletRequest req) {
	// 세션이 존재할 경우 세션 반환, 없을 경우 새로운 세션을 생성한 후 반환
	HttpSession session = req.getSession(true);
	// 세션에 저장될 정보 Name - Value 를 추가합니다.
	session.setAttribute(AUTHORIZATION_HEADER, "Robbie Auth");
	return "createSession";
}
  • 세션 읽기
@GetMapping("/get-session")
public String getSession(HttpServletRequest req) {
	// 세션이 존재할 경우 세션 반환, 없을 경우 null 반환
	HttpSession session = req.getSession(false);
	String value = (String) session.getAttribute(AUTHORIZATION_HEADER); // 가	져온 세션에 저장된 Value 를 Name 을 사용하여 가져옵니다.
	System.out.println("value = " + value);
	return "getSession : " + value;
}

✔ 쿠키란?

  • 클라이언트에 저장될 목적으로 생성된 정보파일
  • 구성요소 : name, value, domain, path, expires

✔ 쿠키 다루기

  • 쿠키 생성
// 쿠키 생성은 범용적으로 사용될 수 있기 때문에 static 메서드로 선언
public static void addCookie(String cookieValue, HttpServletResponse res) {
	try {
		cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20"); 	// Cookie Value 에는 공백이 불가능해서 enc
		Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue); // Name-Value
		cookie.setPath("/");
		cookie.setMaxAge(30 * 60);
		// Response 객체에 Cookie 추가
		res.addCookie(cookie);
	} catch (UnsupportedEncodingException e) {
		throw new RuntimeException(e.getMessage());
		}
	}
  • 쿠키 읽기
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
	System.out.println("value = " + value);
	return "getCookie : " + value;
}
profile
하루하루 차근차근🌱

0개의 댓글