How do you usually defend against duplicate requests with Redis? - java

I want to defend against repeated requests from the same user to a specific API using Redis in Spring Boot.
Can it be prevented simply by using redisTemplate.hasKey() provided by RedisTemplate?
When a request comes in, if you are checking whether there is a value corresponding to the key in redisTemplate.hasKey(), you know that there is a request that is already being processed and you want to raise an exception. Is this the right way?
if (redisTemplate.hasKey("key")) {
throw new Exception("There is already a request in progress.");
}

Related

How to make $batch POST request using Olingo v4 and Java?

We've to implement batch request for odata in java.I'm new to odata,from the below 2 following references,which one has to be followed.Do we've to construct a batch request or will it be done using odata batch api's?Can anyone please help on how to proceed with the implementation?
https://olingo.apache.org/doc/odata4/tutorials/batch/tutorial_batch.html
https://olingo.apache.org/doc/odata4/tutorials/od4_basic_batch_client.html
The batch request will be created automatically by the OData Client.
TLDR;
A batch request is a REST call to a special endpoint $batch, with a well-defined payload type.
The payload consists of batch requests and subtype of chagesets. Both of them are used to club multiple requests into one except the requests in one changeset is expected to be atomic. So, either all the requests execute or in case one or more fails there should be a rollback (or similar) to prevent the others from persisting
https://olingo.apache.org/doc/odata4/tutorials/od4_basic_batch_client.html
This link has the example for creating the client, Then create an entity and set some properties, put it in change set and execute. In the background it will send a batch request as per the OData $batch format as documented in
https://olingo.apache.org/doc/odata4/tutorials/batch/tutorial_batch.html

Programatically expired spring session causes the rest-api user to face unexpected response

There is an adminUser A who can make the session of another rest-api user B expired.
Collection<SessionInformation> usersSessions = sessionRegistry.getAllSessions(user, true);
usersSessions.forEach((temp) -> {
temp.expireNow();
});
Now, when the user B tries to make any rest request for the first time, it gets following 200 response without any content-type
This session has been expired (possibly due to multiple concurrent logins being attempted as the same user).
I wanted to send the user a proper response something like INVALID_SESSION with a proper HttpStatus, so I tried to intercept the servlet with a custom org.springframework.web.servlet.HandlerInterceptor (which works in other scenarios), and I observed that even the preHandle method was not being called.
It seems that the response is being sent during the session verification process. I have no idea how does this actually work. Is there a way to get custom response? Can javax.servlet.http.HttpSessionListener be useful?

What to return to from a REST API when updates fail

I am writing a web application using Spring Boot that frequently updates data on the back end and returns the updated object to reflect the update on the front end.
The question I have is what to return from my methods if the update should fail for some reason.
I am currently returning the object as it was received should it fail but as it stands the state on the front end would not reflect the failure on the back end in the case that it occurs.
I want to return the object to update the state but doing so prevents me from returning a String or HttpStatus indicating a problem doesn't it? Returning the old object doesn't seem a good solution either.
You can throw an exception in this case of failure from your REST controller.
To handle this exception, Spring provides ResponseEntityExceptionHandler callback class with the help of which you can handle the thrown exception and set different headers in the response entity.
So on client-side, you can recognise that some failure is occurred on server side.
You can set HttpStatus as HttpStatus.INTERNAL_SERVER_ERROR and add more details in the body.
The question I have is what to return from my methods if the update should fail for some reason.
You first need to determine whether the error was caused by the client or by the server, then you can determine the most suitable status code to be returned, either in the 4xx or in the 5xx range. See this answer which may give you some insights.
Instead of returning the request request back in the response, you should return a payload that describes what the problem was. Consider, for example, the payload defined in the RFC 7807 along with the application/problem+json media type.
Finally, this answer may give you insights on how to map an exception to a HTTP status code in Spring:
You can map exceptions to responses by annotating an exception class with #ResponseStatus.
It also gives you the possibility to implement a HandlerExceptionResolver or extend one of the existing implementations, such as the AbstractHandlerExceptionResolver.
Another approach would be using a ResponseEntityExceptionHandler annotated with #ControllerAdvice and define the handled exceptions by annotating the implemented method with #ExceptionHandler.

Is it possible to check JWT validity without refresh tokens?

For a few reasons I cannot use refresh tokens on client, is it possible to implement RemoteTokenServices on ResourceServer so that it checks the token is not revoked on auth server, but get auth information like user details from JWT-token itself, not from authentication server, like default implementation does using uuid tokens?
upd: this question is not duplicate, it's about JS and general
approach, I'm fine with approach I explained, I wonder if and how I can implement it using spring boot and spring security.
JWT consists of three sections:
Header #info about used algorithm
Payload #contains data, this one is important in your case
Signature #basically a hash of the first two items on this list
You should read about Payload (and JWT itself) here https://jwt.io/introduction
Long story short, you can include public data in the payload. If it comes to the mentioned RemoteTokenServices - sure, you can do that but I'm not sure if it's a good idea. You could just add public expiration-date (or expires) property to the payload.
Also, take a look at this: https://jwt.io/

Is custom exception is better to throw from java client?

I have a microservices architecutre and few microservices have its own client in order for other services to easily use the service API.
In case when we need to return response to some service from our client we also can expect that something wrong might happens while client request and client could return some http status (for example 404(not found) in case if data isn't exist for a such request or 500(internal server error) in case of unexpected service error).
My question is which approach we should use for throwing exception from client?
Do we need to create a custom exceptions on client side and handle these in appropriate way? For example MyServiceBasicException, MyServiceResourceNotFoundException, MyServiceInternalServiceErrorException and so on?
Or we need to use already existing exceptions (for example from Spring ResourceNotFoundException that can be thrown in case if data isn't exist for a such request) or other libraries?
Which benefits have one and another approach?
Thanks in advance.
if you want to do some complex handling based on an exception type then you can extend one of the exceptions and do that. otherwise, if it's just for purposes of propagation i would say reuse.

Categories