패키지, 클래스 생성
package com.code.springsecurity.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration //설정파일을 만들기 위한 애노테이션 or Bean을 등록하기 위한 애노테이션이다.
@EnableWebMvc //이부분 MVC
@ComponentScan(basePackages="com.code.springsecurity.demo") //구성요소를 스캔하겠다
public class DemoAppConfig {
@Bean //@Configuration과 함께 사용하며, 자바클래스 내에 그 종속성을 매스드화(인스턴스화)하는데 사용한다
public ViewResolver viewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/view/");
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}

이부분과 동일함
클래스 생성하기, SuperClass 추가(abstractann)

package com.code.springsecurity.demo.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class MySpringMvcDispatcherServletInitalizer extends AbstractAnnotationConfigDispatcherServletInitializer {
//이니셜라이제이션 initialization
//기계를 시동 가능한 상태로 만들기 위한 조작. 또는 데이터 매체를 사용하기 전이나 처리하기 전에 필요한 조작.
@Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return null;
}
@Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return new Class[] { DemoAppConfig.class };
}
@Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String[] {"/"};
//getServletMappings 메서드는 브라우저가 요청한 주소 패턴을 보고
//Spring에서 처리할지 말지를 결정할 수 있도록 해주는 메서드 입니다.
//return new String[] {"/"}; 라고 해주면 모든 요청에 대해
//Spring에서 처리해주겠다는 의미입니다.
//만약 특정 패턴의 주소만 처리해주겠다 하면 그 패턴의 주소 문자열을 셋팅하면 됩니다.
}
}
@Controller
public class DemoController {
//home.jsp가 보여지도록 코딩하세요
@GetMapping("/")
public String showHome() {
return "home";
}
}
pom.xml에 한줄 추가하기


붙여 넣고 버전명 수정하기

슈퍼클래스 추가

package com.code.springsecurity.demo.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.User.UserBuilder;
@Configuration
@EnableWebSecurity //스프링 시큐리티 필터가 스프링 필터체인에 등록
public class DemoSecurityConfig extends WebSecurityConfigurerAdapter{
//로그인 정보를 작성하면 WebSecurityConfigurerAdapter에서 알아서 처리함
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception{
UserBuilder users = User.withDefaultPasswordEncoder();
auth.inMemoryAuthentication()
.withUser(users.username("john").password("test123").roles("EMPLOYEE"))
.withUser(users.username("mary").password("test123").roles("MANAGER"))
.withUser(users.username("susan").password("test123").roles("ADMIN"));
}
}
로그인 기능 생성

로그인 페이지 수정하기
DemoSecurityConfig.java
매서드 생성
새로 로그인 처리할 페이지 선언하기
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll();
}
}
선언한 페이지로 비지니스 로직 변경하기

로그인 폼 만들기
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>My Custom Login Page</title>
</head>
<body>
<h2>My Custom Login Page</h2>
<form:form
action="${pageContext.request.contextPath}/authenticateTheUser"
method="POST">
<div style="color: red;">
<c:if test="${param.error != null}">
<p>Your login attempt was not successful, try again.</p>
<p>Reason: Bad credentials</p>
</c:if>
</div>
<p>
User Name : <input name="username" placeholder="아이디" />
</p>
<p>
Password : <input type="password" name="password" placeholder="비밀번호" />
</p>
<input type=submit value="Login">
</form:form>
</body>
</html>