SPRING 자동 로그인 (Interceptor & cookie)

* 자동 로그인을 체크하면, 다시 로그인 할 필요 없이 바로 로그인 가능

WebUtils.getCookie(request, "쿠키명"): 해당하는 쿠키를 가져온다

 

구조 

1. login.jsp에서 checkbox를 체크 하면 controller의 user_check로 (on 또는 null)값을 보내준다.

2. user_check 컨트롤러에서 받은 값을 로그인을 성공하면 넘겨줘야 하기 때문에, 

RedirectAttributes rs를 통해 rs.addAttribute("키", "밸류")로 값을 넘겨준다.

3. 로그인을 성공하면, redirect:successLogin으로 id와 check유무(on 또는 null) 를 가지고 이동한다.

4. successLogin 컨트롤러로 오게되면, 받아온 id값의 세션을 부여한다.

만약 check가 on일 경우, 받아온 id값의 쿠키를 부여한다.

그리고, db에 현재 회원의 check유무를 부여한다.

5. 그리고 쿠키가 있으면, 자동 로그인을 해야하기 때문에, pre Interceptor에 쿠키값을 가져온다.

만약 쿠키가 있을 경우, 해당 회원이 자동로그인 유무를 db를 통해 가져온다. 

만약 체크를 했을 경우, 세션을 부여한다.

6. 로그아웃 선택시, 쿠키를 지우고, db에 check유무를 "nan"으로 바꾸고, 세션을 삭제한다.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
	<%@ include file="/WEB-INF/views/default/header.jsp" %>
	<h3>login 페이지</h3>
	<form action="user_check" method="post">
		<input type="text" name="id"><br>
		<input type="text" name="pwd"><br>
		<input type="submit" value="로그인" ><br>
		<input id="auto" type="checkbox" name="autoLogin">
		<label for="auto">자동 로그인!!!</label>
	</form>
	<a href="register_form">회원가입</a>
	
</body>
</html>

package com.care.root.member.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.care.root.common.SessionCommon;
import com.care.root.member.dto.MemberDTO;
import com.care.root.member.service.MemberService;
import com.care.root.mybatis.member.MemberMapper;

@Controller
@RequestMapping("member")
public class MemberController implements SessionCommon{
	@Autowired MemberService ms;
	
	@GetMapping("login")
	public String login(HttpSession session) {
		if (session.getAttribute(LOGIN) != null) {
			return "redirect:/index";
		}
		return "member/login";
	}
	@PostMapping("user_check")
	public String userCheck( @RequestParam String id,
						@RequestParam String pwd , 
						@RequestParam(required = false) String autoLogin,
						RedirectAttributes rs) {
		int result = ms.userCheck(id, pwd);
		if(result == 1) {
			rs.addAttribute("id", id );
			rs.addAttribute("autoLogin", autoLogin );
			return "redirect:successLogin";
		}
		return "redirect:login";
	}
	@GetMapping("successLogin")
	public String successLogin(@RequestParam String id,
						@RequestParam(required = false) String autoLogin,
								HttpSession session, 
								HttpServletResponse res) {
		session.setAttribute( LOGIN , id);//("loginUser", id)
		if (autoLogin != null) {
			int limitTime = 60*60*24*90; // 90일동안 자동로그인 유지
			Cookie cook = new Cookie("loginCookie", id);
			cook.setPath("/");
			cook.setMaxAge(limitTime);
			res.addCookie(cook);
			
			ms.keepLogin(id, autoLogin);
		}
		return "member/successLogin";
	}

	@GetMapping("logout")
	public String logout(HttpSession session, 
			@CookieValue(value="loginCookie", required=false) Cookie cook, 
			HttpServletResponse res) {
		if (cook != null) {
			cook.setMaxAge(0);
			cook.setPath("/");
			res.addCookie(cook);
			ms.keepLogin((String)session.getAttribute(LOGIN), "nan");
		}
		session.invalidate();
		
		return "redirect:login";
	}
	@GetMapping("memberInfo")
	public String memberInfo(Model model, HttpSession session) {
		ms.memberInfo( model );
		return "member/memberInfo";
	}
	@GetMapping("info")
	public String info(Model model, @RequestParam String id) {
		ms.info(model, id);
		return "member/info";
	}
	@GetMapping("register_form")
	public String registerForm() {
		return "member/register";
	}
	@PostMapping("register")
	public String register(MemberDTO dto, HttpServletRequest req) {
		String[] addrs = req.getParameterValues("addr");
		int result = ms.register(dto);
		
		if(result == 1) {
			return "redirect:login";
		}
		return "redirect:register_form";
	}
}
package com.care.root.interceptor;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.util.WebUtils;

import com.care.root.common.SessionCommon;
import com.care.root.member.dto.MemberDTO;
import com.care.root.mybatis.member.MemberMapper;

public class AutoLogin extends HandlerInterceptorAdapter implements SessionCommon{
	
	@Autowired MemberMapper mapper;
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		System.out.println("auto login 실행");
		Cookie cook = WebUtils.getCookie(request, "loginCookie");
		System.out.println("cook : " + cook);
		if (cook != null) {
			MemberDTO dto = mapper.getData(cook.getValue());
			if (dto.getSessionId().equals("on")) {
				request.getSession().setAttribute(LOGIN, dto.getId());
			}
		}
		return true;
	}
}

 

실행 결과

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING  보안처리 (crosssitescripting XSS)

* 회원가입 하거나, db에 저장할때 javascript형식으로 저장하면, script 문법이 실행됨

이러한 공격(XSS)을 막기 위한 방법

 

받아온 데이터 안에 스크립트 문법이 있는지 없는지 체크

첫번째 방법

검증하고 싶은 값을 받아와서, 받아온값.replcae()를 통해 수정

 

 

두번째 방법

써있는대로 저장

 

lucy-xss-servlet-filter-rule.xml
0.00MB

 

위에 파일 복사 - src/main/resource에 붙여넣기

= 알아서 보안처리를 해준다.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

SPRING file upload & download

https://mvnrepository.com/ - commons fileupload(파일 업로드) 검색 - 첫번째 클릭 

- 1.3.3버전 클릭 - maven내용 복사 - pom.xml 붙여넣기

 

https://mvnrepository.com/ - commons io(파일 입출력) 검색 - 첫번째 클릭 

- 2.4버전 클릭 - maven내용 복사 - pom.xml 붙여넣기

 

 bean 추가하는 두가지 방법

1. config에서 bean 추가 ( 이 방법을 선호!! )

 

2. servlet-context.xml에서 bean 추가

 

 

<input>태그의 text는 @RequestParam이라는 타입으로 받아온다

<input>태그의 file은 MultipartFile이라는 타입으로 받아온다

 

file을 받아오는 두가지 방법

1. 파라미터 MultipartFile file로 받아온다

2. 파라미터 MultipartHttpServletRequest mReq로 받아온 후, 

MultipartFile file = MReq.getFile("파일name")으로 받아온다

 

 

파일에 저장

public static final String IMG_REPO = "c:/spring" : 파일 저장 위치

SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss-"); : 시간 형식 지정
String sysFileName = format.format(new Date()) : 지정한 형식으로 현재 시간 저장

File saveFile = new File(IMG_REPO + "/" + sysFileName) 

file.transferTo(saveFile) : 해당하는 위치에 파일 저장

 

 

db에 파일 저장 

 

화면에 띄우기 및 다운로드

res.addHeader("Content-dispostion", attachment;fileName="+file); 

: Content-dispostion = 다운로드 형식, attachment;fileName="+file = 파일명을 붙여서 다운

File f = new File(FileServiceImpl.IMG_REPO + "/" + file) : 해당 파일을 저장할 위치 지정

FileInputStream in = new FileInputStream(f) : FileInputStream()을 이용하여, 파일의 내용을 읽어옴
FileCopyUtils.copy(in, res.getOutputStream()) : 불러온 내용을 복사하여, 클라이언트에게 전송

 

 

파일 삭제

+ Recent posts