AuthenticationEntryPoint : 負責驗證時的例外,像是token過期、未帶token去打受保護之API...。AccessDeniedHandler : 負責被PreAuthrorize擋下來的請求,因此是跟「權限、角色」相關。httpSecurity
.csrf(//...)
.sessionManagement(//...)
.authorizeHttpRequests(//...)
.addFilterBefore(//...)
.exceptionHandling(ex -> ex
// 401: token過期 or 未登入去打受保護API
.authenticationEntryPoint((request, response, authException) -> {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.getWriter().write("{\"code\":401,\"msg\":\"未登入或憑證已失效,請重新登入\"}");
})
// 403: 權限不足(被 @PreAuthorize 擋下)
.accessDeniedHandler((request, response, accessDeniedException) -> {
response.setContentType("application/json;charset=UTF-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().write("{\"code\":403,\"msg\":\"權限不足,拒絕訪問\"}");
})
);
本篇文章出自《每天學Java直到今年結束》Day242,大家可以到我的網站上查看~