'spring security'에 해당되는 글 3건

  1. 2012.03.12 Spring Security InMemory + JDBCImpl 설정 방법.
  2. 2012.03.12 Spring Security login/logout 관련 글.
  3. 2012.03.12 3. Spring MVC 에 Spring Security 적용해 보기 1

Spring Security InMemory + JDBCImpl 설정 방법.

ITWeb/개발일반 2012. 3. 12. 17:22
가장 쉽게 접근할 수 있는 방법에 대해서 기술 합니다.
모든 내용의 기초는 아래 사이트에서 참고하였습니다.
- 없는건 검색했고요.. ㅎㅎ

 

[spring-security.xml InMemory] 

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"

    xmlns:beans="http://www.springframework.org/schema/beans" 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.0.xsd

           http://www.springframework.org/schema/security

           http://www.springframework.org/schema/security/spring-security-3.1.xsd">


    <global-method-security secured-annotations="enabled" />


    <http auto-config='true'>

        <intercept-url pattern="/login.html*" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <intercept-url pattern="/welcome.html*" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <intercept-url pattern="/**" access="ROLE_ADMIN" />

        <form-login login-page='/login.html' default-target-url='/index.html' always-use-default-target='true' authentication-failure-url="/login.html" />

        <logout logout-success-url="/welcome.html" delete-cookies="JSESSIONID" />

        <remember-me key="daSDAsdaSDsa" />

    </http>


    <authentication-manager>

        <authentication-provider>

<!-- in memory case user-service start -->

            <user-service>

                <user name="jimi" password="1234" authorities="ROLE_USER, ROLE_ADMIN" />

                <user name="bob" password="1234" authorities="ROLE_USER" />

            </user-service>

<!-- in memory case user-service end -->

        </authentication-provider>

    </authentication-manager> 



[spring-security.xml JDBCImpl Case 1]
- InMemory 코드에서 빨간 부분이 변경 됩니다.

<!-- jdbcImpl case 1 start -->

            <jdbc-user-service data-source-ref="dataSource"

                users-by-username-query="SELECT username, password, enabled FROM users WHERE username=?"

                authorities-by-username-query="SELECT u.username, au.authority FROM users u, authorities au WHERE u.username=? AND au.username=u.username"

            />

<!-- jdbcImpl case 1 end -->



[spring-security.xml JDBCImpl Case 2]

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"

    xmlns:beans="http://www.springframework.org/schema/beans" 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.0.xsd

           http://www.springframework.org/schema/security

           http://www.springframework.org/schema/security/spring-security-3.1.xsd">


    <global-method-security secured-annotations="enabled" />


    <http auto-config='true'>

        <intercept-url pattern="/login.html*" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <intercept-url pattern="/welcome.html*" access="IS_AUTHENTICATED_ANONYMOUSLY" />

        <intercept-url pattern="/**" access="ROLE_ADMIN" />

        <form-login login-page='/login.html' default-target-url='/index.html' always-use-default-target='true' authentication-failure-url="/login.html" />

        <logout logout-success-url="/welcome.html" delete-cookies="JSESSIONID" />

        <remember-me key="daSDAsdaSDsa" />

    </http>


    <authentication-manager>

<!-- jdbcImpl case 2 start -->

        <authentication-provider user-service-ref="userDetailsService" />

<!-- jdbcImpl case 2 end -->

    </authentication-manager>


<!-- jdbcImpl case 2 start -->

    <beans:bean id="userDetailsService" class="org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl">

        <beans:property name="dataSource" ref="dataSource"/>

    </beans:bean>

<!-- jdbcImpl case 2 end -->

</beans:beans>


※ 이넘들이 사용하는 Table Schema 는 아래 글 참고 하세요.
http://jjeong.tistory.com/610  

그리고 참고하기 위해서 JdbcDaoImpl.java 코드 올려 봅니다. 
이 코드를 보시면 이해 하는데 도움이 될겁니다.

※ 코드를 보시니 이제 감이 오시나요???
그렇습니다.
JdbcImpl.java 와 같은 넘을 biz 요구사항에 맞춰서 작성을 하시면 customized authentication 과 authority 를 구현 하실 수 있습니다. ^^ 
그래도 잘 모르시겠다구요.
그럼 아래를 참고하세요.
이미 정리 된 문서가 있어서 link 겁니다.

[원본링크]

 
:

Spring Security login/logout 관련 글.

ITWeb/개발일반 2012. 3. 12. 15:21
기본적으로 아래 페이지를 한번 정독 하시면 어떻게 하는지 아실 수 있습니다.

그럼에도 불구하고 샘플코드가 잘 정리된게 있으면 좋겠죠.
굳이 제가 정리 하지 않아도 잘 정리된게 있어서 첨부 합니다.

[원본글 링크]

[Login 예제]

Defined your custom login form in Spring XML file. See explanation below :

  1. login-page=”/login” – The login form will be “/login”
  2. default-target-url=”/welcome” – If authentication success, forward to “/welcome”
  3. authentication-failure-url=”/loginfailed” – If authentication failed, forward to “/loginfailed”
  4. logout-success-url=”/logout” – If logout , forward to “/logout”

File : spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" 
	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.0.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
 
	<http auto-config="true">
		<intercept-url pattern="/welcome*" access="ROLE_USER" />
		<form-login login-page="/login" default-target-url="/welcome"
			authentication-failure-url="/loginfailed" />
		<logout logout-success-url="/logout" />
	</http>
 
	<authentication-manager>
	  <authentication-provider>
		<user-service>
			<user name="mkyong" password="123456" authorities="ROLE_USER" />
		</user-service>
	  </authentication-provider>
	</authentication-manager>
 
</beans:beans>

In custom login form, you have to follow Spring Security standard name :

  1. j_spring_security_check – Login service
  2. j_spring_security_logout – Logout service
  3. j_username – Username
  4. j_password – Password

To display authentication error messages, use this :

${sessionScope["SPRING_SECURITY_LAST_EXCEPTION"].message}

File : login.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<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>User:</td>
				<td><input type='text' name='j_username' value=''>
				</td>
			</tr>
			<tr>
				<td>Password:</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>

File : hello.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
	<h3>Message : ${message}</h3>	
	<h3>Username : ${username}</h3>	
 
	<a href="<c:url value="/j_spring_security_logout" />" > Logout</a>
 
</body>
</html>



[Logout 예제]

In Spring Security, to log out, just add a link to url “j_spring_security_logout“, for example :

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<body>
	<h3>messages, whatever</h3>	
	<a href="<c:url value="j_spring_security_logout" />" > Logout</a>
</body>
</html>

In Spring security, declares “logout” tag, and configure the “logout-success-url” attribute :

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" 
	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.0.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
 
	<http auto-config="true">
		<intercept-url pattern="/welcome*" access="ROLE_USER" />
		<logout logout-success-url="/welcome" />
	</http>
 
	<authentication-manager>
	  <authentication-provider>
	    <user-service>
		<user name="mkyong" password="password" authorities="ROLE_USER" />
	    </user-service>
	  </authentication-provider>
	</authentication-manager>
 
</beans:beans>



[Database Login]

1. Database Tables

In database, you need to create two tables to store user details and user role details, one to many relationship, one user can contains many roles.

A simple and standard table design for user role relationship. And, you are allow to add extra columns for extra functionality. In additional, the table name and column name are not fixed, you can rename to whatever name.

P.S All scripts in MySQL.

CREATE TABLE `users` (
  `USER_ID` INT(10) UNSIGNED NOT NULL,
  `USERNAME` VARCHAR(45) NOT NULL,
  `PASSWORD` VARCHAR(45) NOT NULL,
  `ENABLED` tinyint(1) NOT NULL,
  PRIMARY KEY (`USER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `user_roles` (
  `USER_ROLE_ID` INT(10) UNSIGNED NOT NULL,
  `USER_ID` INT(10) UNSIGNED NOT NULL,
  `AUTHORITY` VARCHAR(45) NOT NULL,
  PRIMARY KEY (`USER_ROLE_ID`),
  KEY `FK_user_roles` (`USER_ID`),
  CONSTRAINT `FK_user_roles` FOREIGN KEY (`USER_ID`) REFERENCES `users` (`USER_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Insert data for testing, now an user “mkyong” is created and contains role named “ROLE_USER“.

INSERT INTO mkyongdb.users (USER_ID, USERNAME,PASSWORD, ENABLED)
VALUES (100, 'mkyong', '123456', TRUE);
 
INSERT INTO mkyongdb.user_roles (USER_ROLE_ID, USER_ID,AUTHORITY)
VALUES (1, 100, 'ROLE_USER');

2. Spring JDBC

Create a data source bean, and connect to database via Spring JDBC.

<beans xmlns="http://www.springframework.org/schema/beans"
	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.0.xsd">
 
   <bean id="dataSource"
	class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 
	<property name="driverClassName" value="com.mysql.jdbc.Driver" />
	<property name="url" value="jdbc:mysql://localhost:3306/mkyongdb" />
	<property name="username" value="root" />
	<property name="password" value="password" />
   </bean>
 
</beans>

3. Spring Security

In Spring security configuration file, use “jdbc-user-service” tag, and define your query to get the data from database.

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" 
	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.0.xsd
	http://www.springframework.org/schema/security
	http://www.springframework.org/schema/security/spring-security-3.0.3.xsd">
 
	<http auto-config="true">
		<intercept-url pattern="/welcome*" access="ROLE_USER" />
		<form-login login-page="/login" default-target-url="/welcome"
			authentication-failure-url="/loginfailed" />
		<logout logout-success-url="/logout" />
	</http>
 
	<authentication-manager>
	   <authentication-provider>
		<jdbc-user-service data-source-ref="dataSource"
 
		   users-by-username-query="
		      select username,password, enabled 
		      from users where username=?" 
 
		   authorities-by-username-query="
		      select u.username, ur.authority from users u, user_roles ur 
		      where u.user_id = ur.user_id and u.username =?  " 
 
		/>
	   </authentication-provider>
	</authentication-manager>
 
</beans:beans>




:

3. Spring MVC 에 Spring Security 적용해 보기

ITWeb/개발일반 2012. 3. 12. 12:40
Spring MVC 에 기본 Minimal http configuration 에대한 소스 코드만 삽입해 놓습니다.
확장 버전은 직접 해보시는면 좋겠죠.
- 다만, 진행 하면서 코드는 추가 하겠습니다.

[소스코드]

- Eclipse import 하시면 프로젝트 확인 가능 합니다.


※ import/export 방법은 아래 글 참고하세요.
http://jjeong.tistory.com/564 


1. Spring MVC 구성해 보기.
2. Spring MVC 에 MyBatis 적용해 보기.
3. Spring MVC 에 Spring Security 적용해 보기. 
4. Spring MVC 에 Hibernate 적용해 보기. 
5. 2+3번 적용해 보기.
6. 3+4번 적용해 보기. 


- 소스코드를 첨부 하였으므로 요약 정보만 기술 합니다.

[참고링크]


[pom.xml]
- spring security 관련 dependency 추가 합니다.

<!-- Spring Security 사용을 위한 dependency 등록 Start -->

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-core</artifactId>

            <version>3.1.0.RELEASE</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-web</artifactId>

            <version>3.1.0.RELEASE</version>

        </dependency>

        <dependency>

            <groupId>org.springframework.security</groupId>

            <artifactId>spring-security-config</artifactId>

            <version>3.1.0.RELEASE</version>

        </dependency>

<!-- Spring Security 사용을 위한 dependency 등록 End -->



[web.xml]
- security 관련 fitler 와 context 설정을 등록 합니다.

    <context-param>

        <param-name>contextConfigLocation</param-name>

        <param-value>

        /WEB-INF/spring/root-context.xml

        classpath:context/**/applicationContext*.xml

        </param-value>

    </context-param>


<!-- Spring Security 사용을 위해 filter 추가 Start -->

    <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>

<!-- Spring Security 사용을 위해 filter 추가 End -->



[application-security.xml]
- http security 관련 설정을 합니다.
- 메모리 기반의 인증 처리 방식 입니다. (추후 업그레이드가 되어야 하는 부분)

<?xml version="1.0" encoding="UTF-8"?>

<beans:beans xmlns="http://www.springframework.org/schema/security"

    xmlns:beans="http://www.springframework.org/schema/beans" 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.0.xsd

           http://www.springframework.org/schema/security

           http://www.springframework.org/schema/security/spring-security-3.1.xsd">


    <http auto-config='true'>

        <intercept-url pattern="/**" access="ROLE_USER" />

    </http>


    <authentication-manager>

        <authentication-provider>

            <user-service>

                <user name="jimi" password="1234" authorities="ROLE_USER, ROLE_ADMIN" />

                <user name="bob" password="1234" authorities="ROLE_USER" />

            </user-service>

        </authentication-provider>

    </authentication-manager>

</beans:beans>



[실행하기]
- Spring MVC 예제에서 했던 것과 같습니다.
- 이전 글을 참고해 주세요.

- 아래는 실행 시킨 결과 화면 입니다.

[테스트URL]
http://localhost:8080/security/index.html 

[인증 전]

 
[인증 후] 

 


※ 보시는 것 처럼 spring security의 시작은 아주 쉽게 따라 할 수 있습니다. 문서를 잘 참고 하시면 됩니다.
: