亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

JAVA - 自定義過濾器驗證失敗后如何重定向到登錄頁面?

JAVA - 自定義過濾器驗證失敗后如何重定向到登錄頁面?

智慧大石 2023-07-19 16:26:29
我必須在 Spring-security 中的驗證過程中添加一些額外的驗證。我在配置 xml 中添加了“自定義過濾器”,但是當它失敗時,會將我重定向到錯誤頁面,而不是登錄頁面。我可以毫無問題地訪問我的“authenticationFilter”類,并且當我的憑據良好并進入主頁面時,我不會遇到問題。我的 Spring 安全配置是:<http auto-config="true" use-expressions="true">    <intercept-url pattern="/admin**" access="hasRole('ADMIN')" />    <intercept-url pattern="/login" access="permitAll" />    <intercept-url pattern="/**" access="isAuthenticated()" />    <custom-filter         ref="authenticationFilter"             before="FORM_LOGIN_FILTER"    />    <!-- access denied page -->    <access-denied-handler error-page="/403" />    <form-login         login-page="/login"         default-target-url="/home"        authentication-failure-url="/login?error"         username-parameter="username"        password-parameter="password"    />    <logout logout-success-url="/login?logout" /></http>我的過濾器是:@Component("authenticationFilter")public class RequestBodyReaderAuthenticationFilter extends UsernamePasswordAuthenticationFilter {    private static final Log LOG = LogFactory.getLog(RequestBodyReaderAuthenticationFilter.class);    private static final String ERROR_MESSAGE = "Error en la validación con AD";    private final ObjectMapper objectMapper = new ObjectMapper();    public RequestBodyReaderAuthenticationFilter() {    }    @Autowired    @Qualifier("authenticationManager")    @Override    public void setAuthenticationManager(AuthenticationManager authenticationManager) {        super.setAuthenticationManager(authenticationManager);    }我需要當“自定義過濾器”驗證失敗時,它重定向到登錄頁面,而不是拋出 401/403 默認頁面。
查看完整描述

2 回答

?
慕田峪4524236

TA貢獻1875條經驗 獲得超5個贊

最后我找到了解決我的問題的方法。我重寫 RequestBodyReaderAuthenticationFilter 類的 unsuccessfulAuthentication 方法,并重定向到我的登錄錯誤頁面。

我做了很多證明,并且在所有情況下都是成功的。

現在的班級是:

   @Component("authenticationFilter")

    public class RequestBodyReaderAuthenticationFilter extends UsernamePasswordAuthenticationFilter {


        private static final Log LOG = LogFactory.getLog(RequestBodyReaderAuthenticationFilter.class);

        private static final String ERROR_MESSAGE = "Error en la validación con AD";

        private final ObjectMapper objectMapper = new ObjectMapper();

        public RequestBodyReaderAuthenticationFilter() {

        }


        @Autowired

        @Qualifier("authenticationManager")

        @Override

        public void setAuthenticationManager(AuthenticationManager authenticationManager) {

            super.setAuthenticationManager(authenticationManager);

        }


        @Override

        protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {

            LOG.error("El usuario no existe en AD");

            response.sendRedirect(request.getContextPath()+"/login?error"); //To change body of generated methods, choose Tools | Templates.

        }


        @Override

        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {

            String requestBody;

            Boolean valido = false;

            try {

                requestBody = IOUtils.toString(request.getReader());

                ArrayList<String> credenciales = new ArrayList<String>();

                //Busco el Usu y pass enviados en el request

                for (String val : requestBody.split("&")) {

                    credenciales.add(val.split("=")[1]);

                }


                try {

                    //hago el llamado el WS

                    org.tempuri.ADWS service = new org.tempuri.ADWS();

                    org.tempuri.IADWS port = service.getBasicHttpBindingIADWS();


                    valido = port.login(credenciales.get(0), credenciales.get(1));

                } catch (Exception ex) {

                    LOG.error(ERROR_MESSAGE, ex);

                }

                UsernamePasswordAuthenticationToken token;

                if (valido) {

                    //si existe en AD, realizo la validación en el sistema

                    token = new UsernamePasswordAuthenticationToken(credenciales.get(0), credenciales.get(1));

                    setDetails(request, token);

                    return this.getAuthenticationManager().authenticate(token);

                }else{

                    throw new InternalAuthenticationServiceException(ERROR_MESSAGE);                

                }

            } catch (IOException e) {

                LOG.error(ERROR_MESSAGE, e);

                throw new InternalAuthenticationServiceException(ERROR_MESSAGE, e);

            }

        }

    }


查看完整回答
反對 回復 2023-07-19
?
慕姐4208626

TA貢獻1852條經驗 獲得超7個贊

如果我理解正確,用戶可以登錄,但是在過濾器中,您正在檢查一些額外的驗證,因為用戶未獲得授權?然后你必須設置

<access-denied-handler error-page="/403" />

<access-denied-handler error-page="/login" />


查看完整回答
反對 回復 2023-07-19
  • 2 回答
  • 0 關注
  • 249 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號