Spring MVC - Spring Security

Programming/Java 2016.12.31 18:33 Posted by 파란크리스마스

Spring Security

출처 : 사랑이 고픈 프로그래머.. - 흔히 보게되는 절대 써먹을 수 없는 Spring Security의 초간단 셋팅
jjeong :: Spring Security login/logout 관련 글

web.xml 내용추가(WebContent\WEB-INF\web.xml)

	<!-- 스프링 스큐리티 관련 설정 / 시작 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/iot-datasource.xml
			/WEB-INF/iot-mybatis.xml
			/WEB-INF/iot-security.xml
		</param-value>
	</context-param>
	
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<filter>
		<filter-name>springSecurityFilterChain</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>springSecurityFilterChain</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	<!-- 스프링 스큐리티 관련 설정 / 끝 -->

iot-security.xml 파일 생성(WebContent\WEB-INF\iot-security.xml)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:security="http://www.springframework.org/schema/security"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
           http://www.springframework.org/schema/security
           http://www.springframework.org/schema/security/spring-security-3.2.xsd">

	<!-- 확장자를 이용해 패턴을 걸때는 /**/*.해당 확장자 로 할 것(Ant Pattern 규칙) -->
	<security:http pattern="/**/*.js" security="none"/>
	<security:http pattern="/**/*.css" security="none"/>
	<security:http pattern="/images/*" security="none"/>
	
	<!--
	<security:http pattern="/user_add_ajax.iot" security="none" //>
	<security:http pattern="/login.iot" security="none" />
	<security:http pattern="/loginfailed.iot" security="none" />
	<security:http pattern="/logout.iot" security="none" />
	-->
	
	<security:http auto-config="true">
		<security:intercept-url pattern="/json.iot" access="ROLE_ANONYMOUS,ROLE_USER" />
		<security:intercept-url pattern="/**/*.iot" access="ROLE_USER"/>
		
		<!-- 
		<security:form-login login-page="/login.iot" default-target-url="/hello_world.iot" authentication-failure-url="/loginfailed.iot" />
		<security:logout logout-success-url="/login.iot" />
		-->
	</security:http>

	<security:authentication-manager>
		<security:authentication-provider>

			<security:jdbc-user-service
				data-source-ref="dataSource"
				users-by-username-query="select user_id username, password password, 1 as enabled from user_info where user_id = ?"
				authorities-by-username-query="select name username, 'ROLE_USER' authority from user_info where user_id = ?" />

		</security:authentication-provider>
	</security:authentication-manager>

</beans>

로그인 페이지 만들기

package com.iot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class LoginController {

	@RequestMapping(value = "/login.iot", method = RequestMethod.GET)
	public String login(ModelMap modelMap) throws Exception {
		return "/login";
	}
}

로그인페이지 추가 (WebContent\WEB-INF\jsp\login.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
<style>
.errorblock {
	color: #ff0000;
	background-color: #ffEEEE;
	border: 3px solid #ff0000;
	padding: 8px;
	margin: 16px;
}
</style>
</head>
<body onload='document.f.j_username.focus();'>

 <div id="background_login">
	<h3>IOT 로그인 페이지</h3>
 
	<c:if test="${not empty error}">
		<div class="errorblock">
			Your login attempt was not successful, try again.<br /> Caused :
			${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}
		</div>
	</c:if>

	<form name='f' action="<c:url value='j_spring_security_check' />" method='POST'>
		<table>
			<tr>
				<td>사용자ID : </td>
				<td><input type='text' name='j_username' value=''>
				</td>
			</tr>
			<tr>
				<td>PassWord : </td>
				<td><input type='password' name='j_password' />
				</td>
			</tr>
			<tr>
				<td><input name="submit" type="submit" value="로그인" />
				<td><input name="reset" type="reset" />
				</td>
			</tr>
		</table>
	</form>
</div>

<a href="<c:url value='/user_add_ajax.iot' />">사용자추가</a>

</body>
</html>

시큐리티 제외 주소 설정

iot-security.xml 파일 내용 추가(WebContent\WEB-INF\iot-security.xml)

로그인 관련 주소는 시큐리티 설정에서 제외 시킨다.

	<security:http pattern="/user_add_ajax.iot" security="none" />
	<security:http pattern="/login.iot" security="none" />
	<security:http pattern="/loginfailed.iot" security="none" />
	<security:http pattern="/logout.iot" security="none" />

로그인 페이지 설정

iot-security.xml 파일 내용 추가(WebContent\WEB-INF\iot-security.xml)

		<security:form-login login-page="/login.iot" 
			default-target-url="/hello_world.iot" 
			authentication-failure-url="/loginfailed.iot" />
		<security:logout logout-success-url="/logout.iot" />

로그아웃

웹페이지 주소에 /j_spring_security_logout 이동하면 로그아웃

로그인 아웃 페이지 만들기(src\com\iot\controller\LoginController.java)

	@RequestMapping(value = "/logout.iot", method = RequestMethod.GET)
	public String logout(ModelMap modelMap) throws Exception {
		return "/logout";
	}

로그인아웃 페이지 추가 (WebContent\WEB-INF\jsp\logout.jsp)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
	<h3>로그아웃</h3>	
	<a href="<c:url value="j_spring_security_logout" />" >로그아웃</a>
</body>
</html>

컨트롤러에서 로그인 아이디 얻기

	Authentication auth = SecurityContextHolder.getContext().getAuthentication();
	String user_id = auth.getName();


저작자 표시
신고


 

티스토리 툴바