-
[Spring] spring boot security - login 만들기Study/Java 2020. 7. 5. 20:35
pom.xml
12345<!-- security --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-security</artifactId></dependency>cs Maven에 들어가서 spring boot security 검색하여 원하는 버젼 다운
http:s//mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security
LoginController.java
1234567891011121314151617package simple.login;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controllerpublic class LoginController {@RequestMapping(value="/login", method = RequestMethod.GET)public String indexWindow(Model model) {return "login/login";}}cs SpringSecurityConfig.java
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253package simple.configuration;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.context.annotation.Configuration;import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;import org.springframework.security.config.annotation.web.builders.HttpSecurity;import org.springframework.security.config.annotation.web.builders.WebSecurity;import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;@Configuration@EnableWebSecurity@EnableGlobalAuthenticationpublic class SpringSecurityConfig extends WebSecurityConfigurerAdapter {@Autowiredprivate AuthProvider authProvider;@Autowiredprivate LoginHandler loginHandler;// 스프링 시큐리티의 필터 연결 설정@Overridepublic void configure(WebSecurity web) throws Exception {web.ignoring().antMatchers("/resources/**");}// 인터셉터로 요청을 안전하게 보호하는 방법 설정@Overrideprotected void configure(HttpSecurity http) throws Exception {http.csrf().disable().authorizeRequests().antMatchers("/login").permitAll().antMatchers("/**").hasRole("USER").and().formLogin().loginPage("/login").permitAll().loginProcessingUrl("/login").usernameParameter("userId").passwordParameter("passwd").successHandler(loginHandler).failureHandler(loginHandler).permitAll().and().logout().logoutUrl("/logout").logoutSuccessHandler(loginHandler).invalidateHttpSession(true).permitAll();}// 사용자 세부 서비스 설정@Overrideprotected void configure(AuthenticationManagerBuilder auth) throws Exception {auth.authenticationProvider(authProvider);}}cs Interface WebSecurityConfigurer<T extends SecurityBuilder<javax.servlet.Filter>>
WebSecurityConfigurerAdapter
=> Adapter는 implements한 인터페이스를 모두 오버라이드 한 클래스
=> 메소드를 부분만 사용할 수 있게 만들어 놓은 클래스임
=> Adapter를 extends하면 사용할 클래스만 extends하면 됨
AuthProvider.java
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657package simple.configuration;import java.util.ArrayList;import java.util.List;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.security.authentication.AuthenticationProvider;import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.core.GrantedAuthority;import org.springframework.security.core.authority.SimpleGrantedAuthority;import org.springframework.security.crypto.password.PasswordEncoder;import org.springframework.security.web.session.HttpSessionEventPublisher;import org.springframework.stereotype.Component;import simple.user.UserService;import simple.user.UserVo;@Componentpublic class AuthProvider implements AuthenticationProvider {@Autowiredprivate UserService userService;@Overridepublic Authentication authenticate(Authentication authentication) throws AuthenticationException {String userIdInput = authentication.getName();String passwdInput = (String) authentication.getCredentials();UsernamePasswordAuthenticationToken token;UserVo userVo = userService.selectUserOne(new UserVo(userIdInput));if ( userVo != null && userVo.getPasswd().equals(passwdInput) ) {List<GrantedAuthority> roles = new ArrayList<GrantedAuthority>();roles.add(new SimpleGrantedAuthority("USER"));token = new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), roles);token.setDetails(userVo);return token;}else {return null;}}@Overridepublic boolean supports(Class<?> authentication) {return authentication.equals(UsernamePasswordAuthenticationToken.class);}}cs LoginHandler.java
123456789101112131415161718192021222324252627282930313233343536373839404142434445package simple.configuration;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.springframework.security.core.Authentication;import org.springframework.security.core.AuthenticationException;import org.springframework.security.web.authentication.AuthenticationFailureHandler;import org.springframework.security.web.authentication.AuthenticationSuccessHandler;import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;import org.springframework.stereotype.Component;import simple.user.UserVo;@Componentpublic class LoginHandler implements AuthenticationSuccessHandler, AuthenticationFailureHandler, LogoutSuccessHandler {@Overridepublic void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {UserVo userVo = (UserVo) authentication.getDetails();request.getSession().setAttribute("userVo", new UserVo());response.sendRedirect("/user/indexWindow");System.out.println("로그인 성공");}@Overridepublic void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {response.sendRedirect("/login");System.out.println("로그인 실패");}@Overridepublic void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {request.getSession().invalidate();response.sendRedirect("/login");}}cs login.jsp
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html><html><head><title>Insert title here</title><link rel="stylesheet" href="/resources/lib/jqWidgets/styles/jqx.base.css" type="text/css" /><script type="text/javascript" src="/resources/lib/jquery/jquery-3.4.1.min.js"></script><script type="text/javascript" src="/resources/lib/jqWidgets/jqx-all.js"></script><style>body {width: 100%;height: 600px;background: #fff;margin: 0 auto;display: table;}#loginContent {display: table-cell;text-align: center;vertical-align: middle;}#loginForm {width: 400px;display: inline-block;}</style><script type="text/javascript">$(function() {initComponent();});function initComponent() {var template = [{bind:'userId', name:'userId', type:'text', label:'아이디', required:true, labelWidth:'80px', width:'250px', height: '25px'}, {bind:'passwd', name: 'passwd', type:'password', label:'비밀번호', required:true, labelWidth:'80px', width:'250px'}];$('#loginForm').jqxForm({template: template,padding: { left: 10, top: 10, right: 10, bottom: 10 }});$("#loginBtn").jqxButton({ width: '100', height: '25', value:'로그인'});$("#loginBtn").on('click', function() {$('#loginForm').jqxForm('submit', "/login", null, 'POST');});}</script></head><body><div id="loginContent"><div id="loginForm"></div><div style="width: 100%; text-align: center;"><div style="display: inline-block; text-align: center; margin-top:10px;"><input type="button" id="loginBtn" /></div></div></div></body></html>cs
실행결과
'Study > Java' 카테고리의 다른 글
[Class String] Encode/Decode Constructor, Method (0) 2020.07.16 [spring] 비밀번호 암호화 (0) 2020.07.05 [spring, jQWidgets] 주소록 CRUD 만들기 (0) 2020.07.05 Http -> Https TLS/SSL 적용하기 (0) 2020.06.30 [CSS] CSS 적용 우선순위 (0) 2020.06.30