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<String, Collection<ConfigAttribute>> resourceMap = null;

private UrlMatcher urlMatcher = new AntUrlPathMatcher();





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

public void loadResourceDefine()throws Exception {

this.resourceMap = new HashMap<String, Collection<ConfigAttribute>>();



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

List<BasicAuthorities> authoritiesList = basicAuthoritiesHibernateDAO.findAllByDeleteFlag();

for(int i=0;i<authoritiesList.size();i++){

BasicAuthorities url = (BasicAuthorities)authoritiesList.get(i);

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

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



Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();

ConfigAttribute ca = new SecurityConfig(token);

atts.add(ca);



this.resourceMap.put(antPath, atts);

}

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

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

resourceMap = new HashMap<String, Collection<ConfigAttribute>>();

Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();

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<ConfigAttribute> 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<String> ite = resourceMap.keySet().iterator();

while (ite.hasNext()) {

String resURL = ite.next();

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

Collection<ConfigAttribute> 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<ConfigAttribute> getAllConfigAttributes() {



Set<ConfigAttribute> allAttributes = new HashSet<ConfigAttribute>();

for (Map.Entry<String, Collection<ConfigAttribute>> 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<GrantedAuthority> getAuthorities(int userId) {

List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

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的默认配置很简单,但是为了满足系统的需求是需要重写很多配置的,一般需要好好研究一下源码,才能明白

注:关于<一>的配置没有通过网易审核,不知道网易怎么搞的
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值