cas 实现带验证码的自动登录

Controller类

import java.lang.reflect.Constructor;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.validation.constraints.NotNull;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.validator.constraints.NotEmpty;
import org.jasig.cas.CentralAuthenticationService;
import org.jasig.cas.authentication.principal.Service;
import org.jasig.cas.authentication.principal.SimpleWebApplicationServiceImpl;
import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
import org.jasig.cas.authentication.principal.Response.ResponseType;
import org.jasig.cas.ticket.TicketException;
import org.jasig.cas.util.HttpClient;
import org.jasig.cas.web.support.ArgumentExtractor;
import org.jasig.cas.web.support.CookieRetrievingCookieGenerator;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.ReflectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
import org.springframework.web.servlet.view.RedirectView;

public class SSOController extends AbstractController{
	
	private static final Log log = LogFactory.getLog(SSOController.class);
	
	public static final String CAS_OA_HOMPAGE_URL = "cas.oa.hompage.url";
	
	@NotNull
	private CentralAuthenticationService centralAuthenticationService; 
	
	@NotNull
	private CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator;
	
	@NotNull  
	private CookieRetrievingCookieGenerator warnCookieGenerator;   
	
	@NotEmpty  
	private List<ArgumentExtractor> argumentExtractors; 
	
	@NotNull
	private DataSource  dataSource;
	
	@NotNull
	private PlatformTransactionManager txManager;
	
	private boolean pathPopulated; 

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest req,HttpServletResponse resp) throws Exception {
		resp.addHeader("P3P","CP=\"IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT\"");

		final String token = req.getParameter("token");
		String value=null;
		//获取验证码信息
		final JdbcTemplate jdbcTemplate = new JdbcTemplate(this.dataSource); 
		String querySql = "SELECT VAL FROM CAS_VALIDATOR_CODE WHERE ROUND(TO_NUMBER(SYSDATE - EXPIRE_TIME) * 24 * 60*60)<=60 AND TOKEN=? AND STATUS=0";
		try {
			value = jdbcTemplate.queryForObject(querySql, String.class,token);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("验证码已超时", e);
		}
		//不存在,跳到提示页面
		if(org.apache.commons.lang.StringUtils.isBlank(value)){
			return new ModelAndView("overtimeView");
		}
		String[] values = value.split(":");
		if (!this.pathPopulated) {                 
			final String contextPath = req.getContextPath();                 
			final String cookiePath = StringUtils.hasText(contextPath) ? contextPath + "/" : "/";                 
			logger.info("Setting path for cookies to: "+ cookiePath);                 
			this.warnCookieGenerator.setCookiePath(cookiePath); 
			this.ticketGrantingTicketCookieGenerator.setCookiePath(cookiePath);
			this.pathPopulated = true;             
		}
		UsernamePasswordCredentials credentials = new UsernamePasswordCredentials();  
		credentials.setUsername(values[0]);  
		credentials.setPassword(values[1]);  
		
		String ticketGrantingTicketId="";   
		String serviceTicket = "";   
		String url =null;
		
		try {   
			//读取资源配置文件
			Resource resource = new ClassPathResource("/application.properties");
			Properties props = PropertiesLoaderUtils.loadProperties(resource);
			
			url= props.getProperty(CAS_OA_HOMPAGE_URL);
			
			Constructor<SimpleWebApplicationServiceImpl> constructor = SimpleWebApplicationServiceImpl.class
			.getDeclaredConstructor(String.class, String.class, String.class, ResponseType.class,HttpClient.class); 
			ReflectionUtils.makeAccessible(constructor); 
			
			Service service = constructor.newInstance(url, url,null, ResponseType.REDIRECT,null); 
			
			 ticketGrantingTicketId = this.centralAuthenticationService.createTicketGrantingTicket(credentials);   
	        /***  
	        * 产生新的票据,并将票据及服务记录在缓存中  
	        */  
			serviceTicket=   this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId,service);   
			         
			this.ticketGrantingTicketCookieGenerator.removeCookie(resp);   
			this.warnCookieGenerator.removeCookie(resp); 
			     
			this.ticketGrantingTicketCookieGenerator.addCookie(req, resp, ticketGrantingTicketId);  
			this.warnCookieGenerator.addCookie(req, resp, "true");   
			
			//更新验证码状态
			final String updateSql ="UPDATE CAS_VALIDATOR_CODE SET STATUS=1 WHERE TOKEN=?";
			TransactionTemplate tt =new TransactionTemplate(this.getTxManager());
			tt.execute(new TransactionCallback<Object>() {
				@Override
				public Object doInTransaction(TransactionStatus arg0) {
					jdbcTemplate.update(updateSql,token);
					return null;
				} 
				
			});
		} catch (TicketException e) {   
		     e.printStackTrace();   
		     log.error("请求登录失败", e);
		     return new ModelAndView("oa-errorView");
	    }   

	    return new  ModelAndView(new RedirectView(url+"&ticket="+serviceTicket+"&lt="+System.currentTimeMillis()));   
	}
	

	public CentralAuthenticationService getCentralAuthenticationService() {
		return centralAuthenticationService;
	}

	public void setCentralAuthenticationService(
			CentralAuthenticationService centralAuthenticationService) {
		this.centralAuthenticationService = centralAuthenticationService;
	}

	public CookieRetrievingCookieGenerator getTicketGrantingTicketCookieGenerator() {
		return ticketGrantingTicketCookieGenerator;
	}

	public void setTicketGrantingTicketCookieGenerator(
			CookieRetrievingCookieGenerator ticketGrantingTicketCookieGenerator) {
		this.ticketGrantingTicketCookieGenerator = ticketGrantingTicketCookieGenerator;
	}

	public CookieRetrievingCookieGenerator getWarnCookieGenerator() {
		return warnCookieGenerator;
	}

	public void setWarnCookieGenerator(
			CookieRetrievingCookieGenerator warnCookieGenerator) {
		this.warnCookieGenerator = warnCookieGenerator;
	}

	public List<ArgumentExtractor> getArgumentExtractors() {
		return argumentExtractors;
	}

	public void setArgumentExtractors(List<ArgumentExtractor> argumentExtractors) {
		this.argumentExtractors = argumentExtractors;
	}


	public DataSource getDataSource() {
		return dataSource;
	}


	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}


	public PlatformTransactionManager getTxManager() {
		return txManager;
	}


	public void setTxManager(PlatformTransactionManager txManager) {
		this.txManager = txManager;
	}  

 as-servlet.xml

<bean id="ssocontroller" class="xxx.web.SSOController" 
    	p:argumentExtractors-ref="argumentExtractors"  
        p:warnCookieGenerator-ref="warnCookieGenerator"  
	    p:centralAuthenticationService-ref="centralAuthenticationService"  
	    p:ticketGrantingTicketCookieGenerator-ref="ticketGrantingTicketCookieGenerator"
	    p:dataSource-ref="dataSource"
	    p:txManager-ref="txManager"
	    />

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值