spring security 整合

本文详细解析了Spring Security框架中的异常处理机制,包括登录验证、权限控制及异常记录等方面。通过配置文件securityContext.xml实现自定义认证提供者和用户详情服务,确保系统安全稳定运行。
摘要由CSDN通过智能技术生成

【涉及文件】

ExceptionHandleServlet.java    --- 异常信息处理

MyDaoAuthenticationProvider.java  -- 验证入口,验证完后记录账户信息

SecurityServiceImpl .java          -- 自定义 User 获取类

securityContext.xml           -- Spring 配置文件

web.xml                              --  定义拦截器等


【securityContext.xml】

<beans:beans xmlns="http://www.springframework.org/schema/security"
	xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:security = "http://www.springframework.org/schema/security"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.1.xsd ">

	<http auto-config="true" authentication-manager-ref="authenticationManager">
	
		<intercept-url pattern="/exceptions" access="IS_AUTHENTICATED_ANONYMOUSLY" />
		<!-- <intercept-url pattern="/resteasy/**" access="IS_AUTHENTICATED_FULLY" /> -->
		<logout invalidate-session="true" logout-url="/webui/j_spring_security_logout" />
			
		<form-login always-use-default-target="true"
			login-processing-url="/j_spring_security_check"
			login-page="/login.html"
			default-target-url="/resteasy/basemanager/acluser/currLogined"
			authentication-failure-url="/ExceptionHandler" />
	</http>

	<authentication-manager id="authenticationManager">
		<authentication-provider ref="daoAuthenticationProvider" />
	</authentication-manager>
	
	<beans:bean id="daoAuthenticationProvider" class="com.xiazhi.security.common.MyDaoAuthenticationProvider">
		<beans:property name="userDetailsService" ref="securityServiceImpl" />
	</beans:bean>
	
</beans:beans>

【SecurityServiceImpl】

@Service(value="securityServiceImpl")
public class SecurityServiceImpl implements UserDetailsService {

	@Autowired
	private AclUserService aclUserService;

	public UserDetails loadUserByUsername(String paramString) throws UsernameNotFoundException {
		
		AclUser user = aclUserService.findAclUsers(paramString).get(0);
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
		List<String> authoritiesStrs = aclUserService.findUserResourcesByIdToList(user.getId());
		for (String authoritiesStr : authoritiesStrs)
			authorities.add(new SimpleGrantedAuthority(authoritiesStr));

		return new User(user.getAccountName(), user.getAccountPwd(), true, true, true, true, authorities);
	}

}

【MyDaoAuthenticationProvider】

@Transactional(noRollbackFor = AuthenticationException.class)
public class MyDaoAuthenticationProvider extends DaoAuthenticationProvider {

	@Autowired
	private AclUserService aclUserService;

	public Authentication authenticate(Authentication paramAuthentication) throws AuthenticationException {
		Authentication result = null;

		int nowdate = (int) (new java.util.Date().getTime() / 1000);
		String j_username = paramAuthentication.getName();
		try {
			
			// 用户登录成功
			result = super.authenticate(paramAuthentication);
			SecurityContextHolder.getContext().setAuthentication(result);
			// 更新用户档的登录时间与次数
			AclUser user = aclUserService.findAclUsers(j_username).get(0);
			user.setLastLoginTime(nowdate);
			user.setLoginTimes((user.getLoginTimes() == null ? 0 : user.getLoginTimes()) + 1);
			user.setErrLoginTimes(0); // 错误次数清零
			aclUserService.updateEntity(user);
			// System.out.println(" 正确日志记录");
		} catch (RuntimeException e) {
			try {
				if (e instanceof AuthenticationException) { // 用户名正确,密码错误
					// 更新用户档的登录失败时间与次数
					AclUser user = aclUserService.findAclUsers(j_username).get(0);
					user.setLastErrLoginTime(nowdate);
					user.setErrLoginTimes((user.getErrLoginTimes() == null ? 0 : user.getErrLoginTimes()) + 1);
					aclUserService.updateEntity(user);

					// System.out.println(" 错误日志记录");
				}
			} catch (Exception e1) { // 用户名错误
				// 插入到日志档,用户ID为空
			}

			// throw new
			// RestRuntimeException(e.getMessage(),e.getMessage(),Status.INTERNAL_SERVER_ERROR,997);
			throw e;
		}

		return result;
	}
}


【ExceptionHandleServlet】

@SuppressWarnings("serial")
public class ExceptionHandleServlet extends HttpServlet {
	
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
		RuntimeException ex=(RuntimeException)request.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION");

		RestRuntimeException restRuntimeException = null;
		
		if(ex instanceof AuthenticationServiceException){
			//用户名错误
			restRuntimeException = RestRuntimeExceptionEnum.ACLUSER_ACCOUNTNAME_ERR.getException();
			if(ex.getCause() instanceof NullPointerException){
				//此帐户已被锁定,请联系管理员
				restRuntimeException = RestRuntimeExceptionEnum.ACLUSER_RESOURCES_ERR.getException();
			}
		}else if(ex instanceof BadCredentialsException){
			//密码错误
			restRuntimeException = RestRuntimeExceptionEnum.ACLUSER_ACCOUNTPWD_ERR.getException();
		}else if(ex instanceof DisabledException){
			//帐户锁定
			restRuntimeException = RestRuntimeExceptionEnum.ACLUSER_LOCK_ERR.getException();
		}else{
			//登陆验证错误
			restRuntimeException = RestRuntimeExceptionEnum.ACLUSER_LOGIN_ERR.getException();
		}
		
//		ex.printStackTrace();
//		restRuntimeException.setStackTrace(ex.getStackTrace());
		
		PrintWriter out = response.getWriter();
		out.write(new Gson().toJson(restRuntimeException));
		out.flush();
		out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

}


【web.xml】

<!-- Spring Security -->
	<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>
	</filter-mapping>
	<servlet>
		<servlet-name>ExceptionHandler</servlet-name>
		<servlet-class>com.xiazhi.security.common.ExceptionHandleServlet</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ExceptionHandler</servlet-name>
		<url-pattern>/ExceptionHandler</url-pattern>
	</servlet-mapping>
	<!-- Spring Security End -->




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值