일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | ||||||
2 | 3 | 4 | 5 | 6 | 7 | 8 |
9 | 10 | 11 | 12 | 13 | 14 | 15 |
16 | 17 | 18 | 19 | 20 | 21 | 22 |
23 | 24 | 25 | 26 | 27 | 28 |
- 스프링부트오류
- REST API 규칙
- Error creating bean with name
- @IdClass
- REST란
- uncheck Exception
- ERD 작성
- JoinColumn
- json gson 차이
- git
- Spring Spring boot 차이
- Unsatisfied dependency
- 복합키
- Q 클래스
- 빈생성안됨
- Filter
- JPA
- github
- jpa에러
- JPA주의사항
- 1차캐시
- queryDSL
- 스프링 부트 기능
- 스프링 부트 공식 문서
- 인텔리제이
- jwt메서드
- spring서버
- 최종 프로젝트
- json
- jpa회원가입
- Today
- Total
Everyday Dev System
인증 - 쿠키와 세션 본문
Cookie는 클라이언트에 저장될 목적으로 생성한 작은 정보를 담은 파일
Session은 서버에서 일정시간 동안 클라이언트 상태를 유지하기 위해 사용한다.
SessionID는 Cookie에 저장하고 요청 시 서버가 클라이언트를 식별하고 세션을 처리하는데에 활용한다.
Servlet에서 SessionID를 생성해준다. (HTTPSession)
클라이언트가 저장하고 있는 Cookie이다.
Cookie안에 name=value 와 SessionID 가 저장되어있다.
클라이언트는 서버에 요청을 보낼 때 해당 쿠키를 HttpServletRequest 에 넣어서 요청을 한다.
서버는 HttpServletRequest 를 받아서 세션ID를 이용해 사용자를 식별한다.
Servlet에서 요청이 들어 왔을 때에 HttpServletRequest 객체를 만들어 주고,
요청에 대한 응답을 반환하기 위해 HttpServletResponse 를 만든다.
<<Cookie>>
쿠키를 담아서 반환할때, 컨트롤러에서 매핑되는 메서드의 파라미터에
HttpServletResponse res
쿠키에 데이터를 가져올 때, 컨트롤러에서 매핑되는 메서드의 파라미터에
@CookieValue([Name]) String value
<<Session>>
<<세션에 데이터 저장>>
컨트롤러에서 매핑되는 메서드의 파라미터에
HttpServletRequest req
해당 객체에서 Session을 가져오는데, 없을 경우 새로 생성하고 정보를 저장한다.
HttpSession session = req.getSession(true);
session.setAttribute(AUTHORIZATION_HEADER, "Robbie Auth");
<<세션에 데이터 추출>>
컨트롤러에서 매핑되는 메서드의 파라미터에
HttpServletRequest res
해당 객체에서 Session을 가져오는데, 없을 경우 null을 반환한다.
HttpSession session = req.getSession(true);
세션에 name에 따른 데이터를 String으로 캐스팅한 후에 저장한다.
String value = (String) session.getAttribute(AUTHORIZATION_HEADER);
build.gradle 에 의존성 추가
// Security
implementation 'org.springframework.boot:spring-boot-starter-security'
Code :
package com.sparta.springauth.auth;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
@RestController
@RequestMapping("/api")
public class AuthController {
public static final String AUTHORIZATION_HEADER = "Authorization";
@GetMapping("/create-cookie")
public String createCookie(HttpServletResponse res) {
addCookie("Robbie Auth", res);
return "createCookie";
}
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
System.out.println("value = " + value);
return "getCookie : " + value;
}
public static void addCookie(String cookieValue, HttpServletResponse res) {
try {
cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20");
// Cookie Value 에는 공백이 불가능해서 encoding 진행.
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());
}
}
}
쿠키에 데이터 담기
1. 띄어쓰기가 포함된 문자열의 경우 아래와 같이 인코딩
cookieValue = URLEncoder.encode(cookieValue, "utf-8").replaceAll("\\+", "%20");
2. cookie 객체 생성하여 Setting한 후에 Servlet에서 만들어준 그 Response 객체에 넣음.
HttpServletResponse 타입의 객체에 데이터를 담으면 클라이언트로 반한이 된다.
Cookie cookie = new Cookie(AUTHORIZATION_HEADER, cookieValue); // Name-Value
cookie.setPath("/");
cookie.setMaxAge(30 * 60);
res.addCookie(cookie);
결과 :
res.addCookie(cookie);
위 코드를 통해 응답 Header에 Set-Cookie를 한다.
쿠키에 데이터 가져오기
1. @CookieValue(AUTHORIZATION_HEADER) String value
와 같이 해당 매개변수 앞에 @CookieValue([NAME]) 기재
@GetMapping("/get-cookie")
public String getCookie(@CookieValue(AUTHORIZATION_HEADER) String value) {
System.out.println("value = " + value);
return "getCookie : " + value;
}
결과 :
개발자 도구를 열어서 보면 다음과 같이 가져 오는 것을 알 수 있다.
Code :
@GetMapping("/create-session")
public String createSession(HttpServletRequest req) {
// Servlet에서 요청 들어왔을 때 HttpServletRequest 객체를 만들어줌
// 세션이 존재할 경우 세션 반환, 없을 경우 새로운 세션을 생성한 후 반환
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;
}
세션에 데이터 담기
1. Servlet에서 요청이 들어 왔을 때에 HttpServletRequest 객체를 만들어 준다.
2. HttpServletRequest 타입 객체에 getSession을 하여 저장.
- true라는 옵션을 주면 세션이 존재하면 해당 세션을 반환하고, 없으면 새로 생성 후 반환한다.
HttpSession session = req.getSession(true);
3. 세션에 name, value를 저장한다.
session.setAttribute(AUTHORIZATION_HEADER, "Robbie Auth");
결과 :
세션에 데이터 꺼내오기
1. Servlet에서 요청이 들어 왔을 때에 HttpServletRequest 객체를 만들어 준다.
2. HttpServletRequest 타입 객체에 getSession을 하여 저장.
- false라는 옵션을 주면 세션이 존재하면 해당 세션을 반환하고, 없으면 null을 반환한다.
HttpSession session = req.getSession(false);
3. 세션에 name을 통해 해당 데이터를 String으로 캐스팅한 후에 저장한다.
String value = (String) session.getAttribute(AUTHORIZATION_HEADER);
결과 :
references:
'내배캠 주요 학습 > Spring 숙련' 카테고리의 다른 글
Spring 에서 Filter란? (0) | 2023.06.20 |
---|---|
로그인 구현하기 (0) | 2023.06.19 |
회원가입 구현하기 (0) | 2023.06.19 |
JWT version 0.11.5 (0) | 2023.06.19 |
같은 타입의 Bean 객체 활용하기 (0) | 2023.06.19 |