I am getting below error when trying to send message to browser
java.lang.IllegalStateException: getOutputStream() has already been called for this response
I am using basic authentication and trying to send message when authentication failed .so getting this above error when executing the below code.
public class MyBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
org.springframework.security.core.AuthenticationException authException)
throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "Basic realm=" + getRealmName());
response.setContentType("text/html");
PrintWriter writer = response.getWriter();//here getting error
writer.println("HTTP Status 401 : " + authException.getMessage());
}
@Override
public void afterPropertiesSet() throws Exception {
setRealmName("localhost");
super.afterPropertiesSet();
}
}
Can anyone please help on this ?
It might be that you are using Spring Boot and it detects that you have not implemented a ErrorViewResolver Bean, i have looked inside the DefaultErrorViewResolver class and found a @ConditionalOnMissingBean configuration that gives you back a DefaultErrorViewResolver.
Basically your spring auto config is using the getOutputStream() of your HttpServletResponse, and as you know Streams usually can not be operated upon once they have been used. (as you can see here: https://docs.oracle.com/javaee/6/api/javax/servlet/ServletResponse.html#getOutputStream() )
Your option is to either disable the DefaultErrorViewResolver or make your class implement ErrorViewResolver, then place your logic inside the resolveErrorView() method.
Hope this might help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.