HttpStatusServerAccessDeniedHandler write error message

This commit is contained in:
Rob Winch 2017-10-28 21:44:46 -05:00
parent 77acb34bcd
commit 192776858d
3 changed files with 21 additions and 9 deletions

View File

@ -72,8 +72,7 @@ public class HelloWebfluxMethodApplicationITests {
.uri("/message")
.attributes(robsCredentials())
.exchange()
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN)
.expectBody().isEmpty();
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
@Test

View File

@ -77,8 +77,7 @@ public class HelloWebfluxMethodApplicationTests {
.uri("/message")
.attributes(robsCredentials())
.exchange()
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN)
.expectBody().isEmpty();
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
@ -101,8 +100,7 @@ public class HelloWebfluxMethodApplicationTests {
.get()
.uri("/message")
.exchange()
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN)
.expectBody().isEmpty();
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
@Test
@ -125,8 +123,7 @@ public class HelloWebfluxMethodApplicationTests {
.get()
.uri("/message")
.exchange()
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN)
.expectBody().isEmpty();
.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}
@Test

View File

@ -16,6 +16,11 @@
package org.springframework.security.web.server.authorization;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;
import org.springframework.http.HttpStatus;
@ -23,6 +28,8 @@ import org.springframework.security.access.AccessDeniedException;
import org.springframework.util.Assert;
import org.springframework.web.server.ServerWebExchange;
import java.nio.charset.Charset;
/**
* Sets an HTTP Status that is provided when
* @author Rob Winch
@ -38,6 +45,15 @@ public class HttpStatusServerAccessDeniedHandler implements ServerAccessDeniedHa
@Override
public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException e) {
return Mono.fromRunnable(() -> exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN));
return Mono.defer(() -> Mono.just(exchange.getResponse()))
.flatMap(response -> {
response.setStatusCode(HttpStatus.FORBIDDEN);
response.getHeaders().setContentType(MediaType.TEXT_PLAIN);
DataBufferFactory dataBufferFactory = response.bufferFactory();
DataBuffer buffer = dataBufferFactory.wrap(e.getMessage().getBytes(
Charset.defaultCharset()));
return response.writeWith(Mono.just(buffer))
.doOnError( error -> DataBufferUtils.release(buffer));
});
}
}