티스토리 뷰
728x90
출처 : Rednics Blog - 보안이 적용되지 않은 간단한 웹 어플리케이션 생성
WEB-INF\web.xml
<!-- 스프링 스큐리티 관련 설정 / 시작 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/iot-datasource.xml <!-- DB 접속 정보 --> /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> <!-- 스프링 스큐리티 관련 설정 / 종료 -->
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"> <!-- 참고 사이트 http://springsource.tistory.com/77 --> <security:http pattern="/*.html" security="none" /> <security:http pattern="/resources/**/*" security="none" /> <security:http pattern="/login.do" security="none" /> <security:http pattern="/loginfailed.do" security="none" /> <security:http pattern="/logout.do" security="none" /> <security:http auto-config="true"> <security:intercept-url pattern="/favicon.ico" access="ROLE_ANONYMOUS" /> <security:intercept-url pattern="/**" access="ROLE_USER" /> <security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" /> <security:form-login login-page="/login.do" default-target-url="/ShoppingMall2.do" authentication-failure-url="/loginfailed.do" /> <security:logout logout-success-url="/logout.do" /> </security:http> <security:authentication-manager> <security:authentication-provider> <security:jdbc-user-service data-source-ref="dataSource" users-by-username-query="select user_id username, pass password, 1 as enabled from tbluser where user_id = ?" authorities-by-username-query="select user_id username, 'ROLE_USER' authority from tbluser where user_id = ?" /> </security:authentication-provider> </security:authentication-manager> </beans>
Controller
package com.iot.controller; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; @Controller public class LoginController { @RequestMapping(value = "/login.do", method = RequestMethod.GET) public String login(ModelMap modelMap) throws Exception { return "/login"; } @RequestMapping(value = "/loginfailed.do", method = RequestMethod.GET) public String loginfailed(ModelMap modelMap) throws Exception { return "/loginfailed"; } @RequestMapping(value = "/logout.do", method = RequestMethod.GET) public String logout(ModelMap modelMap) throws Exception { return "/logout"; } }
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"%> <html> <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();'> <h3>Login with Username and Password (Custom Page)</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>암호:</td> <td><input type='password' name='j_password' /> </td> </tr> <tr> <td colspan='2'><input name="submit" type="submit" value="submit" /> </td> </tr> <tr> <td colspan='2'><input name="reset" type="reset" /> </td> </tr> </table> </form> </body> </html>
AuthenticationToken 확장
출처 : Syaku (샤쿠) | 스프링 시큐리티 커스텀 로그인 : Spring Security
IotAuthenticationToken.java
package com.iot.handler; import java.util.Collection; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.GrantedAuthority; import com.iot.domain.UserInfo; public class IotAuthenticationToken extends UsernamePasswordAuthenticationToken { // ----------------------------------- PRIVATE ATTRIBUTES private UserInfo userInfo = null; private String login_type; // ----------------------------------- CONSTRUCTOR public IotAuthenticationToken( Object principal, Object credentials, Collection<? extends GrantedAuthority> authorities, UserInfo userInfo, String login_type ) { super(principal, credentials, authorities); this.userInfo = userInfo; this.login_type = login_type; } // ----------------------------------- GET/SET TERS public UserInfo getUserInfo() { return userInfo; } public void setUserInfo(UserInfo userInfo) { this.userInfo = userInfo; } public String getLogin_type() { return login_type; } public void setLogin_type(String login_type) { this.login_type = login_type; } }
IotAuthenticationProvider.java
package com.iot.handler; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.authentication.AuthenticationProvider; import org.springframework.security.authentication.BadCredentialsException; 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.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Component; import com.iot.domain.UserInfo; import com.iot.service.UserInfoService; @Component public class IotAuthenticationProvider implements AuthenticationProvider { @Autowired private UserInfoService service; @Autowired private HttpSession session; // ---------------------------------- PUBLIC METHODS @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = (String) authentication.getCredentials(); UserInfo userInfo = null; Collection<? extends GrantedAuthority> authorities; try { IotAuthDets authDetails = (IotAuthDets) authentication.getDetails(); userInfo = service.selectUserInfo(username); if(userInfo!=null && userInfo.getDelete_yn().equals("Y")){ throw new UsernameNotFoundException("User details not found with this username: " + username); } if (userInfo == null) { throw new UsernameNotFoundException("User details not found with this username: " + username); } if (!password.equals(userInfo.getPassword())) { throw new BadCredentialsException("비밀번호가 일치하지 않습니다."); } authorities = getAuthorities(userInfo.getAuthority()); userInfo.setAuthorities(authorities); return new CMXAuthenticationToken( (authDetails.isSublogin() ? "sub," + userInfo.getUser_id() + "@" + userInfo.getKira_user() : userInfo.getUser_id()), authentication.getCredentials(), authorities, userInfo, authDetails.getLoginType() ); } catch (UsernameNotFoundException e) { throw new UsernameNotFoundException(e.getMessage()); } catch (BadCredentialsException e) { throw new BadCredentialsException(e.getMessage()); } catch (Exception e) { throw new RuntimeException(e.getMessage()); } } private List<GrantedAuthority> getAuthorities(String role) { List<GrantedAuthority> authList = new ArrayList<GrantedAuthority>(); authList.add(new SimpleGrantedAuthority("ROLE_USER")); if (role != null && role.trim().length() > 0) { if (role.equals("A")) { authList.add(new SimpleGrantedAuthority("ROLE_ADMIN")); } else if (role.equals("S")) { authList.add(new SimpleGrantedAuthority("ROLE_MBER_MANAGER")); } } return authList; } @Override public boolean supports(Class<? extends Object> authentication) { return UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication) && authentication.equals(UsernamePasswordAuthenticationToken.class); } }
iot-security.xml
<bean id="iotAuthenticationProvider" class="com.iot.handler.IotAuthenticationProvider"/> <security:authentication-manager alias="authenticationManager"> <security:authentication-provider ref="iotAuthenticationProvider" /> </security:authentication-manager>
JSP에서 로그인 정보 조회
출처 : Spring Security에서 화면에 사용자 정보, 권한에 따른 동적 메뉴 화면 구성 및 로그아웃 구성하기
<%@ page import="org.springframework.security.core.context.SecurityContextHolder"%> <%@ page import="org.springframework.security.core.Authentication"%> <%@ page import="com.iot.handler.IotAuthenticationToken"%> <%@ page import="com.iot.domain.UserInfo"%> <% Authentication auth = (Authentication)request.getUserPrincipal(); IotAuthenticationToken iotAuth = null; if (auth!=null && auth instanceof IotAuthenticationToken) { iotAuth = (IotAuthenticationToken)auth; } // <sec:authentication property="userInfo" /> // <sec:authentication property="userInfo.email" /> System.out.println("user_info = " + iotAuth.getUserInfo()); // <sec:authentication property="login_type"/> System.out.println("login_type = " + iotAuth.getLogin_type()); %>
<c:set> security값 설정
출처 : How to set value from<security:authentication/> to the parameter with <c:set>
<c:set var="login_type"><sec:authentication property="login_type"/></c:set> 로그인 타입 : ${login_type} <c:if test="${login_type == 'LOGIN_TYPE_DAUM' || login_type == 'LOGIN_TYPE_DAUM'}"> 다음로그인 </c:if>
-
-
-
-
-
-
-->
댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
TAG
- 서울오토살롱
- BPI-M4
- KOBA
- 동경
- 일본여행
- 전예희
- ubuntu
- android
- Xcode
- NDK
- 지스타2007
- Linux
- ffmpeg
- Spring MVC
- oracle
- 레이싱모델 익스트림 포토 페스티벌
- koba2010
- flex
- JavaScript
- 송주경
- ble
- Mac
- Delphi Tip
- 튜닝쇼 2008
- MySQL
- Spring
- SAS
- sas2009
- Java
- Delphi
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 | 31 |
글 보관함