亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

解決Spring Security中AuthenticationEntryPoint不生效相關(guān)問題

 更新時間:2021年12月20日 09:43:23   作者:沖鴨hhh  
這篇文章主要介紹了解決Spring Security中AuthenticationEntryPoint不生效相關(guān)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

之前由于項目需要比較詳細(xì)地學(xué)習(xí)了Spring Security的相關(guān)知識,并打算實現(xiàn)一個較為通用的權(quán)限管理模塊。由于項目是前后端分離的,所以當(dāng)認(rèn)證或授權(quán)失敗后不應(yīng)該使用formLogin()的重定向,而是返回一個json形式的對象來提示沒有授權(quán)或認(rèn)證。 ??

這時,我們可以使用AuthenticationEntryPoint對認(rèn)證失敗異常提供處理入口,而通過AccessDeniedHandler對用戶無授權(quán)異常提供處理入口

在這里我的代碼如下

/**
 * 對已認(rèn)證用戶無權(quán)限的處理
 */
@Component
public class JsonAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
		// 提示無權(quán)限        
        httpServletResponse.getWriter().print(JSONObject.toJSONString(new BaseResult<String>(NO_PERMISSION, false, null)));
    }
}
/**
 * 對匿名用戶無權(quán)限的處理
 */
@Component
public class JsonAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
		// 認(rèn)證失敗        
        httpServletResponse.getWriter().print(JSONObject.toJSONString(new BaseResult<String>(e.getMessage(), false, null)));
    }
}

在這樣的設(shè)置下,如果認(rèn)證失敗的話會提示具體認(rèn)證失敗的原因;而用戶進(jìn)行無權(quán)限訪問的時候會返回?zé)o權(quán)限的提示。 ??

用不存在的用戶名密碼登錄后會出現(xiàn)以下返回數(shù)據(jù)

在這里插入圖片描述

與我所設(shè)置的認(rèn)證異常返回值不一致。

在繼續(xù)講解前,我先簡單說下我當(dāng)前的Spring Security配置,我是將不同的登錄方式整合在一起,并模仿Spring Security中的UsernamePasswordAuthenticationFilter實現(xiàn)了不同登錄方式的過濾器。 ??

設(shè)想通過郵件、短信、驗證碼和微信等登錄方式登錄(這里暫時只實現(xiàn)了驗證碼登錄的模板)。

在這里插入圖片描述 ??

以下是配置信息

/**
 * @Author chongyahhh
 * 驗證碼登錄配置
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class VerificationLoginConfig extends SecurityConfigurerAdapter<DefaultSecurityFilterChain, HttpSecurity> {
    private final VerificationAuthenticationProvider verificationAuthenticationProvider;
    @Qualifier("tokenAuthenticationDetailsSource")
    private AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> authenticationDetailsSource;
    @Override
    public void configure(HttpSecurity http) throws Exception {
        VerificationAuthenticationFilter verificationAuthenticationFilter = new VerificationAuthenticationFilter();
        verificationAuthenticationFilter.setAuthenticationManager(http.getSharedObject((AuthenticationManager.class)));
        http
                .authenticationProvider(verificationAuthenticationProvider)
                .addFilterAfter(verificationAuthenticationFilter, UsernamePasswordAuthenticationFilter.class); // 將VerificationAuthenticationFilter加到UsernamePasswordAuthenticationFilter后面
    }
}
/**
 * @Author chongyahhh
 * Spring Security 配置
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    private final AuthenticationEntryPoint jsonAuthenticationEntryPoint;
    private final AccessDeniedHandler jsonAccessDeniedHandler;
    private final VerificationLoginConfig verificationLoginConfig;
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                    .apply(verificationLoginConfig) // 用戶名密碼驗證碼登錄配置導(dǎo)入
                .and()
                    .exceptionHandling()
                    .authenticationEntryPoint(jsonAuthenticationEntryPoint) // 注冊自定義認(rèn)證異常入口
                    .accessDeniedHandler(jsonAccessDeniedHandler) // 注冊自定義授權(quán)異常入口
                .and()
                    .anonymous()
                .and()
                    .formLogin()
                .and()
                    .csrf().disable(); // 關(guān)閉 csrf,防止首次的 POST 請求被攔截
    }
    @Bean("customSecurityExpressionHandler")
    public DefaultWebSecurityExpressionHandler webSecurityExpressionHandler(){
        DefaultWebSecurityExpressionHandler handler = new DefaultWebSecurityExpressionHandler();
        handler.setPermissionEvaluator(new CustomPermissionEvaluator());
        return handler;
    }
}

以下是實現(xiàn)的驗證碼登錄過濾器

模仿UsernamePasswordAuthenticationFilter繼承AbstractAuthenticationProcessingFilter實現(xiàn)。

/**
 * @Author chongyahhh
 * 驗證碼登錄過濾器
 */
public class VerificationAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String VERIFICATION_CODE = "verificationCode";
    private boolean postOnly = true;
    public VerificationAuthenticationFilter() {
        super(new AntPathRequestMatcher(SECURITY_VERIFICATION_CODE_LOGIN, "POST"));
        // 繼續(xù)執(zhí)行攔截器鏈,執(zhí)行被攔截的 url 對應(yīng)的接口
        super.setContinueChainBeforeSuccessfulAuthentication(true);
    }
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (this.postOnly && !request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String verificationCode = this.obtainVerificationCode(request);
        System.out.println("驗證中...");
        String username = this.obtainUsername(request);
        String password = this.obtainPassword(request);
        username = (username == null) ? "" : username;
        password = (password == null) ? "" : password;
        username = username.trim();
        VerificationAuthenticationToken authRequest = new VerificationAuthenticationToken(username, password);
        //this.setDetails(request, authRequest);
        return this.getAuthenticationManager().authenticate(authRequest);
    }
    private String obtainPassword(HttpServletRequest request) {
        return request.getParameter(PASSWORD);
    }
    private String obtainUsername(HttpServletRequest request) {
        return request.getParameter(USERNAME);
    }
    private String obtainVerificationCode(HttpServletRequest request) {
        return request.getParameter(VERIFICATION_CODE);
    }
    private void setDetails(HttpServletRequest request, VerificationAuthenticationToken authRequest) {
        authRequest.setDetails(this.authenticationDetailsSource.buildDetails(request));
    }
    private boolean validate(String verificationCode) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        Object validateCode = session.getAttribute(VERIFICATION_CODE);
        if(validateCode == null) {
            return false;
        }
        // 不分區(qū)大小寫
        return StringUtils.equalsIgnoreCase((String)validateCode, verificationCode);
    }
}

其它的設(shè)置與本問題無關(guān),就先不放出來了。 ??

首先我們要知道,AuthenticationEntryPoint和AccessDeniedHandler是過濾器ExceptionTranslationFilter中的一部分,當(dāng)ExceptionTranslationFilter捕獲到之后過濾器的執(zhí)行異常后,會調(diào)用AuthenticationEntryPoint和AccessDeniedHandler中的對應(yīng)方法來進(jìn)行異常處理。

以下是對應(yīng)的源碼

private void handleSpringSecurityException(HttpServletRequest request,
			HttpServletResponse response, FilterChain chain, RuntimeException exception)
			throws IOException, ServletException {
		if (exception instanceof AuthenticationException) { // 認(rèn)證異常
			...
			sendStartAuthentication(request, response, chain,
					(AuthenticationException) exception); // 在這里調(diào)用 AuthenticationEntryPoint 的 commence 方法
		} else if (exception instanceof AccessDeniedException) { // 無權(quán)限
			Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
			if (authenticationTrustResolver.isAnonymous(authentication) || authenticationTrustResolver.isRememberMe(authentication)) {
				...
				sendStartAuthentication(
						request,
						response,
						chain,
						new InsufficientAuthenticationException(
							messages.getMessage(
								"ExceptionTranslationFilter.insufficientAuthentication",
								"Full authentication is required to access this resource"))); // 在這里調(diào)用 AuthenticationEntryPoint 的 commence 方法
			} else {
				...
				accessDeniedHandler.handle(request, response,
						(AccessDeniedException) exception); // 在這里調(diào)用 AccessDeniedHandler 的 handle 方法
			}
		}
	}

在ExceptionTranslationFilter抓到之后的攔截器拋出的異常后就進(jìn)行以上判斷:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		try {
			chain.doFilter(request, response);
			logger.debug("Chain processed normally");
		}
		catch (IOException ex) {
			throw ex;
		}
		catch (Exception ex) {
			// Try to extract a SpringSecurityException from the stacktrace
			Throwable[] causeChain = throwableAnalyzer.determineCauseChain(ex);
			RuntimeException ase = (AuthenticationException) throwableAnalyzer
					.getFirstThrowableOfType(AuthenticationException.class, causeChain);
			if (ase == null) {
				ase = (AccessDeniedException) throwableAnalyzer.getFirstThrowableOfType(
						AccessDeniedException.class, causeChain);
			}
			if (ase != null) {
				if (response.isCommitted()) {
					throw new ServletException("Unable to handle the Spring Security Exception because the response is already committed.", ex);
				}
				// 這里進(jìn)入上面的方法?。?!
				handleSpringSecurityException(request, response, chain, ase);
			}
			else {
				// Rethrow ServletExceptions and RuntimeExceptions as-is
				if (ex instanceof ServletException) {
					throw (ServletException) ex;
				}
				else if (ex instanceof RuntimeException) {
					throw (RuntimeException) ex;
				}
				// Wrap other Exceptions. This shouldn't actually happen
				// as we've already covered all the possibilities for doFilter
				throw new RuntimeException(ex);
			}
		}
	}

?

綜上,我們考慮攔截器鏈沒有到達(dá)ExceptionTranslationFilter便拋出異常并結(jié)束處理;或是經(jīng)過了ExceptionTranslationFilter,但之后的異常沒被其抓取便處理結(jié)束。 ??

我們首先看一下當(dāng)前Security的攔截器鏈

在這里插入圖片描述

??

很明顯可以發(fā)現(xiàn),我們自定義的過濾器在ExceptionTranslationFilter之前,所以在拋出異常后,應(yīng)該會處理后直接終止執(zhí)行鏈。 ??

由于篇幅原因,這里不具體給出debug過程,直接給出結(jié)果。 ??

我們查看VerificationAuthenticationFilter繼承的AbstractAuthenticationProcessingFilter中的doFilter方法:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
     	// 在此處進(jìn)行 url 匹配,如果不是該攔截器攔截的 url,就直接執(zhí)行下一個攔截器的攔截
		if (!requiresAuthentication(request, response)) {
			chain.doFilter(request, response);
			return;
		}
		if (logger.isDebugEnabled()) {
			logger.debug("Request is to process authentication");
		}
		Authentication authResult;
		try {
			// 調(diào)用我們實現(xiàn)的 VerificationAuthenticationFilter 中的 attemptAuthentication 方法,進(jìn)行登錄邏輯驗證
			authResult = attemptAuthentication(request, response);
			if (authResult == null) {
				return;
			}
			sessionStrategy.onAuthentication(authResult, request, response);
		} catch (InternalAuthenticationServiceException failed) {
			logger.error(
					"An internal error occurred while trying to authenticate the user.",
					failed);
			unsuccessfulAuthentication(request, response, failed);
			return;
		} catch (AuthenticationException failed) {
			//
			// 注意這里,如果登錄失敗,我們拋出的異常會在這里被抓取,然后通過 unsuccessfulAuthentication 進(jìn)行處理
			// 翻閱 unsuccessfulAuthentication 中的代碼我們可以發(fā)現(xiàn),如果我們沒有設(shè)置認(rèn)證失敗后的重定向url,就會封裝一個401的響應(yīng),也就是我們上面出現(xiàn)的情況
			// 
			unsuccessfulAuthentication(request, response, failed);
			// 執(zhí)行完成后直接中斷攔截器鏈的執(zhí)行
			return;
		}
		// 如果登錄成功就繼續(xù)執(zhí)行,我們設(shè)置的 continueChainBeforeSuccessfulAuthentication 為 true
		if (continueChainBeforeSuccessfulAuthentication) {
			chain.doFilter(request, response);
		}
		successfulAuthentication(request, response, chain, authResult);
	}

通過這段代碼的分析,原因就一目了然了,如果我們繼承AbstractAuthenticationProcessingFilter來實現(xiàn)我們的登錄驗證邏輯,無論該過濾器在ExceptionTranslationFilter的前面或后面,都無法順利觸發(fā)ExceptionTranslationFilter中的異常處理邏輯,因為AbstractAuthenticationProcessingFilter會對認(rèn)證異常進(jìn)行自我消化并中斷攔截器鏈的進(jìn)行,所以我們只能通過其他的Filter來封裝我們的登錄邏輯攔截器,如:GenericFilterBean。 ??

為了保證攔截器鏈能順利到達(dá)ExceptionTranslationFilter

我們需要滿足兩個條件: ????

1、自定義的認(rèn)證過濾器不能通過繼承AbstractAuthenticationProcessingFilter實現(xiàn); ????

2、自定義的認(rèn)證過濾器應(yīng)在ExceptionTranslationFilter后面:

在這里插入圖片描述 ??

此外,我們也可以通過實現(xiàn)AuthenticationFailureHandler的方式來處理認(rèn)證異常。

public class JsonAuthenticationFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().print(JSONObject.toJSONString(new BaseResult<String>(exception.getMessage(), false, null)));
    }
}
public class VerificationAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private static final String USERNAME = "username";
    private static final String PASSWORD = "password";
    private static final String VERIFICATION_CODE = "verificationCode";
    private boolean postOnly = true;
    public VerificationAuthenticationFilter() {
        super(new AntPathRequestMatcher(SECURITY_VERIFICATION_CODE_LOGIN, "POST"));
        // 繼續(xù)執(zhí)行攔截器鏈,執(zhí)行被攔截的 url 對應(yīng)的接口
        super.setContinueChainBeforeSuccessfulAuthentication(true);
        // 設(shè)置認(rèn)證失敗處理入口
        setAuthenticationFailureHandler(new JsonAuthenticationFailureHandler());
    }
    ...
}

以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java8新特性Stream的完全使用指南

    Java8新特性Stream的完全使用指南

    這篇文章主要給大家介紹了關(guān)于Java8新特性Stream的完全使用指南,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Java8具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-05-05
  • SpringBoot?RESTful?應(yīng)用中的異常處理梳理小結(jié)

    SpringBoot?RESTful?應(yīng)用中的異常處理梳理小結(jié)

    這篇文章主要介紹了SpringBoot?RESTful?應(yīng)用中的異常處理梳理小結(jié),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • 實現(xiàn)java文章點擊量記錄實例

    實現(xiàn)java文章點擊量記錄實例

    這篇文章主要為大家介紹了實現(xiàn)java文章點擊量記錄實例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-10-10
  • Java字符串替換函數(shù)replace()用法解析

    Java字符串替換函數(shù)replace()用法解析

    這篇文章主要介紹了Java字符串替換函數(shù)replace()用法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • 淺談Java中File文件的創(chuàng)建以及讀寫

    淺談Java中File文件的創(chuàng)建以及讀寫

    文中有非常詳細(xì)的步驟介紹了Java中file文件的創(chuàng)建以及讀寫,對剛開始學(xué)習(xí)java的小伙伴們很有幫助,而且下文有非常詳細(xì)的代碼示例及注釋哦,需要的朋友可以參考下
    2021-05-05
  • java 引用類型的數(shù)據(jù)傳遞的是內(nèi)存地址實例

    java 引用類型的數(shù)據(jù)傳遞的是內(nèi)存地址實例

    這篇文章主要介紹了java 引用類型的數(shù)據(jù)傳遞的是內(nèi)存地址實例,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-10-10
  • MyBatis中select語句中使用String[]數(shù)組作為參數(shù)的操作方法

    MyBatis中select語句中使用String[]數(shù)組作為參數(shù)的操作方法

    在 MyBatis 中,如何在 mapper.xml 配置文件中 select 語句中使用 String[] 數(shù)組作為參數(shù)呢,并且使用IN關(guān)鍵字來匹配數(shù)據(jù)庫中的記錄,這篇文章主要介紹了MyBatis中select語句中使用String[]數(shù)組作為參數(shù),需要的朋友可以參考下
    2023-12-12
  • Springboot+QueryDsl實現(xiàn)融合數(shù)據(jù)查詢

    Springboot+QueryDsl實現(xiàn)融合數(shù)據(jù)查詢

    這篇文章主要將介紹的是 Springboot 使用 QueryDsl 實現(xiàn)融合數(shù)據(jù)查詢,文中有詳細(xì)的代碼講解,對 SpringBoot?Querydsl?查詢操作感興趣的朋友一起看看吧
    2023-08-08
  • 解決springmvc關(guān)于前臺日期作為實體類對象參數(shù)類型轉(zhuǎn)換錯誤的問題

    解決springmvc關(guān)于前臺日期作為實體類對象參數(shù)類型轉(zhuǎn)換錯誤的問題

    下面小編就為大家?guī)硪黄鉀Qspringmvc關(guān)于前臺日期作為實體類對象參數(shù)類型轉(zhuǎn)換錯誤的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • Java調(diào)用打印機的2種方式舉例(無驅(qū)/有驅(qū))

    Java調(diào)用打印機的2種方式舉例(無驅(qū)/有驅(qū))

    我們平時使用某些軟件或者在超市購物的時候都會發(fā)現(xiàn)可以使用打印機進(jìn)行打印,這篇文章主要給大家介紹了關(guān)于Java調(diào)用打印機的2種方式,分別是無驅(qū)/有驅(qū)的相關(guān)資料,需要的朋友可以參考下
    2023-11-11

最新評論