Spring에 Security를 추가하면 자동적으로 로그인은 내장된 화면을 이용하여 진행하도록 되어 있습니다.
이 화면이 심플해서 맘에 들어 그냥 사용하고 싶다면 괜찮지만 새로 만드는 작업이 그리 복잡하지 않기 때문에 가능하면 직접 만들어 사용 하는 것도 좋습니다. 한번 프로젝트를 생성해서 로그인 화면을 작성해 보겠습니다.
테스트를 위해 프로젝트 이름을 Login 으로 생성 했습니다.
추가되는 라이브러리는 Security 와 Web입니다.
그 외에 필요한 라이브러리는 pom.xml에 직접 추가를 해줍니다.
pom.xml
<dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> </dependency> <dependency> <groupId>org.webjars</groupId> <artifactId>jquery</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> |
Login 화면용 jsp 파일의 위치를 정하기 위해 application.properties 파일에 설정을 해주고
#jsp location spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp server.servlet.jsp.init-parameters.development=true |
설정한 값을 이용하여 파일이 들어갈 폴더도 생성 합니다.
여기 까지는 일반 프로젝트를 만드는 방법과 동일한 작업 입니다. 이제 단 한가지 작업만 진행 하면 로그인 화면을 직접 만들어 사용할 수 있습니다.
기본 로그인 화면을 새로 생성한 로그인 페이지를 이용 하도록 수정하려면 WebSecurityConfigurerAdapter를 상속받은 class를 생성해서 configure(HttpSecurity http)에 설정을 추가 하기만 하면 됩니다.
@Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().authorizeRequests() .antMatchers("/user/login").permitAll() .and().logout().permitAll() .and().formLogin() .loginPage("/user/login") .loginProcessingUrl("/loginProcess") .defaultSuccessUrl("/mainHome") .and().csrf().disable(); } |
위의 설정은
loginPage("/user/login") : 새로운 로그인 페이지 호출을 설정 합니다.
loginProcessingUrl("/loginProcess") : 실제 로그인을 진행 합니다.
이 두 가지만 해주면 설정은 끝입니다.
defaultSuccessUrl("/mainHome") 이건 그냥 로그인 성공시 보여줄 페이지 입니다.
실제로 호출되는 Controller 클래스도 생성을 합니다.
@RequestMapping("/user/login") public String login() throws Exception { return "login/userLogin"; }
@RequestMapping("/mainHome") public String loginMain() throws Exception { return "main"; } |
작동 순서
1. 로그인 페이지 설정 :
로그인을 진행할 페이지를 호출하기 위해 Controller에서 @RequestMapping("/user/login") 요렇게 해놓고 return "login/loginForm"; 리턴에서 새로 생성한 로그인 화면(loginForm.jsp)을 보여줍니다.
2. 로그인 진행 :
/login/LoginForm.jsp 에서 <form> 태그에 username, password를 입력하고
<form action="/loginProcess" method="post"> 이렇게 처리하면 로그인을 진행 합니다.
3. 로그인 성공 페이지
로그인이 완료 되면 Controller에서 @RequestMapping("/mainHome") 이걸 호출 하고 return "main";으로 넘겨 main.jsp 화면을 보여 줍니다.
신규 로그인 화면 입니다.
기본 제공 로그인 화면이 더 좋은거 같군요...
다음은 로그인 성공시 보여주는 화면입니다.
예쁘게 꾸며서 사용하세요.
전체 소스
WebSecurityConfigurerAdapter
package com.copycoding.security;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder;
@Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override protected void configure(HttpSecurity http) throws Exception { http.httpBasic().and().authorizeRequests() .antMatchers("/user/login").permitAll() .and().logout().permitAll() .and().formLogin() .loginPage("/user/login") .loginProcessingUrl("/loginProcess") .defaultSuccessUrl("/mainHome") .and().csrf().disable(); }
@Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("copycoding").password(passwordEncoder().encode("copycopy")).roles("ADMIN"); auth.inMemoryAuthentication() .withUser("honggil").password(passwordEncoder().encode("hoho")).roles("USER"); }
@Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } |
Controller
package com.copycoding.security;
import org.springframework.web.bind.annotation.RequestMapping;
public class TestController {
@RequestMapping("/user/login") public String login() throws Exception { return "login/userLogin"; }
@RequestMapping("/mainHome") public String loginMain() throws Exception { return "main"; } } |
/login/loginForm.jsp
<%@ page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%> <!DOCTYPE html> <html> <head> <meta charset="EUC-KR"> <title>Insert title here</title> </head> <body> <h1>로그인 페이지</h1>
<form action="/loginProcess" method="post"> <table> <tr> <td>username</td><td><input type="text" name="username" placeholder="username 입력"></td> </tr> <tr> <td>password</td><td><input type="password" name="password" placeholder="비밀번호 입력"></td> </tr> <tr> <td colspan="2" align="right"><button type="submit">로그인</button></td> </tr> </table> </form> </body> </html> |
/main.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html> <html> <head> <meta charset="EUC-KR"> <title>Insert title here</title> </head> <body>
<h1>Main Page!</h1>
</body> </html> |
- copy coding -
'Java' 카테고리의 다른 글
Maven jQuery Validation 이용 form input 유효성 검사 (0) | 2020.03.29 |
---|---|
JAVA substring split 특수문자 문자열 자르기 (0) | 2020.03.15 |
Spring Security @PreAuthorize @Secured 사용법 (5) | 2020.02.12 |
REST URL Sub-Resource 처리 @PathVariable() (2) | 2020.02.05 |
ubuntu oracle java 수동 설치 (6) | 2019.06.08 |