我使用彈簧安全(4.0.0.M2)來保護我的Web應用程序和我的休息API。一切都很好。但我有一個問題。我想返回401結果403(禁止)instean 401,當用戶無法驗證時安全的休息API使用彈簧安全 - 自定義狀態代碼
我爲每個身份驗證方案定義了不同的http定義,一個用於web,一個用於api。
<http pattern="/rest/v?/**" auto-config="false" use-expressions="true"
disable-url-rewriting="true" authentication-manager-ref="tokenAuthenticationManager"
create-session="stateless" realm="API security check"
entry-point-ref="http403EntryPoint">
<intercept-url pattern="/rest/v?/*" access="isAuthenticated()" />
<anonymous enabled="false" />
<http-basic />
</http>
<authentication-manager id="tokenAuthenticationManager" erase-credentials="true">
<authentication-provider user-service-ref="tokenUserDetailsService" />
</authentication-manager>
public class TokenUserDetailsService implements UserDetailsService {
@Override
public org.springframework.security.core.userdetails.UserDetails loadUserByUsername(String checkUser)
throws UsernameNotFoundException {
// lookup user
if (user == null) {
// here I whant to return 403 instead of 401
throw new UsernameNotFoundException("User not found");
}
}
}
有人可以幫助返回http狀態碼403在這種情況下?
謝謝你的幫助。
此致
桑尼
謝謝你的回覆。但它不起作用。正如你在我的第一篇文章中看到的,我已經使用http403EntryPoint作爲入口點引用。但是,當引發UsernameNotFoundException或loadUserByUsername返回null時,不會調用此入口點。 – sonny 2014-10-04 21:13:29
這是'ExceptionTranslationFilter'中使用的入口點。您尚未設置基本身份驗證參考。再次檢查我的答案並閱讀鏈接的文檔。 – 2014-10-04 23:44:06