使用 Spring Boot 1.5.6.RELEASE 我可以发送HTTP状态代码401
而不是403
,如How let spring security response unauthorized(http 401 code) if requesting uri without authentication中所述,通过这样做:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.exceptionHandling()
.authenticationEntryPoint(new Http401AuthenticationEntryPoint("myHeader"));
//...
}
}
使用org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint
类。
我刚升级到Spring Boot 2.0.0.RELEASE,发现不再有这样的课程了(至少在那个包中)。
Qestions:
Spring Boot中是否存在此类(Http401AuthenticationEntryPoint
)?
如果不是,那么在现有项目中保持相同行为以保持与依赖于此状态代码(401
)而不是{{1 }}
答案 0 :(得分:12)
已删除课程org.springframework.boot.autoconfigure.security.Http401AuthenticationEntryPoint
,转而使用org.springframework.security.web.authentication.HttpStatusEntryPoint
。
在我的情况下,代码将如下所示:
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//...
http.exceptionHandling()
.authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
//...
}
}
答案 1 :(得分:2)
Http401AuthenticationEntryPoint
已被删除,请参见10715:
删除Http401AuthenticationEntryPoint
rwinch于2017年10月20日发表了评论
据我所知,Spring Boot代码库中未使用它,因此最好删除Http401AuthenticationEntryPoint
。
根据您的要求,您可以使用:
答案 2 :(得分:1)
只需阐述@lealceldeiro的答案:
在Spring Boot 2之前,我的Securiy Configuration类如下:
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {
@Bean
public Http401AuthenticationEntryPoint securityException401EntryPoint() {
return new Http401AuthenticationEntryPoint("Bearer realm=\"webrealm\"");
}
@Autowired
private Http401AuthenticationEntryPoint authEntrypoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
// some http configuration ...
// Spring Boot 1.5.x style
http.exceptionHandling().authenticationEntryPoint(authEntrypoint);
}
//...
}
现在在Spring Boot 2中看起来像这样:
@Configuration
public class MyConfig extends WebSecurityConfigurerAdapter {
//Bean configuration for Http401AuthenticationEntryPoint can be removed
//Autowiring also removed
@Override
protected void configure(HttpSecurity http) throws Exception {
// some http configuration ...
// Spring Boot 2 style
http.exceptionHandling().authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED));
}
//...
}
答案 3 :(得分:1)
您可以通过重写AuthenticationEntryPoint类来自定义逻辑 这应该可以工作:
@Component public class AuthEntryPointException implements AuthenticationEntryPoint, Serializable {
private static final long serialVersionUID = -8970718410437077606L;
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException authException) throws IOException {
response.setStatus(HttpStatus.SC_UNAUTHORIZED);
response.setContentType("application/json");
response.getWriter().write("{\"result\":\"UNAUTHORIZED\",\"message\":\"UNAUTHORIZED or Invalid Token\"}");
}
}