---
title: "cas自定义登录异常"
author: "simplehappy"
date: "2016-03-23T11:18:41Z"
tags: []
categories: ["开源软件"]
slug: "cas"
draft: false
lastmod: "2016-03-23T12:38:22Z"
id: 2285631
url: "https://simplehappy.iteye.com/blog/2285631"
---

cas版本4.0 

定义异常类com.xxx.MyLoginException

在认证时根据实际情况抛出MyLoginException：

```
public class MyDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {
    /** {@inheritDoc} */
    @Override
    protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential) throws GeneralSecurityException, PreventedException {
        final String username = credential.getUsername();        
        try {
        	//do sth
        	if (...){
        	    throw new MyLoginException("...");
                }

        } catch (final Exception e) {
            throw new PreventedException("exception", e);
        }
        
        return createHandlerResult(credential, new SimplePrincipal(username), null);
    }
```

  替换默认的认证异常处理handler：

```
public class MyAuthenticationExceptionHandler extends AuthenticationExceptionHandler {
	
    private List<Class<? extends Exception>> errs= new ArrayList<Class<? extends Exception>>();	

	public void init() {
		errs.addAll(getErrors());
		errs.add(com.xxx.MyLoginException.class);
		setErrors(errs);
	}
}
```

 cas-servlet.xml修改 

```
  <!-- <bean id="authenticationExceptionHandler" class="org.jasig.cas.web.flow.AuthenticationExceptionHandler" /> -->
  <bean id="authenticationExceptionHandler" class="com.xxx.MyAuthenticationExceptionHandler" init-method="init" />
```

 messages\_\*.properties加入异常类对应的消息

authenticationFailure.MyLoginException=登录失败异常...

 

login-webflow.xml加入异常转向的页面处理

 

```
  <action-state id="handleAuthenticationFailure">
......
    <transition on="MyLoginException" to="generateLoginTicket"/>
......
  </action-state>
```