cas 自定义登陆异常提示

时间:2024-04-09 18:17:36

自定义登录错误提示消息

CAS核心类CentralAuthenticationServiceImpl负责进行登录认证、创建TGTST、验证票据等逻辑,该类中注册了CAS认证管理器AuthenticationManager,对应bean的配置如下:

cas 自定义登陆异常提示
    <bean id="centralAuthenticationService" class="org.jasig.cas.CentralAuthenticationServiceImpl"
        p:ticketGrantingTicketExpirationPolicy-ref="grantingTicketExpirationPolicy"
        p:serviceTicketExpirationPolicy-ref="serviceTicketExpirationPolicy"
        p:authenticationManager-ref="authenticationManager"
        p:ticketGrantingTicketUniqueTicketIdGenerator-ref="ticketGrantingTicketUniqueIdGenerator"
        p:ticketRegistry-ref="ticketRegistry" p:servicesManager-ref="servicesManager"
        p:persistentIdGenerator-ref="persistentIdGenerator"
        p:uniqueTicketIdGeneratorsForService-ref="uniqueIdGeneratorsMap" />
cas 自定义登陆异常提示

CentralAuthenticationServiceImpl中的方法负责调用AuthenticationManager进行认证,并捕获AuthenticationException类型的异常,如创建ST的方法grantServiceTicket代码示例如下:

cas 自定义登陆异常提示
    if (credentials != null) {
        try {
            final Authentication authentication = this.authenticationManager
                .authenticate(credentials);
            final Authentication originalAuthentication = ticketGrantingTicket.getAuthentication();
    
            if (!(authentication.getPrincipal().equals(originalAuthentication.getPrincipal()) && authentication.getAttributes().equals(originalAuthentication.getAttributes()))) {
                throw new TicketCreationException();
            }
        } catch (final AuthenticationException e) {
            throw new TicketCreationException(e);
        }
    }
cas 自定义登陆异常提示

在CAS WEBFLOW流转的过程中,对应的action就会捕获这些TicketCreationException,并在表单中显示该异常信息。

如org.jasig.cas.web.flow.AuthenticationViaFormAction类中的表单验证方法代码如下:

cas 自定义登陆异常提示
    public final String submit(final RequestContext context, final Credentials credentials, final MessageContext messageContext) throws Exception {
        final String ticketGrantingTicketId = WebUtils.getTicketGrantingTicketId(context);
        final Service service = WebUtils.getService(context);
    
        if (StringUtils.hasText(context.getRequestParameters().get("renew")) && ticketGrantingTicketId != null && service != null) {
    
            try {
                final String serviceTicketId = this.centralAuthenticationService.grantServiceTicket(ticketGrantingTicketId, service, credentials);
                WebUtils.putServiceTicketInRequestScope(context, serviceTicketId);
                putWarnCookieIfRequestParameterPresent(context);
                return "warn";
            } catch (final TicketException e) {
                if (e.getCause() != null && AuthenticationException.class.isAssignableFrom(e.getCause().getClass())) {
                    populateErrorsInstance(e, messageContext);
                    return "error";
                }
                this.centralAuthenticationService.destroyTicketGrantingTicket(ticketGrantingTicketId);
                if (logger.isDebugEnabled()) {
                    logger.debug("Attempted to generate a ServiceTicket using renew=true with different credentials", e);
                }
            }
        }
    
        try {
            WebUtils.putTicketGrantingTicketInRequestScope(context, this.centralAuthenticationService.createTicketGrantingTicket(credentials));
            putWarnCookieIfRequestParameterPresent(context);
            return "success";
        } catch (final TicketException e) {
            populateErrorsInstance(e, messageContext);
            return "error";
        }

}
cas 自定义登陆异常提示

因此在自定义的AuthenticationHandler类的验证方法中抛出继承自AuthenticationException的异常,登录页面(默认为WEB-INF/view/jsp/default/ui/casLoginView.jsp)中的Spring Security验证表单将会自动输出该异常对应的错误消息。

CAS AuthenticationException结构如下图,CAS已经内置了一些异常,比如用户名密码错误、未知的用户名错误等。

cas 自定义登陆异常提示

假设这样一个需求:用户注册时需要验证邮箱才能登录,如果未验证邮箱,则提示用户还未验证邮箱,拒绝登录。

为实现未验证邮箱后提示用户的需求,定义一个继承自AuthenticationException的类:UnRegisterEmailAuthenticationException,代码示例如下:

cas 自定义登陆异常提示
    package test;
    
    import org.jasig.cas.authentication.handler.BadUsernameOrPasswordAuthenticationException;
    
    public class UnRegisterEmailAuthenticationException extends BadUsernameOrPasswordAuthenticationException {
        /** Static instance of UnknownUsernameAuthenticationException. */
        public static final UnRegisterEmailAuthenticationException ERROR = new UnRegisterEmailAuthenticationException();
    
        /** Unique ID for serializing. */
        private static final long serialVersionUID = 3977861752513837361L;
    
        /** The code description of this exception. */
        private static final String CODE = "error.authentication.credentials.bad.unregister.email";
    
        /**
         * Default constructor that does not allow the chaining of exceptions and
         * uses the default code as the error code for this exception.
         */
        public UnRegisterEmailAuthenticationException() {
            super(CODE);
        }
    
        /**
         * Constructor that allows for the chaining of exceptions. Defaults to the
         * default code provided for this exception.
         *
         * @param throwable the chained exception.
         */
        public UnRegisterEmailAuthenticationException(final Throwable throwable) {
            super(CODE, throwable);
        }
    
        /**
         * Constructor that allows for providing a custom error code for this class.
         * Error codes are often used to resolve exceptions into messages. Providing
         * a custom error code allows the use of a different message.
         *
         * @param code the custom code to use with this exception.
         */
        public UnRegisterEmailAuthenticationException(final String code) {
            super(code);
        }
    
        /**
         * Constructor that allows for chaining of exceptions and a custom error
         * code.
         *
         * @param code the custom error code to use in message resolving.
         * @param throwable the chained exception.
         */
        public UnRegisterEmailAuthenticationException(final String code,
            final Throwable throwable) {
            super(code, throwable);
        }
    }
cas 自定义登陆异常提示

请注意代码中的CODE私有属性,该属性定义了一个本地化资源文件中的键,通过该键获取本地化资源中对应语言的文字,这里只实现中文错误消息提示,修改WEB-INF/classes/messages_zh_CN.properties文件,添加CODE定义的键值对,如下示例:

error.authentication.credentials.bad.unregister.email=\u4f60\u8fd8\u672a\u9a8c\u8bc1\u90ae\u7bb1\uff0c\u8bf7\u5148\u9a8c\u8bc1\u90ae\u7bb1\u540e\u518d\u767b\u5f55

后面的文字是使用native2ascii工具编码转换的中文错误提示。

接下来只需要在自定义的AuthenticationHandler类的验证方法中,验证失败的地方抛出异常即可。

自定义AuthenticationHandler示例代码如下:

cas 自定义登陆异常提示
    package cn.test.web;
    
    import javax.validation.constraints.NotNull;
    
    import org.jasig.cas.adaptors.jdbc.AbstractJdbcUsernamePasswordAuthenticationHandler;
    import org.jasig.cas.authentication.handler.AuthenticationException;
    import org.jasig.cas.authentication.principal.UsernamePasswordCredentials;
    import org.springframework.dao.IncorrectResultSizeDataAccessException;
    
    public class CustomQueryDatabaseAuthenticationHandler extends AbstractJdbcUsernamePasswordAuthenticationHandler {
    
        @NotNull
        private String sql;
    
        @Override
        protected boolean authenticateUsernamePasswordInternal(UsernamePasswordCredentials credentials) throws AuthenticationException {
            final String username = getPrincipalNameTransformer().transform(credentials.getUsername());
            final String password = credentials.getPassword();
            final String encryptedPassword = this.getPasswordEncoder().encode(password);
    
            try {
    
                // 查看邮箱是否已经验证。
                Boolean isEmailValid= EmailValidation.Valid();

                if(!isEmailValid){
                    throw new UnRegisterEmailAuthenticationException();
                }
    
                //其它验证
                ……
    
            } catch (final IncorrectResultSizeDataAccessException e) {
                // this means the username was not found.
                return false;
            }
        }
    
        public void setSql(final String sql) {
            this.sql = sql;
        }
    }
cas 自定义登陆异常提示

 

三、配置使自定义登录认证生效

最后需要修改AuthenticationManager bean的配置(一般为修改WEB-INF/spring-configuration/applicationContext.xml文件),加入自定义的AuthenticationHandler,配置示例如下:

cas 自定义登陆异常提示
    <bean id="authenticationManager" class="org.jasig.cas.authentication.AuthenticationManagerImpl">
        <property name="credentialsToPrincipalResolvers">
            <list>
                <bean class="org.jasig.cas.authentication.principal.UsernamePasswordCredentialsToPrincipalResolver">
                    <property name="attributeRepository" ref="attributeRepository" />
                </bean>
                <bean class="org.jasig.cas.authentication.principal.HttpBasedServiceCredentialsToPrincipalResolver" />
            </list>
        </property>
    
        <property name="authenticationHandlers">
            <list>
                <bean class="org.jasig.cas.authentication.handler.support.HttpBasedServiceCredentialsAuthenticationHandler"
                    p:httpClient-ref="httpClient" p:requireSecure="false" />
                <bean class="cn.test.web.CustomQueryDatabaseAuthenticationHandler">
                    <property name="sql" value="select password from t_user where user_name=?" />
                    <property name="dataSource" ref="dataSource" />
                    <property name="passwordEncoder" ref="passwordEncoder"></property>
                </bean>
            </list>
        </property>
    </bean>
cas 自定义登陆异常提示
 
 
参考原文地址:
http://www.cnblogs.com/gao241/p/3367805.html