使用spring security保护rest api-自定义状态代码
我正在使用SpringSecurity(4.0.0.M2)来保护我的web应用程序和RESTAPI。一切都很好。但我有一个问题。当用户无法进行身份验证时,我想返回http结果403(禁止),而不是401 我为每个身份验证场景定义了不同的http定义,一个用于web,一个用于api使用spring security保护rest api-自定义状态代码,spring,rest,spring-security,http-status-code-403,userdetailsservice,Spring,Rest,Spring Security,Http Status Code 403,Userdetailsservice,我正在使用SpringSecurity(4.0.0.M2)来保护我的web应用程序和RESTAPI。一切都很好。但我有一个问题。当用户无法进行身份验证时,我想返回http结果403(禁止),而不是401 我为每个身份验证场景定义了不同的http定义,一个用于web,一个用于api <http pattern="/rest/v?/**" auto-config="false" use-expressions="true" disable-url-rewriting="true" au
<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");
}
}
}
公共类TokenUserDetailsService实现UserDetailsService{
@凌驾
public org.springframework.security.core.userdetails.userdetails加载userbyusername(字符串checkUser)
抛出UsernameNotFoundException{
//查找用户
if(user==null){
//这里我不想返回403而不是401
抛出新的UsernameNotFoundException(“未找到用户”);
}
}
}
在这种情况下,是否有人可以帮助返回http状态代码403
谢谢你的帮助
致意
sonny由
元素创建的也有一个对入口点的引用。当身份验证失败时,它会调用该函数,这就是401代码的来源(这在基本身份验证中是正常的)
如果要更改它,可以使用namespace属性。所以
<http-basic entry-point-ref="http403EntryPoint" />
应该给出你想要的结果。目前我找到了一个可行的解决方案。当我使用自定义过滤器(position=pre_auth)时,我可以使用doFilter方法更改响应代码
但我不确定这是否是最好的解决方案。谢谢您的回复。但它不起作用。正如您在我的第一篇文章中所看到的,我已经准备好使用http403EntryPoint作为entry-point-ref。但是当抛出UsernameNotFoundException或loadUserByUsername返回null时,不会调用此入口点。这是在
ExceptionTranslationFilter
中使用的入口点。您尚未设置基本身份验证引用。再次检查我的答案并阅读链接文档。