SpringSecurity安全配置—SSH整合

SpringSecurity安全配置—SSH整合

项目中使用了SpringSecurity,发现SpringSecurity实现登录管理很方便,花了一点时间,将SpringSecurity安全配置整理出来,实现SpringSecurity安全配置登陆,供需要的朋友参考,如有整理不到位的地方,请提出意见,谢谢!

使用Springsecurity首先要提的就是jar包了,Springsecurity的jar下载地址:http://static.springsource.org/spring-security/site/downloads.html。不过我的项目里的jar包比较旧点了,是从项目抽取出来的,所需jar如下:

第1步:新建一个web工程,将Springsecurity的jar添加到web工程中WEB-INF中lib中,本DEMO中整合了Struts2,Hibernate,Spring,编写web.xml,具体配置如下:


xmlns="http://java.sun.com/xml/ns/javaee" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

 
 
  contextConfigLocation
  classpath:applicationContext*.xml
 


 
 
  chinese
  com.filter.EncodingFilter
 

  
 
 
  loginFilter
  com.filter.LoginFilter
  
  
  
  sessionKey
  LOGIN_NAME
  

  
  
  
  redirectURL
  /user/login.htm
  

  
  
  
  notCheckURLList
  /user/login.htm;/user/my.htm;
  

 

  
 
 
  openSession
  org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
 

  
 
   
    springSecurityFilterChain  
    org.springframework.web.filter.DelegatingFilterProxy  
 

  
   
 
  struts2
  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
 

  
 
  chinese
  /*
 

  
 
  openSession
  /*
 

  
 
  springSecurityFilterChain
    /*  
 

  
   
  loginFilter
  *.htm
 

  
 
  struts2
  *.htm
 



 
 
  org.springframework.web.context.ContextLoaderListener
 

  
 
    index.jsp
 


第2步:编写LoginFilter.java,用于过滤校验用户是否登陆,具体如下:

/**
 * @Discription: 登陆过滤器:
 * 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面 
 * 配置参数:
 * sessionKey:需检查的在 Session 中保存的关键字
 * redirectURL:如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath 
 * notCheckURLList:不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath
 * @Project: SpringSecurity
 * @Package: com.filter
 * @Title: LoginFilter.java
 * @author: [heyong]
 * @date 2012-4-21
 * @version 1.0
 * @update [日期YYYY-MM-DD] [更改人姓名]
 */
public class LoginFilter implements Filter{

/**
*

Discription:[logger日志]


*/
private static Log logger = LogFactory.getLog(LoginFilter.class);

/**
*

Discription:[需检查的在 Session 中保存的关键字]


*/
private String sessionKey = null;

/**
*

Discription:[如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath ]


*/
private String redirectURL = null;

/**
*

Discription:[不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath]


*/
private List notCheckURLList = new ArrayList();

public void destroy() {
notCheckURLList.clear();
}

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request    = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;

// 获得Session
HttpSession session = request.getSession();

// 判断sessionKey 是否为空
if(StringUtils.isEmpty(sessionKey)){
filterChain.doFilter(request, response);
return;
}

if (!checkRequestURIIntNotFilterList(request)) {
UserDetail userDetail = null;
try {
// 取得当前用户登陆的信息
userDetail = (UserDetail)SpringSecurityUtils.getCurrentUser();
} catch (Exception e) {
logger.info("Event=[LoginFilter#doFilter] redirect:".concat(request.getContextPath().concat(redirectURL)));
response.sendRedirect(request.getContextPath().concat(redirectURL));
return;
}

// 判断是否登陆
if (userDetail == null || userDetail.getUserId() == null) {
response.sendRedirect(request.getContextPath().concat(redirectURL));
return;
}

// 在userDetail中得到用户信息
SysStUser user = userDetail.getCurrentUser();

// UserDetail 存在,测检查Session是否存在,若不存在则,初始化Session
if (session.getAttribute(sessionKey) == null) {
logger.info("Event=[LoginFilter#doFilter] sessionKey: " + sessionKey);
session.setAttribute(sessionKey, user);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}

public void init(FilterConfig filterConfig) throws ServletException {
sessionKey     = filterConfig.getInitParameter("sessionKey");
redirectURL    = filterConfig.getInitParameter("redirectURL");
String urlList = filterConfig.getInitParameter("notCheckURLList");

if (StringUtils.isNotEmpty(urlList)) {
StringTokenizer st = new StringTokenizer(urlList, ";");
notCheckURLList.clear();
while (st.hasMoreTokens()) {
notCheckURLList.add(st.nextToken());
}
}
}

/**
* @Description: 检测当前访问URL,是否有过滤掉的URL。
* @author [heyong]
* @date 2012-4-21
* @version 1.0
* @param request
* @return
* @update:[日期YYYY-MM-DD] [更改人姓名]
*/
private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
        String url = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
        return notCheckURLList.contains(url);
    }
}

第3步:提供一个UserDetail.java,该类继承org.springframework.security.userdetails.User类,用于保存一些自定义的业务数据,具体如下:

/**
 * @Discription: UserDetail继承User
 * @Project: SpringSecurity
 * @Package: com.security
 * @Title: UserDetail.java
 * @author: [heyong]
 * @date 2012-4-21
 * @version 1.0
 * @update [日期YYYY-MM-DD] [更改人姓名]
 */
public class UserDetail extends User {
/**
*

Discription:[serialVersionUID]


*/
private static final long serialVersionUID = 5533186529087001787L;

/**
* 用户ID
*/
private String userId;

/**
* 用户真实姓名
*/
private String realName;

/**
* 当前登录的用户信息
*/
private SysStUser currentUser;

public UserDetail(String userId, String realName, String username,String password, GrantedAuthority[] authorities) {
super(username, password, true, true, true, true, authorities);
this.userId = userId;
this.realName = realName;
}

public UserDetail(String username, String password, boolean enabled,
          boolean accountNonExpired, boolean credentialsNonExpired,
          boolean accountNonLocked, GrantedAuthority[] authorities)throws IllegalArgumentException {
super(username, password, enabled, accountNonExpired,credentialsNonExpired, accountNonLocked, authorities);
}

public String getUserId() {
return userId;
}

public void setUserId(String userId) {
this.userId = userId;
}

public String getRealName() {
return realName;
}

public void setRealName(String realName) {
this.realName = realName;
}

public SysStUser getCurrentUser() {
return currentUser;
}

public void setCurrentUser(SysStUser currentUser) {
this.currentUser = currentUser;
}
}

第4步:提供一个UserDetailsServiceImpl.java,该类实现org.springframework.security.userdetails.UserDetailsService类,必须实现loadUserByUsername()方法,具体如下:

/**
 * @Discription: UserDetailsServiceImpl实现UserDetailsService接口,实现UserDetailsService类中loadUserByUsername()方法
 * @Project: SpringSecurity
 * @Package: com.iservices
 * @Title: UserDetailsServiceImpl.java
 * @author: [heyong]
 * @date 2012-4-20
 * @version 1.0
 * @update [日期YYYY-MM-DD] [更改人姓名]
 */
public class UserDetailsServiceImpl implements UserDetailsService{

/**
* 用户信息Services(自已提供查询Services查询接口)
*/
private UsersServices usersServices;

/**
* @Description: 实现loadUserByUsername(),根据用户名明查询用户的信息
* @author [heyong]
* @date 2012-4-20
* @version 1.0
* @param LoginName:登陆用户名
* @return
* @throws UsernameNotFoundException
* @throws DataAccessException
* @update:[日期YYYY-MM-DD] [更改人姓名]
*/
public UserDetails loadUserByUsername(String LoginName)throws UsernameNotFoundException, DataAccessException {
SysStUser sysStUser = usersServices.searchSysUserByLoginName(LoginName);
if (sysStUser != null) {
UserDetail userdetail = new UserDetail(sysStUser.getId(), sysStUser.getUserRname(), sysStUser.getUserName(),sysStUser.getUserPwd(),new GrantedAuthority[0]);
userdetail.setCurrentUser(sysStUser);
return userdetail;
}
return null;
}

public void setUsersServices(UsersServices usersServices) {
this.usersServices = usersServices;
}
}

第5步:提供一个ResourceDetailsServiceImpl.java,该类实现org.springside.modules.security.springsecurity.ResourceDetailsService类,必须实现getRequestMap()方法,具体如下:

/**
 * 从数据库查询URL--授权定义Map的实现类.
 */
public class ResourceDetailsServiceImpl implements ResourceDetailsService {
public LinkedHashMap getRequestMap() throws Exception {
return new LinkedHashMap();
}
}


第6步:前面基础的java实现类都已将准备完成了,接下来重要的一步来了。在web工程的src目录下新建一个applicationContext-security.xml,用于SpringSecurity安全配置,具体如下:


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-2.5.xsd
                        http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.4.xsd"
default-autowire="byType" default-lazy-init="true">

SpringSecurity安全配置

 

 
authentication-failure-url="/user/login.htm?error=true" /> 
 
 








































到此为止,基本的java类,以及配置,都已完成。

第5步:准备测试jsp页面,login.jsp,具体如下:


   


    

用户登陆-SpringSecurity安全配置Demo


   

 

浏览器地址栏里输入下面的url:


测试:录入用户名:admin;密码:123456,然后点击提交按钮,最终页面如下:


测试:录入不存在的用户名:abcdfg;密码:123456,然后点击提交按钮,最终页面如下:


你可能感兴趣的:(Java,ssh,filter,springSecurity)