天天看點

Spring Boot 整合 Security 權限控制-6:自定義failureHandler

在 java 源碼目錄下建立hander檔案夾, 在該檔案夾下建立CustomAuthenticationFailHander類檔案

/**
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.edurt.hander;
 
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.WebAttributes;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
 
/**
 * CustomAuthenticationFailHander <br/>
 * 描述 : CustomAuthenticationFailHander <br/>
 * 作者 : qianmoQ <br/>
 * 版本 : 1.0 <br/>
 * 建立時間 : 2018-03-20 下午4:08 <br/>
 * 聯系作者 : <a href="mailTo:[email protected]">qianmoQ</a>
 */
@Component(value = "customAuthenticationFailHander")
public class CustomAuthenticationFailHander extends SimpleUrlAuthenticationFailureHandler {
 
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        System.out.println("登入失敗!!!");
        this.returnJson(response, exception);
    }
 
    /**
     * 直接傳回需要傳回的 json 資料
     */
    private void returnJson(HttpServletResponse response,
                            AuthenticationException exception) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println("{\"ok\":0,\"msg\":\"" + exception.getLocalizedMessage() + "\"}");
    }
 
    /**
     * 直接返會錯誤頁面
     */
    private void returnErrorPage(HttpServletRequest request, HttpServletResponse response,
                                 AuthenticationException exception) throws IOException, ServletException {
        String strUrl = request.getContextPath() + "/loginErrorPath";
        request.getSession().setAttribute("status", 0);
        request.getSession().setAttribute("message", exception.getLocalizedMessage());
        request.getSession().setAttribute(WebAttributes.AUTHENTICATION_EXCEPTION, exception);
        // 使用該方法會出現錯誤
//        request.getRequestDispatcher(strUrl).forward(request, response);
        response.sendRedirect(strUrl);
    }
 
}
複制代碼           

修改WebSecurityConfig配置檔案支援自定義Handler

@Autowired
private CustomAuthenticationFailHander customAuthenticationFailHander;
 
 
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            // 允許直接通路/路徑
            .authorizeRequests().antMatchers("/").permitAll()
            // 使其支援跨域
            .requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
            // 其他路徑需要授權通路
            .anyRequest().authenticated()
            // 指定登入頁面
            .and().formLogin().loginPage("/user/login")
            // 指定登入失敗跳轉位址, 使用自定義錯誤資訊
            .failureHandler(customAuthenticationFailHander)
            // 登入成功後的預設路徑
            .defaultSuccessUrl("/").permitAll()
            // 登出後的預設路徑
            .and().logout().logoutSuccessUrl("/user/login").permitAll();
}           

作者:EdurtIO

連結:https://juejin.cn/post/7164934051236118559

來源:稀土掘金

著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請注明出處。

繼續閱讀