﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-云自无心水自闲-随笔分类-Spring</title><link>http://www.blogjava.net/usherlight/category/36797.html</link><description>天平山上白云泉，云自无心水自闲。何必奔冲山下去，更添波浪向人间！</description><language>zh-cn</language><lastBuildDate>Wed, 31 Aug 2011 01:01:28 GMT</lastBuildDate><pubDate>Wed, 31 Aug 2011 01:01:28 GMT</pubDate><ttl>60</ttl><item><title>Spring Security中指定session超时后跳转的页面</title><link>http://www.blogjava.net/usherlight/archive/2011/08/31/357615.html</link><dc:creator>云自无心水自闲</dc:creator><author>云自无心水自闲</author><pubDate>Tue, 30 Aug 2011 23:25:00 GMT</pubDate><guid>http://www.blogjava.net/usherlight/archive/2011/08/31/357615.html</guid><wfw:comment>http://www.blogjava.net/usherlight/comments/357615.html</wfw:comment><comments>http://www.blogjava.net/usherlight/archive/2011/08/31/357615.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/usherlight/comments/commentRss/357615.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/usherlight/services/trackbacks/357615.html</trackback:ping><description><![CDATA[<div>Spring Security中指定session超时后跳转的页面<br /><br />在xml配置文件中加入：&lt;session-management invalid-session-url="/session-timeout.htm" /&gt;<br /></div><img src ="http://www.blogjava.net/usherlight/aggbug/357615.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/usherlight/" target="_blank">云自无心水自闲</a> 2011-08-31 07:25 <a href="http://www.blogjava.net/usherlight/archive/2011/08/31/357615.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Spring MVC + Spring Security + Spring JDBC中注入dataSource总是为Null的原因和解决</title><link>http://www.blogjava.net/usherlight/archive/2011/08/26/357316.html</link><dc:creator>云自无心水自闲</dc:creator><author>云自无心水自闲</author><pubDate>Fri, 26 Aug 2011 00:57:00 GMT</pubDate><guid>http://www.blogjava.net/usherlight/archive/2011/08/26/357316.html</guid><wfw:comment>http://www.blogjava.net/usherlight/comments/357316.html</wfw:comment><comments>http://www.blogjava.net/usherlight/archive/2011/08/26/357316.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/usherlight/comments/commentRss/357316.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/usherlight/services/trackbacks/357316.html</trackback:ping><description><![CDATA[<div><br />在applicationContext.xml中定义了一个DataSource：&lt;bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" /&gt;<br />但是在代码中，使用anotation进行注入的时候，却总是找不到这个dataSource.<br /><br />&nbsp;&nbsp; &nbsp;@Autowired<br />&nbsp;&nbsp; &nbsp;public void setDataSource(DataSource dataSource) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;jdbcTemplate = new JdbcTemplate(dataSource);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;jdbcInsert = new SimpleJdbcInsert(dataSource);<br />&nbsp;&nbsp; &nbsp;}<br /><br />最后终于想明白了，原因大概是这样的，使用autowired的时候，默认是根据类型来匹配的，在xml中定义的类型是：BasicDataSource，而不是接口DataSource，所以默认情况下这样是无法自动装配的。解决办法是指令使用名字来进行bean的匹配，也就是用Qualifier指定bean的id.<br /><br />&nbsp;&nbsp; &nbsp;@Autowired<br />&nbsp;&nbsp; &nbsp;public void setDataSource(@Qualifier("dataSource") DataSource dataSource) {<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;jdbcTemplate = new JdbcTemplate(dataSource);<br />&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;jdbcInsert = new SimpleJdbcInsert(dataSource);<br />&nbsp;&nbsp; &nbsp;}<br /><br /><br /><div>另外一点，在网上搜索的过程中发现有不少人都有类似的问题，但是他们的原因是没有正确使用spring的注入，而是自己在代码中new了一个Dao的实例，这样的话，spring是无法将dataSource注入到dao的实例中的</div><br /></div><img src ="http://www.blogjava.net/usherlight/aggbug/357316.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/usherlight/" target="_blank">云自无心水自闲</a> 2011-08-26 08:57 <a href="http://www.blogjava.net/usherlight/archive/2011/08/26/357316.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Spring Security - Using custom Authentication Processing Filter</title><link>http://www.blogjava.net/usherlight/archive/2010/06/11/323293.html</link><dc:creator>云自无心水自闲</dc:creator><author>云自无心水自闲</author><pubDate>Fri, 11 Jun 2010 00:12:00 GMT</pubDate><guid>http://www.blogjava.net/usherlight/archive/2010/06/11/323293.html</guid><wfw:comment>http://www.blogjava.net/usherlight/comments/323293.html</wfw:comment><comments>http://www.blogjava.net/usherlight/archive/2010/06/11/323293.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/usherlight/comments/commentRss/323293.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/usherlight/services/trackbacks/323293.html</trackback:ping><description><![CDATA[Recently I got a chance working with Spring security, formerly known as Acegi Security for spring. While working with the framework, I heard comments from friends and colleagues saying that spring security lacks proper documentation. So thought of sharing a little knowledge. By the way, this is first ever blog posting and kindly excuse me and let me know any errors and improvements.

Spring security offers a simple configuration based security for your web applications helping you secure your web application with out littering your business logic with any security code. It provides securing URL's based on the Role (Authorities), securing your business methods based on the ACL's.

The first step in hooking up the spring security to your web application is by specifying the DelegatingFilterProxy in your web.xml.

<!--Spring security filter-->
<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>
 <dispatcher>REQUEST</dispatcher>
 <dispatcher>INCLUDE</dispatcher>
 <dispatcher>FORWARD</dispatcher>
</filter-mapping>
<!--End spring security filter-->


If you want to externalize all of your security related configuration into a separate file, you can do so and add that to your context location param.
<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 /WEB-INF/beans.xml , /WEB-INF/springSecurity.xml </param-value>
</context-param>


Now comes the part of security configuration for your application, Adding the URL security patterns is pretty simple and straight forward. Add all the URL patterns which you want to secure and add the wild card pattern at the end. You need to have some default principal and role even for non logged in users as you need to give access to pages like log in, register and forgot password kind of functionality even to non logged in users.

I tried to add comments to pretty much every element which I am using here.
As an example I added just a wild card intercept url which make every page of my application secure. You need to exclude different urls based on the roles.



 <security:http entry-point-ref="myAuthenticationEntryPoint" session-fixation-protection="newSession" >
 <!--add any of your cusotom url patterns to protect--> <security:intercept-url pattern="/login/**" access="ROLE_ANONYMOUS"/> <security:intercept-url pattern="/register/**" access="ROLE_ANONYMOUS"/>
 <security:intercept-url pattern="/**" access="ROLE_USER"/>
 <security:logout logout-success-url="/home.htm"/>
 <security:anonymous username="guest" granted-authority="ROLE_ANONYMOUS"/>
 </security:http>
 <!--name of my authenticationManager is authenticationManager-->
 <security:authentication-manager alias="authenticationManager"/>
 <!--Cutom login filter which replaces the default AUTHENTICATION_PROCESSING_FILTER -->
 <bean id="customizedFormLoginFilter" class="org.springframework.security.ui.webapp.AuthenticationProcessingFilter" >
 <security:custom-filter position="AUTHENTICATION_PROCESSING_FILTER"/><!--replace the default one-->
 <property name="defaultTargetUrl" value="/main.htm"/><!--After a successful login, the user will be taken to this page-->
 <property name="authenticationFailureUrl" value="/home.htm?error=true" /><!--Authentication failed? take him to error page-->
 <property name="authenticationManager" ref="myAuthenticationManager"/> <!--Here it is the custom authenticationManager, login magic goes here -->
 <property name="allowSessionCreation" value="true" /> <!--Allow the application to create sessions-->
 </bean>
 <!--My custom auth manager-->
 <bean id="myAuthenticationManager" class="com.teja.security.CustomAuthunticationManager" />
 <!-- Automatically receives AuthenticationEvent messages -->
 <bean id="loggerListener" class="org.springframework.security.event.authentication.LoggerListener"/>
 <!--My authuntication entry point, can be replaced easily if we are doing custom commence of invalid auths.-->
 <bean id="myAuthenticationEntryPoint"
 class="com.teja.security.CustomAuthenticationEntryPoint" >
 <property name="loginFormUrl" value="/home.htm"/>
 </bean>

Following is my custom implementation of AuthenticationEntryPoint, which currently is not doing any thing except leveraging the commence to its super class which is the spring implementation of AuthenticationProcessingFilterEntryPoint. I hooked it to add any custom logic.

public class CustomAuthenticationEntryPoint extends AuthenticationProcessingFilterEntryPoint {
 private static final Log logger = LogFactory.getLog(CustomAuthenticationEntryPoint.class);
 

 @Override
 public void commence(ServletRequest request, ServletResponse response, AuthenticationException authException) throws IOException, ServletException {
 super.commence(request, response, authException);
 }
}

This is my custom authentication manager which actually does the custom login of the user. It will throw an BadCredentialsException in case of invalid credentials or thorws a AuthenticationServiceException in case of a service error (Database error, SQL error or any other error).

public class CustomAuthunticationManager implements AuthenticationManager {
 @Autowired
 UserManagerService userManagerService;
 public Authentication authenticate(Authentication authentication) throws AuthenticationException {
 if(StringUtils.isBlank((String) authentication.getPrincipal()) || StringUtils.isBlank((String) authentication.getCredentials())){
 throw new BadCredentialsException("Invalid username/password");
 }
 User user = null;
 GrantedAuthority[] grantedAuthorities = null;
 try{
 user = userManagerService.getUser((String) authentication.getPrincipal(), (String) authentication.getCredentials());
 }
 catch(InvalidCredentialsException ex){
 throw new BadCredentialsException(ex.getMessage());
 }
 catch(Exception e){
 throw new AuthenticationServiceException("Currently we are unable to process your request. Kindly try again later.");
 }
 if (user != null) {
 List<Role> roles = user.getAssociatedRoles();
 grantedAuthorities = new GrantedAuthority[roles.size()];
 for (int i = 0; i &lt; roles.size(); i++) {
 Role role = roles.get(i);
 GrantedAuthority authority = new GrantedAuthorityImpl(role.getRoleCode());
 grantedAuthorities[i] = authority;
 }
 }
 else{
 throw new BadCredentialsException("Invalid username/password");
 }
 return new UsernamePasswordAuthenticationToken(user, authentication.getCredentials(), grantedAuthorities);
 }
}


At the client side (jsp), the simple configuration you need to do is post the request to"/j_spring_security_check" with parameters "j_username" and "j_password".

That's pretty much all you need to do for enabling spring security to your existing web application. I will try to explain about doing the method security using ACL's and configuring the view using spring security tags in another post.<img src ="http://www.blogjava.net/usherlight/aggbug/323293.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/usherlight/" target="_blank">云自无心水自闲</a> 2010-06-11 08:12 <a href="http://www.blogjava.net/usherlight/archive/2010/06/11/323293.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>如何使用spring的autowire为servlet注入Bean</title><link>http://www.blogjava.net/usherlight/archive/2009/09/04/293864.html</link><dc:creator>云自无心水自闲</dc:creator><author>云自无心水自闲</author><pubDate>Fri, 04 Sep 2009 06:19:00 GMT</pubDate><guid>http://www.blogjava.net/usherlight/archive/2009/09/04/293864.html</guid><wfw:comment>http://www.blogjava.net/usherlight/comments/293864.html</wfw:comment><comments>http://www.blogjava.net/usherlight/archive/2009/09/04/293864.html#Feedback</comments><slash:comments>2</slash:comments><wfw:commentRss>http://www.blogjava.net/usherlight/comments/commentRss/293864.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/usherlight/services/trackbacks/293864.html</trackback:ping><description><![CDATA[在应用中一般普通的JavaPojo都是由Spring来管理的，所以使用autowire注解来进行注入不会产生问题，但是有两个东西是例外的，一个是Filter，一个是Servlet，这两样东西都是由Servlet容器来维护管理的，所以如果想和其他的Bean一样使用Autowire来注入的话，是需要做一些额外的功夫的。<br />
对于Filter，Spring提供了DelegatingFilterProxy，所以本文主要讲述Servlet的解决。<br />
1、比较直观但是不大优雅的做法是重写init()方法，在里面使用AutowireCapableBeanFactory来手工告诉Spring：我这个Servlet是需要这样的一个Bean的。具体写法：<br />
public void init(ServletConfig servletConfig) throws ServletException {<br />
&nbsp;&nbsp;&nbsp; ServletContext servletContext = servletConfig.getServletContext();<br />
&nbsp;&nbsp;&nbsp; WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);<br />
&nbsp;&nbsp;&nbsp; AutowireCapableBeanFactory autowireCapableBeanFactory = webApplicationContext.getAutowireCapableBeanFactory();<br />
&nbsp;&nbsp;&nbsp; autowireCapableBeanFactory.configureBean(this, BEAN_NAME);<br />
}<br />
其中，BEAN_NAME就是需要注入的Bean在spring中注册的名字.<br />
这样写的主要问题是就是那个BEAN_NAME,这样写有点主动查找，而不是依赖注入的感觉。<br />
<br />
2、创建一个类似于DelegatingFilterProxy那样的代理，通过代理根据配置来找到实际的Servlet，完成业务逻辑功能。<br />
假定我们有一个Servlet名字叫UserServlet，需要注入一个UserManager，伪代码如下：<br />
public class UserServlet extends HttpServlet {<br />
&nbsp;&nbsp;&nbsp; @Autowired(required = true)<br />
&nbsp;&nbsp;&nbsp; private UserManager userManager;<br />
}<br />
第一步:<br />
public class DelegatingServletProxy extends GenericServlet {<br />
&nbsp;&nbsp;&nbsp; private String targetBean;<br />
&nbsp;&nbsp;&nbsp; private Servlet proxy;<br />
<br />
&nbsp;&nbsp;&nbsp; @Override<br />
&nbsp;&nbsp;&nbsp; public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; proxy.service(req, res);<br />
&nbsp;&nbsp;&nbsp; }<br />
<br />
&nbsp;&nbsp;&nbsp; @Override<br />
&nbsp;&nbsp;&nbsp; public void init() throws ServletException {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.targetBean = getServletName();<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; getServletBean();<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; proxy.init(getServletConfig());<br />
&nbsp;&nbsp;&nbsp; }<br />
<br />
&nbsp;&nbsp;&nbsp; private void getServletBean() {<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; this.proxy = (Servlet) wac.getBean(targetBean);<br />
&nbsp;&nbsp;&nbsp; }<br />
}<br />
第二步：<br />
配置web.xml文件，原来UserServlet的配置大致是这样的：<br />
&nbsp;&nbsp;&nbsp; &lt;servlet&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;userServlet&lt;/servlet-name&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;servlet-class&gt;com.sample.UserServlet&lt;/servlet-class&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/servlet&gt;<br />
<br />
&nbsp;&nbsp;&nbsp; &lt;servlet-mapping&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;userServlet&lt;/servlet-name&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;/userServlet&lt;/url-pattern&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/servlet-mapping&gt;<br />
现在修改为<br />
&nbsp;&nbsp;&nbsp; &lt;servlet&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;userServlet&lt;/servlet-name&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;servlet-class&gt;com.sample.DelegatingServletProxy&lt;/servlet-class&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/servlet&gt;<br />
<br />
&nbsp;&nbsp;&nbsp; &lt;servlet-mapping&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;servlet-name&gt;userServlet&lt;/servlet-name&gt;<br />
&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &lt;url-pattern&gt;/userServlet&lt;/url-pattern&gt;<br />
&nbsp;&nbsp;&nbsp; &lt;/servlet-mapping&gt;<br />
注意,spring是根据Servlet的名字来查找被代理的Servlet的，所以，首先我们要在UserServlet类前面加上@Component,来告诉Srping：我也是一个Bean。如果名称和Web.xml里面定义的不一样的话，可以在这里指定Bean的名字，比如： @Component("userServlet")<br />
<br />
<br /><img src ="http://www.blogjava.net/usherlight/aggbug/293864.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/usherlight/" target="_blank">云自无心水自闲</a> 2009-09-04 14:19 <a href="http://www.blogjava.net/usherlight/archive/2009/09/04/293864.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>