你正在嘗試做的,可以在不修改批註來完成。
在您的Spring配置中,您可以指定一個AccessDeniedHandler
bean,當Spring Security確定您的用戶不被允許執行他們嘗試執行的操作時將被調用。
訪問被拒絕的處理程序是非常簡單的:
public class CustomDefaultAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
AccessDeniedException accessDeniedException) throws IOException, ServletException {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
的AuthenticationProvider
,讓你什麼失敗將提供更多的信息的一個例子:
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Autowired
private UserService userService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
UsernamePasswordAuthenticationToken auth = (UsernamePasswordAuthenticationToken) authentication;
String username = String.valueOf(auth.getPrincipal().toString());
String password = String.valueOf(auth.getCredentials());
if(username.isEmpty() || password.isEmpty()){
throw new UsernameNotFoundException("You pudding, there is no username or password");
} else {
SystemUser user = userService.findByUsername(username);
if(user == null){
throw new UsernameNotFoundException("No user exists, stop hacking");
}
//Do more stuff here to actually apply roles to the AuthToken etc
return new UsernamePasswordAuthenticationToken(username, null, authorities);
}
}
}
感謝您的迴應!我其實已經有了一個AuthenticationFailureHandler。我缺少的是一個AccessDeniedHandler。在你的回答中,你正確地提到了AccessDeniedHandler,但是給出了一個AuthenticationFailureHandler的例子。如果您更新了代碼示例以確保準確,我會將您的答案標記爲選定的答案。 – AlexG
@AlexG明天我會在工作 – JamesENL
@AlexG,爲您更新。這非常簡單 – JamesENL