CAS生成TGT

声明:基于cas4.0改造

1.需求

基于cas做扫码登陆、短信登陆等特殊场景时,用户无需输入账号密码进行登陆操作。

2.改造

2.1.增加生成tgt接口类核心代码如下

// 登陆用户对象
UsernamePasswordCaptchaCredential credential = new UsernamePasswordCaptchaCredential();
credential.setUsername(usernameKey);
// 不验证密码
credential.setSign(1);
// 验证用户信息
Authentication authentication = this.authenticationManager.authenticate(credential);
// 生成tgt
tgt = this.ticketGrantingTicketUniqueIdGenerator.getNewTicketId(TicketGrantingTicket.PREFIX);
TicketGrantingTicket ticketGrantingTicket = new TicketGrantingTicketImpl(tgt, authentication, this.grantingTicketExpirationPolicy);
// 将tgt注册进cas
this.ticketRegistry.addTicket(ticketGrantingTicket);

UsernamePasswordCaptchaCredential 为继承UsernamePasswordCredential扩增了sign用来标示是否需要验证密码

2.2.修改cas-servlet.xml


注入p:ticketGrantingTicketUniqueIdGenerator-ref="ticketGrantingTicketUniqueIdGenerator"
        p:ticketRegistry-ref="ticketRegistry"
        p:grantingTicketExpirationPolicy-ref="grantingTicketExpirationPolicy"
        p:authenticationManager-ref="authenticationManager"

2.3.重写验证流程AbstractJdbcUsernamePasswordAuthenticationHandler

// 等于1忽略验证密码
if(sign != 1){
    // 获取密码 根据配置加密明文密码
	String encryptedPassword = this.getPasswordEncoder().encode(credential.getPassword());
	if (!dbPassword.equals(encryptedPassword)) {
	    throw new FailedLoginException("Password does not match value on record.");
	}
}

此时获取的tgt就能直接存入cookie中使用

3.验证

3.1.生成tgt

CAS生成TGT_第1张图片

3.2.将tgt存入cookie验证

CAS生成TGT_第2张图片

你可能感兴趣的:(cas,单点登陆)