CAS5.3自定义登录提示信息(做个记录)

一:创建异常类继承AccountException

二:复制源码AuthenticationExceptionHandlerAction.java并修改覆盖源码

package com.wangqiang.org.apereo.cas.web.flow.actions;

import java.net.URI;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.wangqiang.cas.config.MyAccountNotFoundException;
import com.wangqiang.cas.config.MyPasswordErrorException;
import com.wangqiang.cas.config.MyUserNameRepeatException;
import lombok.Generated;
import org.apereo.cas.authentication.AuthenticationException;
import org.apereo.cas.services.UnauthorizedServiceForPrincipalException;
import org.apereo.cas.ticket.AbstractTicketException;
import org.apereo.cas.web.support.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.binding.message.MessageBuilder;
import org.springframework.binding.message.MessageContext;
import org.springframework.webflow.action.AbstractAction;
import org.springframework.webflow.action.EventFactorySupport;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

/**
 * @author: 王强
 * @create: 2023-04-12 15:44
 **/
public class AuthenticationExceptionHandlerAction extends AbstractAction{

    @Generated
    private static final Logger LOGGER = LoggerFactory.getLogger(AuthenticationExceptionHandlerAction.class);
    private static final String DEFAULT_MESSAGE_BUNDLE_PREFIX = "authenticationFailure.";
    private static final String UNKNOWN = "UNKNOWN";
    private final Set<Class<? extends Throwable>> errors;
    private String messageBundlePrefix;

    public AuthenticationExceptionHandlerAction() {
        this(new LinkedHashSet());
    }

    public AuthenticationExceptionHandlerAction(final Set<Class<? extends Throwable>> errors) {
        this.messageBundlePrefix = "authenticationFailure.";
        this.errors = errors;
    }

    public Set<Class<? extends Throwable>> getErrors() {
        return new LinkedHashSet(this.errors);
    }

    public String handle(final Exception e, final RequestContext requestContext) {
        MessageContext messageContext = requestContext.getMessageContext();
        if (e instanceof AuthenticationException) {
            return this.handleAuthenticationException((AuthenticationException)e, requestContext);
        } else if (e instanceof AbstractTicketException) {
            return this.handleAbstractTicketException((AbstractTicketException)e, requestContext);
        } else {
            LOGGER.trace("Unable to translate errors of the authentication exception [{}]. Returning [{}]", e, "UNKNOWN");
            String messageCode = this.messageBundlePrefix + "UNKNOWN";
            messageContext.addMessage((new MessageBuilder()).error().code(messageCode).build());
            return "UNKNOWN";
        }
    }

    protected String handleAuthenticationException(final AuthenticationException e, final RequestContext requestContext) {
        if (e.getHandlerErrors().containsKey(UnauthorizedServiceForPrincipalException.class.getSimpleName())) {
            URI url = WebUtils.getUnauthorizedRedirectUrlIntoFlowScope(requestContext);
            if (url != null) {
                LOGGER.warn("Unauthorized service access for principal; CAS will be redirecting to [{}]", url);
                return "serviceUnauthorizedCheck";
            }
        }

        Collection<Class> values = (Collection) e.getHandlerErrors().values().stream().map(Object::getClass).collect(Collectors.toList());
        Objects.requireNonNull(values);
        ArrayList<Class> tempList = new ArrayList(values);
        Class myException = null;
        for (Class clazz : tempList) {
            // 自定义登录异常类,必须以My开头
            if (clazz.getSimpleName().contains("My")) {
                myException = clazz;
                break;
            }
        }
        if (myException == null) {
            myException = tempList.get(0);
        }
        String handlerErrorName = myException.getSimpleName();
        MessageContext messageContext = requestContext.getMessageContext();
        String messageCode = this.messageBundlePrefix + handlerErrorName;

        // 获取自定义异常携带的自定义提示信息并通过.defaultText(customerExceptionMsg)向下传递
        // 这里只处理自定义抛出的异常
        String customerExceptionMsg = "认证信息无效。";
        boolean b = false;
        if (handlerErrorName.equals("MyAccountNotFoundException")) {
            List<Throwable> list = e.getHandlerErrors().values().stream()
                    .filter(O -> O.getClass().getSimpleName().equals("MyAccountNotFoundException"))
                    .collect(Collectors.toList());
            MyAccountNotFoundException myAccountLockedException = (MyAccountNotFoundException) list.get(0);
            customerExceptionMsg = myAccountLockedException.getMessage();
        } else if (handlerErrorName.equals("MyPasswordErrorException")) {
            List<Throwable> list = e.getHandlerErrors().values().stream()
                    .filter(O -> O.getClass().getSimpleName().equals("MyPasswordErrorException"))
                    .collect(Collectors.toList());
            MyPasswordErrorException myPasswordErrorException = (MyPasswordErrorException) list.get(0);
            customerExceptionMsg = myPasswordErrorException.getMessage();
        } else if (handlerErrorName.equals("MyUserNameRepeatException")) {
            List<Throwable> list = e.getHandlerErrors().values().stream()
                    .filter(O -> O.getClass().getSimpleName().equals("MyUserNameRepeatException"))
                    .collect(Collectors.toList());
            MyUserNameRepeatException myUserNameRepeatException = (MyUserNameRepeatException) list.get(0);
            customerExceptionMsg = myUserNameRepeatException.getMessage();
        }

        // 如果抛出自定义登录异常时未配置message,getMessage()时customerExceptionMsg="No supported authentication handlers found for given credentials"
        // 这里置为空字符串,才能在界面展示国际化文件配置的固定提示信息
        if ("No supported authentication handlers found for given credentials".equals(customerExceptionMsg)) {
            customerExceptionMsg = "";
        }
        messageContext.addMessage((new MessageBuilder()).error().defaultText(customerExceptionMsg).code(messageCode).build());
        return handlerErrorName;
    }

    protected String handleAbstractTicketException(final AbstractTicketException e, final RequestContext requestContext) {
        MessageContext messageContext = requestContext.getMessageContext();
        Optional<String> match = this.errors.stream().filter((c) -> {
            return c.isInstance(e);
        }).map(Class::getSimpleName).findFirst();
        match.ifPresent((s) -> {
            messageContext.addMessage((new MessageBuilder()).error().code(e.getCode()).build());
        });
        return (String)match.orElse("UNKNOWN");
    }

    protected Event doExecute(final RequestContext requestContext) {
        Event currentEvent = requestContext.getCurrentEvent();
        LOGGER.debug("Located current event [{}]", currentEvent);
        Exception error = (Exception)currentEvent.getAttributes().get("error", Exception.class);
        if (error != null) {
            LOGGER.debug("Located error attribute [{}] with message [{}] from the current event", error.getClass(), error.getMessage());
            String event = this.handle(error, requestContext);
            LOGGER.debug("Final event id resolved from the error is [{}]", event);
            return (new EventFactorySupport()).event(this, event, currentEvent.getAttributes());
        } else {
            return (new EventFactorySupport()).event(this, "error");
        }
    }
}

 三:在messages_zh_CN.properties这个文件中加入你添加的异常

#Welcome Screen Messages

screen.welcome.welcome=\u6B22\u8FCE\u6765\u5230\u4E2D\u592E\u8BA4\u8BC1\u7CFB\u7EDF\u3002\u9ED8\u8BA4\u7684\u8BA4\u8BC1\u5904\u7406\u5668\u652F\u6301\u90A3\u4E9B\u7528\u6237\u540D\u7B49\u4E8E\u5BC6\u7801\u7684\u8D26\u53F7\uFF0C\u5F00\u53D1\u8005\u53EF\u4EE5\u8BD5\u8BD5\u770B\u3002
screen.welcome.security=\u51FA\u4E8E\u5B89\u5168\u8003\u8651\uFF0C\u4E00\u65E6\u60A8\u8BBF\u95EE\u8FC7\u90A3\u4E9B\u9700\u8981\u60A8\u63D0\u4F9B\u51ED\u8BC1\u4FE1\u606F\u7684\u5E94\u7528\u65F6\uFF0C\u8BF7\u64CD\u4F5C\u5B8C\u6210\u4E4B\u540E<a href="logout">\u767B\u51FA</a>\u5E76\u5173\u95ED\u6D4F\u89C8\u5668\u3002
screen.welcome.instructions=\u8BF7\u8F93\u5165\u60A8\u7684\u7528\u6237\u540D\u548C\u5BC6\u7801.
screen.welcome.label.netid=\u7528\u6237\u540D:
screen.welcome.label.netid.accesskey=n
screen.welcome.label.password=\u5BC6\u3000\u7801:
screen.welcome.label.password.accesskey=p
screen.welcome.label.warn=\u8F6C\u5411\u5176\u4ED6\u7AD9\u70B9\u524D\u63D0\u793A\u6211\u3002
screen.welcome.label.warn.accesskey=w
screen.welcome.button.login=\u767B\u5F55
screen.welcome.button.clear=\u91CD\u7F6E

logo.title=\u8F6C\u5230Apereo\u7F51\u7AD9\u9996\u9875
copyright=\u7248\u6743\u6240\u6709 &copy; 2005&ndash;2012 Apereo, Inc. \u4FDD\u7559\u5168\u90E8\u6743\u5229\u3002

# Blocked Errors Page
screen.blocked.header=\u8BBF\u95EE\u88AB\u62D2\u7EDD
screen.blocked.message=\u8F93\u9519\u5BC6\u7801\u6B21\u6570\u592A\u591A\uFF0C\u8D26\u53F7\u88AB\u9501\u5B9A\u3002

#Confirmation Screen Messages
screen.confirmation.message=\u5355\u51FB <a href="{0}">\u8FD9\u91CC</a> \uFF0C\u4FBF\u80FD\u591F\u8BBF\u95EE\u5230\u76EE\u6807\u5E94\u7528\u3002

#Generic Success Screen Messages
screen.success.header=\u767B\u5F55\u6210\u529F
screen.success.success=\u60A8\u5DF2\u7ECF\u6210\u529F\u767B\u5F55\u4E2D\u592E\u8BA4\u8BC1\u7CFB\u7EDF\u3002
screen.success.security=\u51FA\u4E8E\u5B89\u5168\u8003\u8651\uFF0C\u4E00\u65E6\u60A8\u8BBF\u95EE\u8FC7\u90A3\u4E9B\u9700\u8981\u60A8\u63D0\u4F9B\u51ED\u8BC1\u4FE1\u606F\u7684\u5E94\u7528\u65F6\uFF0C\u8BF7\u64CD\u4F5C\u5B8C\u6210\u4E4B\u540E<a href="logout">\u767B\u51FA</a>\u5E76\u5173\u95ED\u6D4F\u89C8\u5668\u3002

#Logout Screen Messages
screen.logout.header=\u6CE8\u9500\u6210\u529F
screen.logout.success=\u60A8\u5DF2\u7ECF\u6210\u529F\u9000\u51FACAS\u7CFB\u7EDF\uFF0C\u8C22\u8C22\u4F7F\u7528\uFF01
screen.logout.security=\u51FA\u4E8E\u5B89\u5168\u8003\u8651\uFF0C\u8BF7\u5173\u95ED\u60A8\u7684\u6D4F\u89C8\u5668\u3002


screen.service.sso.error.header=\u5728\u8BBF\u95EE\u5230\u5230\u76EE\u6807\u670D\u52A1\u524D\uFF0C\u4F60\u5FC5\u987B\u7ECF\u8FC7\u91CD\u65B0\u8BA4\u8BC1\u7684\u8003\u9A8C
screen.service.sso.error.message=\u4F60\u6B63\u8BD5\u56FE\u8BBF\u95EE\u8981\u6C42\u91CD\u65B0\u8BA4\u8BC1\u7684\u670D\u52A1\u3002\u8BF7\u5C1D\u8BD5\u8FDB\u884C<a href="{0}">\u518D\u6B21\u8BA4\u8BC1</a>\u3002


username.required=\u7528\u6237\u540D\u5FC5\u586B\u3002
password.required=\u5BC6\u7801\u5FC5\u586B\u3002
capcha.required=\u9A8C\u8BC1\u7801\u5FC5\u586B\u3002

# Authentication failure messages
authenticationFailure.AccountDisabledException=\u8FD9\u4E2A\u8D26\u6237\u88AB\u7981\u7528\u4E86\u3002
authenticationFailure.AccountLockedException=\u8FD9\u4E2A\u8D26\u6237\u88AB\u4E0A\u9501\u4E86\u3002
authenticationFailure.CredentialExpiredException=\u4F60\u7684\u5BC6\u7801\u8FC7\u671F\u4E86\u3002
authenticationFailure.InvalidLoginLocationException=\u4F60\u4E0D\u80FD\u4ECE\u8FD9\u4E2A\u5DE5\u4F5C\u7AD9\u767B\u5F55\u3002
authenticationFailure.InvalidLoginTimeException=\u4F60\u7684\u8D26\u6237\u73B0\u5728\u88AB\u7981\u6B62\u767B\u5F55\u4E86\u3002
authenticationFailure.AccountNotFoundException=\u8BA4\u8BC1\u4FE1\u606F\u65E0\u6548\u3002
authenticationFailure.FailedLoginException=\u8BA4\u8BC1\u4FE1\u606F\u65E0\u6548\u3002
authenticationFailure.UNKNOWN=\u8BA4\u8BC1\u4FE1\u606F\u65E0\u6548\u3002

INVALID_REQUEST_PROXY=\u5FC5\u987B\u540C\u65F6\u63D0\u4F9B'pgt'\u548C'targetService'\u53C2\u6570
INVALID_TICKET_SPEC=\u6821\u9A8C\u7968\u6839\u5931\u8D25\u3002\u60A8\u53EF\u80FD\u91C7\u7528\u670D\u52A1\u7968\u6839\u6765\u6821\u9A8C\u4EE3\u7406\u7968\u6839\uFF0C\u6216\u6CA1\u6709\u5C06renew\u8BBE\u4E3Atrue\u3002
INVALID_REQUEST=\u5FC5\u987B\u540C\u65F6\u63D0\u4F9B'service'\u548C'ticket'\u53C2\u6570
INVALID_TICKET=\u672A\u80FD\u591F\u8BC6\u522B\u51FA\u76EE\u6807 ''{0}''\u7968\u6839
INVALID_SERVICE=\u7968\u6839''{0}''\u4E0D\u7B26\u5408\u76EE\u6807\u670D\u52A1
INVALID_PROXY_CALLBACK=\u6240\u63D0\u4F9B\u7684\u4EE3\u7406\u56DE\u8C03\u7F51\u5740''{0}''\u4E0D\u80FD\u63D0\u4F9B\u8BA4\u8BC1\u3002
UNAUTHORIZED_SERVICE_PROXY=\u6240\u63D0\u4F9B\u7684\u670D\u52A1''{0}''\u6CA1\u6709\u6743\u9650\u4F7F\u7528CAS\u4EE3\u7406\u7684\u8BA4\u8BC1\u65B9\u5F0F\u3002

screen.service.error.header=\u672A\u8BA4\u8BC1\u6388\u6743\u7684\u670D\u52A1
screen.service.error.message=\u4E0D\u5141\u8BB8\u4F7F\u7528CAS\u6765\u8BA4\u8BC1\u60A8\u8BBF\u95EE\u7684\u76EE\u6807\u5E94\u7528\u3002
screen.service.empty.error.message=CAS\u7684\u670D\u52A1\u8BB0\u5F55\u662F\u7A7A\u7684\uFF0C\u6CA1\u6709\u5B9A\u4E49\u670D\u52A1\u3002 \
\u5E0C\u671B\u901A\u8FC7CAS\u8FDB\u884C\u8BA4\u8BC1\u7684\u5E94\u7528\u7A0B\u5E8F\u5FC5\u987B\u5728\u670D\u52A1\u8BB0\u5F55\u4E2D\u660E\u786E\u5B9A\u4E49\u3002

# Password policy
password.expiration.warning=\u4F60\u7684\u5BC6\u7801\u4F1A\u5728{0}\u5929\u5185\u8FC7\u671F\u3002\u8BF7\u7ACB\u523B<a href="{1}">\u4FEE\u6539\u4F60\u7684\u5BC6\u7801</a>\u3002
password.expiration.loginsRemaining=\u5728<strong>\u5FC5\u987B</strong>\u4FEE\u6539\u5BC6\u7801\u4E4B\u524D\uFF0C\u4F60\u8FD8\u5269{0}\u6B21\u767B\u5F55\u3002
screen.accountdisabled.heading=\u8FD9\u4E2A\u8D26\u6237\u5DF2\u7ECF\u88AB\u7981\u7528\u4E86\u3002
screen.accountdisabled.message=\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\u6765\u91CD\u65B0\u83B7\u5F97\u8BBF\u95EE\u6743\u9650\u3002
screen.accountlocked.heading=\u8FD9\u4E2A\u8D26\u6237\u5DF2\u7ECF\u88AB\u9501\u4F4F\u4E86\u3002
screen.accountlocked.message=\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\u6765\u91CD\u65B0\u83B7\u5F97\u8BBF\u95EE\u6743\u9650\u3002
screen.expiredpass.heading=\u4F60\u7684\u5BC6\u7801\u5DF2\u7ECF\u8FC7\u671F\u4E86\u3002
screen.expiredpass.message=\u8BF7<a href="{0}">\u4FEE\u6539\u4F60\u7684\u5BC6\u7801</a>\u3002
screen.mustchangepass.heading=\u4F60\u5FC5\u987B\u4FEE\u6539\u4F60\u7684\u5BC6\u7801\u3002
screen.mustchangepass.message=\u8BF7<a href="{0}">\u4FEE\u6539\u4F60\u7684\u5BC6\u7801</a>\u3002
screen.badhours.heading=\u73B0\u5728\u4F60\u7684\u8D26\u6237\u88AB\u7981\u6B62\u767B\u5F55\u4E86\u3002
screen.badhours.message=\u8BF7\u7A0D\u540E\u518D\u8BD5\u3002
screen.badworkstation.heading=\u4F60\u4E0D\u80FD\u4ECE\u8FD9\u4E2A\u5DE5\u4F5C\u7AD9\u767B\u5F55\u3002
screen.badworkstation.message=\u8BF7\u8054\u7CFB\u7CFB\u7EDF\u7BA1\u7406\u5458\u6765\u91CD\u65B0\u83B7\u5F97\u8BBF\u95EE\u6743\u9650\u3002

# OAuth
screen.oauth.confirm.header=\u6388\u6743
screen.oauth.confirm.message=\u8981\u6388\u6743"{0}"\u8BBF\u95EE\u4F60\u5168\u90E8\u4E2A\u4EBA\u4FE1\u606F\u5417\uFF1F
screen.oauth.confirm.allow=\u5141\u8BB8

# Unavailable
screen.unavailable.heading=CAS\u65E0\u6CD5\u4F7F\u7528
screen.unavailable.message=\u5728\u8BD5\u56FE\u5B8C\u6210\u4F60\u7684\u8BF7\u6C42\u65F6\u51FA\u9519\u3002\u8BF7\u901A\u77E5\u4F60\u7684\u6280\u672F\u652F\u6301\u6216\u91CD\u8BD5\u3002

#自己添加的异常
#用户没找到异常
authenticationFailure.MyAccountNotFoundException=\u7528\u6237\u4e0d\u5b58\u5728
#密码错误异常
authenticationFailure.MyPasswordErrorException=\u5bc6\u7801\u9519\u8bef
#用户名重复异常
authenticationFailure.MyUserNameRepeatException=\u7528\u6237\u540d\u91cd\u590d\uff0c\u8bf7\u4f7f\u7528\u624b\u673a\u53f7\u767b\u5f55

 四:在application.properties配置文件中引入你自定义的异常提示类

五:在你的自定义登录验证类中根据情况使用自定义异常提示类

 

参考

https://blog.csdn.net/qq_43542296/article/details/128933103

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值