acegi

Last week, about Acegi security framework of the SSH application in the beginning because Acegi configuration file loading mode confusion a few days, in the end is added to the form of plug-in configuration file struts struts -config.xml In statement or in the web deployment descriptor .xml In statement? Finally the answer, in the web .xml In a statement. Acegi as claimed, it will be loosely coupled with your existing applications for seamless integration. Following the initial application on it to be a description.

Among them, the need to use the jar package are: acegi -security-1.0.3.jar acegi-security-cas-1.0.3.jar commons-codec-1.3.jar 1. First is the web deployment descriptor .xml <?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Container boot parameters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-acegi-security.xml</param-value>
</context-param>

<!-- Character encoding filter -->
<filter>
<filter-name>Set Character Encoding</filter-name>
<filter-class>com.xps.util.SetCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Set Character Encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- Acegi Filter -->
<filter>
<filter-name>Acegi Filter Chain Proxy</filter-name>
<filter-class>org.acegisecurity.util.FilterToBeanProxy</filter-class>
<init-param>
<param-name>targetClass</param-name>
<param-value>org.acegisecurity.util.FilterChainProxy</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>Acegi Filter Chain Proxy</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- struts Controller initialization configuration -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

<!-- Acegi of the context for the listener load -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- System default home page -->
<welcome-file-list>
<welcome-file>/jsp/index.jsp</welcome-file>
</welcome-file-list>
</web-app> Red is the application Acegi need to add, first of all context -param To Acegi's configuration file as a startup parameter loaded into the container, while FilterToBeanProxy as it name suggests, is a filter agent, which is responsible for the different resources to each filter corresponds to, ContextLoaderListener monitor the situation for context loading. 2 . Second, more complex Acegi configuration file applicationContext -acegi-security.xml . <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>

<!-- Acegi authentication database for the preparation of the data source configuration -->
<bean>
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/xgame</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123456</value>
</property>
</bean>

<!-- Filter chain proxy -->
<bean>
<property name="filterInvocationDefinitionSource">
<value>
CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON
PATTERN_TYPE_APACHE_ANT
/**=httpSessionContextIntegrationFilter,logoutFilter,
authenticationProcessingFilter,securityContextHolderAwareRequestFilter,
rememberMeProcessingFilter,anonymousProcessingFilter,
exceptionTranslationFilter,filterInvocationInterceptor
</value>
</property>
</bean>

<!-- Session context integration filter -->
<bean/>

<!-- Cancellation filter -->
<bean>
<constructor-arg value="/jsp/index.jsp"/> <!-- URL redirected to after logout -->
<constructor-arg>
<list>
<ref bean="rememberMeServices"/>
<bean/>
</list>
</constructor-arg>
</bean>

<!-- Authentication processing filter -->
<bean>
<property name="authenticationManager" ref="authenticationManager"/>
<property name="authenticationFailureUrl" value="/jsp/login.jsp"/>
<property name="defaultTargetUrl" value="/login.do"/>
<property name="filterProcessesUrl" value="/j_acegi_security_check"/>
<property name="rememberMeServices" ref="rememberMeServices"/>
</bean>

<bean/>

<!-- Cookie Log filters -->
<bean>
<property name="authenticationManager" ref="authenticationManager"/>
<property name="rememberMeServices" ref="rememberMeServices"/>
</bean>

<!-- Anonymous logon processing filters -->
<bean>
<property name="key" value="changeThis"/>
<property name="userAttribute" value="anonymousUser,AUTH_ANONYMOUS"/>
</bean>

<!-- Exception handling filter -->
<bean>
<property name="authenticationEntryPoint">
<bean>
<property name="loginFormUrl" value="/jsp/login.jsp"/>
<property name="forceHttps" value="false"/>
</bean>
</property>
<property name="accessDeniedHandler">
<bean>
<property name="errorPage" value="/jsp/noGrant.jsp"/>
</bean>
</property>
</bean>

<!-- Filter Blocker -->
<bean>
<property name="authenticationManager"><ref bean="authenticationManager"/></property>
<property name="accessDecisionManager"><ref local="httpRequestAccessDecisionManager"/></property>
<property name="objectDefinitionSource">
<value>
PATTERN_TYPE_APACHE_ANT

<!-- Permissions for all users -->
/searchUser.do=AUTH_USER,AUTH_ROOT,AUTH_RELEASER,AUTH_AUDITOR
/updateInformation.do=AUTH_USER,AUTH_ROOT,AUTH_RELEASER,AUTH_AUDITOR

<!-- Permission to ordinary users -->
/preOrderAd.do=AUTH_USER
/orderAd.do=AUTH_USER
/myAdList.do=AUTH_USER
/findReOrderAd.do=AUTH_USER
/ReOrder.do=AUTH_USER

<!--==== Super administrator rights ====-->

<!-- Auditor competence -->
/noaudit.do=AUTH_AUDITOR,AUTH_ROOT
/allAuditAdNoPass.do=AUTH_AUDITOR,AUTH_ROOT
/auditedAd.do=AUTH_AUDITOR
/audited.do=AUTH_AUDITOR,AUTH_ROOT
/notify.do=AUTH_AUDITOR,AUTH_ROOT
/editAuditedEmail.do=AUTH_AUDITOR,AUTH_ROOT

<!-- Members of the authority issued -->
/unpaymentOrderList.do=AUTH_RELEASER,AUTH_ROOT
/paymentOrderList.do=AUTH_RELEASER,AUTH_ROOT

<!-- Super administrator rights -->
/manageAdpos.do=AUTH_ROOT
/manageUser.do=AUTH_ROOT
/addNewAdpos.do=AUTH_ROOT


</value>
</property>
</bean>

<!-- Request for arbitration Manager -->
<bean>
<property name="allowIfAllAbstainDecisions"><value>false</value></property>
<property name="decisionVoters">
<list>
<ref bean="roleVoter"/>
</list>
</property>
</bean>

<!-- Cookie Server -->
<bean>
<property name="userDetailsService" ref="jdbcDaoImpl"/>
<property name="key" value="changeThis"/>
</bean>

<!-- Certification Manager -->
<bean>
<property name="providers">
<list>
<ref local="daoAuthenticationProvider"/>
<bean>
<property name="key" value="changeThis"/>
</bean>
<bean>
<property name="key" value="changeThis"/>
</bean>
</list>
</property>
</bean>

<!-- A simple database-based authentication -->
<bean>
<property name="userDetailsService" ref="jdbcDaoImpl"/>
<property name="userCache">
<bean>
<property name="cache">
<bean>
<property name="cacheManager">
<bean/>
</property>
<property name="cacheName" value="userCache"/>
</bean>
</property>
</bean>
</property>
</bean>

<!-- User name password match verification and return UserDetails -->
<bean>
<property name="dataSource" ref="dataSource"/>
<property name="usersByUsernameQuery">
<value>select username, password, enabled from user where username = ? and enabled = 1</value>
</property>
<property name="authoritiesByUsernameQuery">
<value>
select u.username, a.authority
from user u, authorities a, user_auth ua
where u.id=ua.user_id and a.id=ua.auth_id and u.username=?
</value>
</property>
</bean>

<!-- Log in Log listener, only for logging, ( Optional ) -->
<bean/>

<!-- Permissions voting machine, mainly used for setting permissions prefix -->
<bean>
<property name="rolePrefix" value="AUTH_"/>
</bean>
</beans>

After a general need in the user login session in order to record user information needs of local calls, so you can log in but after turning LoginAction, in this Action which you can User name seesion years, and then mapping to display the login success page , the code is as follows:

package com.xps.controller.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.acegisecurity.context.SecurityContextHolder;
import org.acegisecurity.userdetails.UserDetails;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class LoginAction extends Action {


public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {

String username = null;
// Acegi's Context from the get user information
Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

if(obj instanceof UserDetails){
username = ((UserDetails)obj).getUsername();
}else{
username = obj.toString();
}

HttpSession session = request.getSession(true);
session.setAttribute("username", username);
return mapping.findForward("success");
}
}

Acegi configuration file above the red part of the changes according to their own needs. Acegi configuration file for instructions, have many friends stood out clearly, and I also do not have much to say, in the next article in reference to a blue font is the User's ( It uses the Acegi version of acegi -security-0.8.3.jar , So some packages may have different ) If the above did not understand the explanations below can be combined to understand. Note: The blue field is a reference section, as reproduced on the internet too much, could not find the original source, please forgive me

In applicationContext -acegi-security.xml In

FILTER CHAIN

FilterChainProxy will call the filter in order to , These filter functions can enjoy Spring ioc , CONVERT_URL_TO_LOWERCASE_BEFORE_COMPARISON Defines the url to lowercase before comparison, PATTERN _TYPE_APACHE_ANT Define the matching model using Apache ant

Basic authentication

1) authenticationManager
Play the role of authentication management, which will verify the function entrusted to the number of Provider, and by traversing Providers , To ensure access to different sources of authentication, if a Provider can be successfully identified the current user's identity, authenticate () Method will return a complete license information contains the user Authentication object, otherwise it will throw an AuthenticationException.
Acegi Provides a different implementation AuthenticationProvider , Such as:
DaoAuthenticationProvider Read user information from the database authenticate
AnonymousAuthenticationProvider Anonymous user authentication
RememberMeAuthenticationProvider Saved cookie in the user authentication information
AuthByAdapterProvider Use container adapter authentication
CasAuthenticationProvider According to verify the identity of Yale Center Certification Service , Used to implement single sign
JaasAuthenticationProvider Landing configuration from JASS authenticate access to user information
RemoteAuthenticationProvider Authenticate users based remote service
RunAsImplAuthenticationProvider Manager of identity has been replaced by the user authentication
X509AuthenticationProvider To obtain certification from the X509 authenticate user information
TestingAuthenticationProvider The use of unit testing

Each person will have their own authentication information specified in that certificate, if this proves DaoAuthenticationProvider information only UsernamePasswordAuthenticationToken certification.


2) daoAuthenticationProvider
A simple database-based authentication. DaoAuthenticationProvider access to the database to match the account password and, if successful at the same time through the user returns an Authentication object that contains authorization information, otherwise the authentication fails, throw a AuthenticatiionException.


3) passwordEncoder
The use of encryption devices on the user input the text is encrypted. Acegi provides three encryption devices :
PlaintextPasswordEncoder - By default, no encryption, return plaintext .
ShaPasswordEncoder - Hash algorithm (SHA) Encryption
Md5PasswordEncoder - News Summary (MD5) Encryption

4) jdbcDaoImpl
Used to get user information in the data. acegi provides authorized users and table structure, but you can own to achieve. By usersByUsernameQuery this SQL to get your ( User ID , Password , State information ); By authoritiesByUsernameQuery this SQL to get your ( User ID , Authorization information )

5) userCache & resourceCache
Cache user and resource information corresponding permissions. When requesting a protected resource, daoAuthenticationProvider will be called to obtain the user authorization information. If obtained from the database each time, then the price is high, for the infrequent user and resource information to change the terms, it is best to related cached authorization information. ( See 2 .6.3 Resources to expand the definition of competence )
userCache Provides two implementation : NullUserCache And EhCacheBasedUserCache , NullUserCache In fact without any cache, EhCacheBasedUserCache is achieved using Ehcache slow function.

6) basicProcessingFilter
Certification for handling HTTP header information, such as the remote protocol from the Spring ( Such as Hessian and Burlap ) Or common browser such as IE ,Navigator The HTTP header to get user information, the properties they refer to the assembly by authenticationManager certification manager. If authentication is successful, will be an Authentication object into session, or, if the authentication fails, control will be transferred to the authentication Entry Point ( Assembly by authenticationEntryPoint property )

7) basicProcessingFilterEntryPoint
Through the browser sends a HTTP401 ( Unauthorized ) Message prompts the user to log on.
Handle HTTP-based authorization process, when the verification process after abnormal " Whereabouts " Usually achieve steering, in response have added features such as error messages.

8) authenticationProcessingFilterEntryPoint
When thrown AccessDeniedException when the user is redirected to the login screen. Property loginFormUrl configured with a login form URL , When you need the user login, authenticationProcessingFilterEntryPoint will redirect the user to the URL

HTTP Security Request

1) httpSessionContextIntegrationFilter
Each request to obtain pre-HttpSessionContextIntegrationFilter Authentication object from the Session, After the request , Session Authentication object stored again in the next request for use , The filter must be used before other Acegi filter, so that it can span multiple requests.


2) httpRequestAccessDecisionManager
After the voting mechanism to determine whether access to a resource (URL Or methods ) . allowIfAllAbstainDecisions is false, if one or more of the decisionVoters vote , Is authorized by. Optional decision-making mechanism ConsensusBased and UnanimousBased


3) roleVoter
Value is set to begin rolePrefix permission to vote , If AUTH _ , ROLE_

4 ) ExceptionTranslationFilter
Abnormal conversion filters, mainly dealing with AccessDeniedException and AuthenticationException, will find the right of each anomaly " Whereabouts "

5) authenticationProcessingFilter
And the servlet spec is almost , Processing login requests . When authentication is successful, AuthenticationProcessingFilter place in a session Authentication object, and redirect to the login success page
authenticationFailureUrl Turn the definition of a page when login fails
defaultTargetUrl Turn the definition of landing page success
filterProcessesUrl Defined landing page request
rememberMeServices Used to add the cookie information after successful authentication

6) filterInvocationInterceptor
Shift in the implementation of the pre-inspection objectDefinitionSource url set of user rights information. First of all, objectDefinitionSource defines the properties needed to access URL information ( Attribute information here is only a symbol of what use to tell accessDecisionManager voter to vote ) . Then, authenticationManager out with their own user authentication provider to verify the information. Finally, voters hold the user authentication and access properties url need, call their own voter to vote, decide whether to allow access.


7) filterDefinitionSource
Custom DBFilterInvocationDefinitionSource read from the database and the cache need to protect resources and their access to information

Method calls the security control

1) methodSecurityInterceptor
Intercept in the implementation of the method before, check the user rights information
2) methodDefinitionSource
Custom MethodDefinitionSource permission to read from the cache

<bean>
<property name="authenticationManager" ref="authenticationManager"/>
<property name="accessDecisionManager" ref="httpRequestAccessDecisionManager"/>
<property name="objectDefinitionSource" ref="methodDefinitionSource"/>
</bean>
<bean>
<property name="acegiCacheManager" ref="acegiCacheManager"/>
</bean>

3. Finally, the login page login .jsp
<html>
<head>
<title> User Login </title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body topmargin="0">
<form action="j_acegi_security_check" method="POST">
<table>
<tr><td> User name :</td><td><input type='text' name='j_username'></td></tr>
<tr><td> Password :</td><td><input type='password' name='j_password'></td></tr>
<tr>
<td><input name="submit" type="submit" value=" Login "></td>
<td><input name="reset" type="reset" value=" Reset "></td>
</tr>
</table>
</form>
</body>
</html>


The red part of the name must be fixed with Acegi, if you want to log off, simply add <a href="j_acegi_logout"> Off </a> If the records need to login to the cookie, you can use <input type="checkbox" name="_acegi_security_remember_me">Don't ask for my password for two weeks , So that users do not log on within two weeks, also had access to the system.

Postscript, in fact, Acegi authentication and authorization aspects of the function is very powerful, it worthy of its complex configuration - - ! I just use it to do a little elementary applications, for some advanced features (like the method level of access control, etc.) used in the study again Yi Hou.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值