24 Nisan 2023 Pazartesi

SpringSecurity ServerAccessDeniedHandler Arayüzü - WebFlux İle Kullanılır

Örnek
Şöyle yaparız
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.server.authorization.ServerAccessDeniedHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

public class CustomAccessDeniedHandler implements ServerAccessDeniedHandler {

  //Access Denied / unauthorized has handle method when failures occur
  @Override
  public Mono<Void> handle(ServerWebExchange exchange, AccessDeniedException accessDeniedException) {
    ServerHttpResponse response = exchange.getResponse();
    response.setStatusCode(HttpStatus.FORBIDDEN);
    return new AuthFailureHandler().formatResponse(response);
  }
}
Cevabı formatlayan kod şöyledir
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.godwinpinto.authable.application.rest.auth.json.ApiResponse;
import lombok.NoArgsConstructor;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

@NoArgsConstructor
public class AuthFailureHandler {

 public Mono<Void> formatResponse(ServerHttpResponse response) {
   response.getHeaders()
     .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
   ObjectMapper mapper = new ObjectMapper();
   ApiResponse apiResponse = new ApiResponse(response.getStatusCode()
     .value(), "Access Denied", null);
   StringBuilder json = new StringBuilder();
   try {
     json.append(mapper.writeValueAsString(apiResponse));
   } catch (JsonProcessingException jsonProcessingException) {
   }

   String responseBody = json.toString();
   byte[] bytes = responseBody.getBytes(StandardCharsets.UTF_8);
   DataBuffer buffer = response.bufferFactory()
     .wrap(bytes);
   return response.writeWith(Mono.just(buffer));
  }
}

Hiç yorum yok:

Yorum Gönder