반응형
SMALL
지난 시간에 스프링의
JDBC와 트랜잭션에 대해 학습했는데요
아직 안보셨다면 아래의 링크 ↓↓
2020/10/02 - [Java] - [Java] 스프링(Spring) JDBC(Java Database Connectivity)와 트랜잭션(Transaction)
이번 학습 주제는 스프링(Spring)의
보안(Security)으로 로그인 프로그램을
제작하면서 알아보겠습니다
먼저 pom.xml에 보안 관련
dependency를 추가해줍니다
1. pom.xml
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>3.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-taglibs</artifactId>
<version>3.2.4.RELEASE</version>
</dependency>
다음으로 보안 관련
설정(Config) 파일을 추가합니다
File → New → Other를 선택하면
아래의 창이 뜨고
Spring Bean Configuration File을 선택하고
Next!
프로젝트의 appServlet에
security-context로 지정하여 추가합니다
2. security-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:security="http://www.springframework.org/schema/security"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.2.xsd">
<security:http auto-config="true">
<security:form-login login-page="/loginForm.html"
authentication-failure-url="/loginForm.html?ng"/>
<security:intercept-url pattern="/login.html*" access="ROLE_USER"/>
<security:intercept-url pattern="/welcome.html*" access="ROLE_ADMIN"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user name="user" password="123" authorities="ROLE_USER"/>
<security:user name="admin" password="123" authorities="ROLE_ADMIN,ROLE_USER"/>
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
</beans>
다음으로 web.xml 파일을
아래와 같이 설정합니다
3. web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- The definition of the Root Spring Container shared by all Servlets and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/spring/root-context.xml
/WEB-INF/spring/appServlet/security-context.xml
</param-value>
</context-param>
<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>
<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- Processes application requests -->
<servlet>
<servlet-name>appServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>appServlet</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
아래의 코드는 In-Memory 인증을 통한
로그인 페이지를 구현한 것입니다
그렇게 어려운 내용은 없어서
설명은 생략하도록 하겠습니다
4. HomeController.java
package com.example.demo;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/*
* Handles requests for the application home page.
*/
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory.getLogger(HomeController.class);
/**
* Simply selects the home view to render by returning its name.
*/
@RequestMapping(value = "/index.html", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
logger.info("Welcome home! The client locale is {}.", locale);
Date date = new Date();
DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale);
String formattedDate = dateFormat.format(date);
model.addAttribute("serverTime", formattedDate );
return "home";
}
@RequestMapping("/login.html")
public String login(Locale locale, Model model) {
return "security/login";
}
@RequestMapping("/welcome.html")
public String welcome(Locale locale, Model model) {
return "security/welcome";
}
@RequestMapping("/loginForm.html")
public String loginForm(Locale locale, Model model) {
return "security/loginForm";
}
}
5. index.jsp
<%@ page contentType="text/html;charset=utf-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Home</title>
</head>
<body>
<h1>
Hello world!
</h1>
<P>Username is ${username}</P>
<br>
<a href="<c:url value="j_spring_security_logout" />" target="_self">Logout</a>
</body>
</html>
6. login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/security/tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>login.jsp</h1>
<%-- <c:if test="${not empty pageContext.request.userPrincipal }">
<p> is Log-In</p>
</c:if>
<c:if test="${empty pageContext.request.userPrincipal }">
<p> is Log-Out</p>
</c:if> --%>
<s:authorize ifAnyGranted="ROLE_USER">
<p> is Log-In</p>
</s:authorize>
<s:authorize ifNotGranted="ROLE_USER">
<p> is Log-Out</p>
</s:authorize>
<%-- USER ID : ${pageContext.request.userPrincipal.name}<br/> --%>
USER ID : <s:authentication property="name"/><br/>
<a href="${pageContext.request.contextPath}/j_spring_security_logout">Log Out</a> <br />
</body>
</html>
7. loginForm.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>loginForm.jsp</h1>
<c:url value="j_spring_security_check" var="loginUrl"/>
<form action="${loginUrl}" method="post">
<c:if test="${param.ng != null}">
<p>
LogIn NG! <br />
<c:if test="${SPRING_SECURITY_LAST_EXCEPTION != NULL}">
message : <c:out value="${SPRING_SECURITY_LAST_EXCEPTION.message}" />
</c:if>
</p>
</c:if>
ID : <input type="text" name="j_username"> <br />
PW : <input type="text" name="j_password"> <br />
<input type="submit" value="LOGIN"> <br />
</form>
</body>
</html>
8. welcome.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
welcome.jsp
</body>
</html>
이것으로 이번 학습을 마치겠습니다
그럼 이만-_-
반응형
LIST
'Java' 카테고리의 다른 글
[Java] HackerRank_Java Static Initializer Block과 Date and Time (0) | 2020.11.19 |
---|---|
[Java] HackerRank_Java If-Else와 Loops (0) | 2020.11.18 |
[Java] 스프링(Spring) JDBC(Java Database Connectivity)와 트랜잭션(Transaction) (0) | 2020.10.02 |
[Java] 스프링(Spring) 폼(Form) 데이터와 Validator 검증 (0) | 2020.09.29 |
[Java] 스프링(Spring) MVC(Model-View-Controller) (0) | 2020.09.28 |