spring-security-3.0.3. 与Spring3.0.3 集成配置配置说明

3. 实现类

3.1 加载数据库中的权限,也要实现FilterInvocationSecurityMetadataSource类

package com.bestsoft.ssh.service.impl.security;



/**

* 加载所有的权限配置

* @author zhangchaobing

*

*/

public class InvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {



//注入自己的DAO

@Resource(name="basicAuthoritiesHibernateDAO")

private IBasicAuthoritiesDAO basicAuthoritiesHibernateDAO;



private static Map> resourceMap = null;

private UrlMatcher urlMatcher = new AntUrlPathMatcher();





/**此法方法会在启动时 被调用**/

public void loadResourceDefine()throws Exception {

this.resourceMap = new HashMap>();



//查询数据库权限配置表

List authoritiesList = basicAuthoritiesHibernateDAO.findAllByDeleteFlag();

for(int i=0;i
BasicAuthorities url = (BasicAuthorities)authoritiesList.get(i);

String antPath = url.getUrl();//需要验证的URL

String token = url.getToken();//拥有此处权限才能访问URl



Collection atts = new ArrayList();

ConfigAttribute ca = new SecurityConfig(token);

atts.add(ca);



this.resourceMap.put(antPath, atts);

}

System.out.println("---加载所有的权限配置---");

/*//通过硬编码设置,resouce和role

resourceMap = new HashMap>();

Collection atts = new ArrayList();

ConfigAttribute ca = new SecurityConfig("/ROLE_ADD");

atts.add(ca);

resourceMap.put("/jsp/admin.jsp", atts);

*/



}



// According to a URL, Find out permission configuration of this URL.

public Collection getAttributes(Object object) throws IllegalArgumentException {

if (logger.isDebugEnabled()) {

logger.debug("getAttributes(Object) - start"); //$NON-NLS-1$

}

// guess object is a URL.

String url = ((FilterInvocation) object).getRequestUrl();

Iterator ite = resourceMap.keySet().iterator();

while (ite.hasNext()) {

String resURL = ite.next();

if (urlMatcher.pathMatchesUrl(url, resURL)) {

Collection returnCollection = resourceMap.get(resURL);

if (logger.isDebugEnabled()) {

logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$

}

return returnCollection;

}

}

if (logger.isDebugEnabled()) {

logger.debug("getAttributes(Object) - end"); //$NON-NLS-1$

}



return null;

}



public boolean supports(Class clazz) {

return true;

}

public Collection getAllConfigAttributes() {



Set allAttributes = new HashSet();

for (Map.Entry> entry : resourceMap.entrySet()) {

for (ConfigAttribute attrs : entry.getValue()) {

allAttributes.add(attrs);

}

}

return allAttributes;

}



public IBasicAuthoritiesDAO getBasicAuthoritiesHibernateDAO() {

return basicAuthoritiesHibernateDAO;

}

public void setBasicAuthoritiesHibernateDAO(

IBasicAuthoritiesDAO basicAuthoritiesHibernateDAO) {

this.basicAuthoritiesHibernateDAO = basicAuthoritiesHibernateDAO;

}





}

3.2认证用户实现UserDetailsService类类

package com.bestsoft.ssh.service.impl.security;

/**

* 查询用户和用户对应的权限

* @author zhangchaobing

*

*/

public class UserDetailServiceImpl implements UserDetailsService {

@Resource(name="basicUserHibernateDAO")

private IBasicUsersDAO basicUserHibernateDAO;



public UserDetails loadUserByUsername(String username){

try{

//查询用户

BasicUsers user = basicUserHibernateDAO.getBasicUser(username);

BasicUsers returnUser = null;

if(user !=null || !user.equals("")){



returnUser = new BasicUsers(user.getUserId(),user.getUsername(),user.getPassword(),getAuthorities(user.getUserId()),DateTime.getStringDate());

}

return returnUser;

}catch (DataAccessException repositoryProblem) {

repositoryProblem.printStackTrace();

throw new AuthenticationServiceException("数据连接失败,服务器忙,请稍后再试");

}

}

//加载用户对应的权限

public List getAuthorities(int userId) {

List authorities = new ArrayList();

authorities.add(new GrantedAuthorityImpl("ROLE_ANONYMOUS")); //赋予一个临时权限

return authorities;

}

}



3.3为了实现对验证码的验证,这里重写登陆验证Filter 继承

UsernamePasswordAuthenticationFilter类



package com.bestsoft.ssh.service.impl.security;



/**

* 验证用户信息

* @author zhangchaobing

*

*/

public class ValidateCodeUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter{



public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {



//zcb 添加对验证码验证

checkValidateCode(request);

return super.attemptAuthentication( request, response);

}



/**

* 验证 验证码

* @param request

*/

protected void checkValidateCode(HttpServletRequest request) {

String sessionValidateCode = (String) request.getSession().getAttribute("rand");

String validateCodeParameter = request.getParameter("randNum");



if (StringUtils.isEmpty(validateCodeParameter)|| StringUtils.isEmpty(sessionValidateCode) || !sessionValidateCode.equalsIgnoreCase(validateCodeParameter)) {

throw new AuthenticationServiceException("验证码不正确!");

}



}



/**

* 重写父类的方法,在验证用户完成调用的方法

*/

protected void successfulAuthentication(

HttpServletRequest arg0, HttpServletResponse arg1,

Authentication arg2) throws IOException, ServletException {



String username = obtainUsername(arg0);

arg0.getSession().setAttribute("userName",arg0.getParameter("j_username"));

super.successfulAuthentication(arg0, arg1, arg2);

}



}





4. 总结

对于spring securiyt3.0的默认配置很简单,但是为了满足系统的需求是需要重写很多配置的,一般需要好好研究一下源码,才能明白

注:关于<一>的配置没有通过网易审核,不知道网易怎么搞的

你可能感兴趣的:(spring)