Can you change the 401 error response? - spring

My question is, can you change the structure of the response of the 401 error message?
{
"error": "unauthorized",
"error_description": "No AuthenticationProvider found for org.springframework.security.authentication.UsernamePasswordAuthenticationToken"
}
for example
{
"timestamp" : 123124354,
"status" : 401,
"message" : "The username or password are not valid!"
}

This was answered a while ago: Modify default JSON error response from Spring Boot Rest Controller. Checking the reference guide I would recommend going with the #ControllerAdvice to give you the most flexibility on defining how the JSON response is returned.

Related

How to set message for error reponse status in Spring MVC?

I have a spring mvc handler like this:
#PostMapping("jwtToken")
fun jwtToken(#RequestBody body: JWTToken)
{
val token = body.token
if(token.isNullOrBlank())
throw ResponseStatusException(HttpStatus.UNAUTHORIZED, "Empty token")
}
If i send it an incorrect input, that triggers the exception, i get a reponse body like this:
{
"timestamp": "2020-10-30T03:41:20.305+00:00",
"status": 401,
"error": "Unauthorized",
"message": "",
"path": "/auth/jwtToken"
}
Why is the 'message' field empty in the response when i did assign a message to the exception? How do i set the message field
It might be related to the updated behaviour of the Spring Boot.
https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.3-Release-Notes#changes-to-the-default-error-pages-content
server.error.include-message=always
in .properties should do the trick but I prefer to use my own extended classes like this:
class CustomException(message: String): Exception(message) { ... }

Send custom error response in Spring Cloud Gateway when no route matches

In Spring Cloud Gateway , I want to send a custom error in case a particular predicate match fails . For eg:-
I have a Path and a header predicate. Something like this -
- id: test
uri: http://localhost:8000/
predicates:
- Path=/consignment
- Header=h,h1
So if the path mathces and header doesn't , the request fails with not found error something like by default-
{
"timestamp": "2020-03-08T20:05:42.440+0000",
"path": "/test",
"status": 404,
"error": "Not Found",
"message": null,
"requestId": "6dd2e799"
}
But I want to send a custom response mentioning that the header is not present.
Is there a way to do that?

How to handle Exception and return proper HTTP code in Spring webflux?

I have a method which gives response using Mono.fromfuture(result) and which throws CustomException with 400 as status.
Now in my service class, when I call that method, the error and code I am throwing there is not getting propagated to my client(postman). Only the message is what I am seeing.
I am getting this below format: -
{
"timestamp": "2019-02-01T11:13:32.748+0000",
"path": "/some_url",
"status": 500,
"error": "Internal Server Error",
"message": "Unable to fetch Response"
}
Expectation (what I want to achieve) : -
{
"timestamp": "2019-02-01T11:13:32.748+0000",
"path": "/some_url",
"status": 400, // (my own status)
"error": "INVALID_ARGUMENT", // (my own error)
"message": "Unable to fetch Response"
}
My Code:-
public Mono<ResponseObject> fetchResponse(arg) {
return Mono.just(somedata which will give exception)
.flatMap(k -> callExternalService(k))
.onErrorMap(e -> Mono.error(
new BusinessException("Unable to fetch Response", e))
*/* e here is giving :-
"code" : 400,
"message" : "Request contains an invalid argument.",
"status" : "INVALID_ARGUMENT" */*
}
Have you looked at the documentation of the Response class?
You can create a Response of your own, using the static methods in the doc, and send it, instead of Mono.error, in the onErrorMap.
You have to return something like below:
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).body(klass, Klass.class);
ServerResponse.status(status).build();//read doc and set for yourself
You can also check this link.

Invalid CSRF Token 'null'

I referred "https://github.com/mswiderski/jbpm-examples/tree/master/spring-boot-jbpm it runs well for GET request.
Now I am trying following code
#RequestMapping(value="/test" ,method=RequestMethod.POST)
public String test(#RequestBody String emp){
System.out.println("Your request is "+emp);
return " Hi ";
}
through POSTMAN but it gives me error as,
{
"timestamp": 1511946868300,
"status": 403,
"error": "Forbidden",
"message": "Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.",
"path": "/test"
}
Please anyone help me to come out of it.
I had same issue and below trick works for me.
Set http.csrf().disable() inside configure method of your DefaultWebSecurityConfig Class.
Please refer https://docs.jboss.org/jbpm/release/7.12.0.Final/jbpm-docs/html_single/ [ 3.4.1.2. Configure authentication and authorization].
Hope this solution help you.

403 Forbidden resposnse from a GET request to http://api.espn.com/v1/sports/news/6277112

I have problem with the ESPN API:
I have an API key, and sent a query to the address http://api.espn.com/v1/sports/news/1581816?region=GB, which included my API key in the parameters.
I received 403 forbidden response: with this JSON
{
"status": "error",
"code": 403,
"message" : "Account Inactive"
}
I am looking at http://developer.espn.com/docs/headlines#using-the-api and at the last line it says that i can make a GET request to this url and it should work, but it doesn't.
How can I receive a valid response from the ESPN servers?
I just test it and it works fine. That means your key is invalid, or you are not including it. Replace below and it will work.
http://api.espn.com/v1/sports/news/1581816?region=GB&apikey=<yourKey>
--
{
timestamp: "2013-10-13T15:33:49Z",
resultsOffset: 0,
status: "success",
resultsLimit: 10,
resultsCount: 1,
headlines: [
{ ... }
]
}

Resources