Controller advice in Spring MVC - java

I have some problems regarding Controller usage in Spring.
Preferably, I would like to keep the Controller methods small and simply use them to call a Service function as follows:
#Controller
class controllerClass {
#RequestMapping("/foo/")
public void foo(Model model) {
Data returnedData = fooServiceFunction();
model.addAttribute("data", returnedData);
}
}
#Service
class serviceClass {
fooServiceFunction() {
Data data = methodCall();
methodCall2();
methodCall3();
return data;
}
}
However, in practise I have found this implementation difficult because I have found myself needing to check if the methods called from within the fooServiceFunction() succeeded or failed. I have been returning a custom 'Status' class from these functions which is passed to the controller to signal if the methods have executed successfully and/or any errors that have occurred (validation errors, etc.).
Now, this is fine if I do not need to return any data. But if I want to return data from the Service function and pass it to the Controller, this would mean I would need to make a custom class for EVERY Controller method which would contain:
a) the data.
b) the success status
which just seems unreasonable.
I have considered just throwing Exceptions to indicate a failure, but this doesn't seem proper.
Is there a better way? What is the optimal way to handle these situations? Or should I just write fat Controller methods that implement more of the application/business logic?
Thank you.

I think the best approach would be to throw a custom exception and then use a class annotated with
#ControllerAdvice
to deal with that exception and make it return a ResponseEntity customized according to your needs. This way the line
return data;
will only occur if there are no exceptions

Related

Custom access control to REST endpoints in a Spring Boot application

First of all, I know about #PreAuthorize annotations and about Expression based access control.
For the sake of learning (as well as for many reasons), what I would like to have is this:
Users are authenticated and their roles are provided by an LDAP directory and populated into the Principal object when they authenticate. This works, as in "it is currently in place in a project".
An annotation (chosen to be #AccessControl) implements the paradigm that access control is entirely tied to roles. The annotation can be set on a class/type (the REST controller), in which case it applies to any method on which there's not also another such annotation, or on a method (a REST endpoint). The deepest annotation always wins, whether it is restricting or relaxing the authorization constraint.
The access control logic, which is a bit more complex than what I could get from the expression based access control, would be enforced by another piece of code. It is also a bit more maintainable but I guess this is only in my eyes.
As an example, a controller would have, except for an #AccessControl annotation over a method, endpoints that can only be accessed by users with ADMIN in their list of roles:
#RestController
#RequestMapping("/admin")
#AccessControl({ Roles.ADMIN })
public class AdminController {
...
}
My current indecision, after reading a lot these past days is more about whether to write a custom request filter or rather an AOP advice.
With a custom request filter, I find myself unable (for the moment) to determine which method of which controller the request is going to be mapped to. The annotations are out of my reach.
With an AOP advice, I don't know (yet) how to reply to the client with a 403 Forbidden status.
My questions stem directly from these two points:
How can I get the controller method that will be called for a client request?
How can I return an HTTP status code from an AOP advice and effectively end the processing of the request when the client is not authorized?
It turned out to be much simpler than I initially thought and I completed it in less than a day, using the AOP option.
This is the code of the AccessControl annotation, comments removed:
#Documented
#Inherited
#Retention(RUNTIME)
#Target({ TYPE, METHOD })
public #interface AccessControl {
public String[] value() default {};
}
It can be placed either on a controller (see my original post/question) or on a controller method:
#RestController
#RequestMapping("/admin")
#AccessControl({ Roles.ADMIN })
public class AdminController {
// This endpoint has open access: no authorization check will happen.
#AccessControl
#RequestMapping(value = "{id}", method = RequestMethod.GET)
public DummyDto getNoCheck(#PathVariable Integer id) {
return service.get(id);
}
// This endpoint specifically allows access to the "USER" role, which is lower
// than ADMIN in my hierarchy of roles.
#AccessControl(Roles.USER)
#RequestMapping(value = "{id}", method = RequestMethod.GET)
public DummyDto getCheckUser(#PathVariable Integer id) {
return service.get(id);
}
// The authorization check defaults to checking the "ADMIN" role, because there's
// no #AccessControl annotation here.
#RequestMapping(value = "{id}", method = RequestMethod.GET)
public DummyDto getCheckRoleAdmin(#PathVariable Integer id) {
return service.get(id);
}
}
In order to perform the actual verification, two questions must be answered:
first, which methods are to be processed?
second, what is checked?
Question 1: which methods are to be processed?
To me, the answer was something like "all REST endpoints in my code". Since my code lies in a specific root package, and since I'm using the RequestMapping annotation in Spring, the concrete answer comes in the form of a Pointcut specification:
#Pointcut("execution(#org.springframework.web.bind.annotation.RequestMapping * *(..)) && within(my.package..*)")
Question 2: what exactly is checked at runtime?
I will not put the entire code here but basically, the answer consists in comparing the user's roles with the roles required by the method (or its controller if the method itself bears no access control specification).
#Around("accessControlled()")
public Object process(ProceedingJoinPoint pjp) throws Throwable {
...
// Get the roles specified in the access control rule that applies (from the method annotation, or from the controller annotation).
// Get the user roles from the UserDetails previously saved when the user went through the authentication process.
// Check authorizations: does the user have one role that is required? If no, throw an exception. If yes, don't do anything.
// No exception has been thrown: let the method proceed and return its results.
}
What was bothering me in my initial thinking was the exception. Since I already had an exception mapper class that bears the #ControllerAdvice annotation, I just reused that class to map my specific AccessControlException to a 403 Forbidden status code.
For retrieving the user's roles, I used SecurityContextHolder.getContext().getAuthentication() to recover the authentication token, then authentication.getPrincipal() to retrieve the custom user details object, which has a roles field that I normally set up during the authentication process.
The code above is not to be used as-is (for instance, path mapping collisions will happen), but this is just to convey the general idea.
I want to provide an approach you can use if you want to follow the AOP advice root:
Concerning this point if using AOP:
How can I return an HTTP status code from an AOP advice and
effectively end the processing of the request when the client is not
authorized? solution:
In your aspect class, using at Around Advice kindly do the following:
#Around("execution(* net.my.package.AdminController.*(..)) && args(.., principal)")
public ResponseEntity<?> processRequest(final ProceedingJoinPoint joinPoint, final Principal principal) {
final String controllerMethodName = joinPoint.getSignature().getName();
LOGGER.info("Controller Method name : {}", controllerMethodName);
final boolean isAuthSuccessful = authenticationService.authenticate(principal);//Pass auth details here
if(!isAuthSuccessful) {
return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Request declined"); //End request if auth failed
} else {
try {
return (ResponseEntity<?>)joinPoint.proceed(); //Continue with request
} catch (Throwable e) {
LOGGER.error("Error In Aspect :", e);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("failed request");
}
}
}
Well, the above code has comments addressing the challenges you are facing. But for this code to work ensure to do the following:
Make Sure all your controller methods you want to intercept do return ResponseEntity
You can change the #Around aspect to use a Point cut with value of #annotation for your #AccessControl annotation and you are free to chain the conditions in the #Around aspect
Make sure you find a way to pass data to this aspect so that you have a way to validate user credentials

Spring MVC: What's the right way to register custom Validator in REST controller

I'm trying to make sense of how validation works in Spring. So far I've learned that there are two ways to perform validation of user input data:
JSR-303 validation based on javax.validation.constraints annotations. This validation is best suitable for simple object fields validation. But you can also implement your custom type level annotations to perform more complicated validation based on checking values of multiple fields.
Spring Validation based on org.springframework.validation.Validator interface. Seems to be better suited for more complicated validation.
If I want to use both these approaches, what is the right way to register my custom validator in controller?
This is what I'm trying to do.
My custom validator.
public class PasswordPairValidator implements Validator {
#Override
public boolean supports(Class<?> clazz) {
return PasswordPair.class.equals(clazz);
}
#Override
public void validate(Object target, Errors errors) {
PasswordPair password = (PasswordPair) target;
if (!password.getPassword().equals(password.getRepeatPassword())) {
errors.reject("passwordField", "passwords don't match");
}
}
}
My controller.
#RestController
#RequestMapping("/api/v1/users")
public class UserController {
#InitBinder
protected void initBinder(WebDataBinder binder) {
binder.addValidators(new PasswordPairValidator());
}
#RequestMapping(method = RequestMethod.POST)
public ResponseEntity<UserInfo> createUser(
#RequestBody #Valid UserInfo userInfo) {
userInfo.setId(123);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(userInfo.getId()).toUri();
return ResponseEntity.created(location).body(userInfo);
}
#RequestMapping(value = "/change_password", method = RequestMethod.POST)
public ResponseEntity<UserInfo> changePassword(
#RequestBody #Valid PasswordPair password) {
UserInfo user = new UserInfo("test#gmail.com", "testuser");
user.setId(123);
return ResponseEntity.ok().body(user);
}
}
When I call createUser endpoint the code fails with the following error:
ERROR c.e.testapp.controller.GlobalExceptionHandler - Internal Server Error
java.lang.IllegalStateException: Invalid target for Validator [com.example.testapp.validation.PasswordPairValidator#49acd001]: com.example.testapp.domain.UserInfo#cae4750
The problem apparently is that Spring tries to apply PasswordPairValidator to UserInfo object, which was not my intention.
Why Spring doesn't use validator's supports() method to check to which objects validator can be applied?
In a different stackoverflow question I found out that I need to specify value for #InitBinder annotation to make it work and the value should be "passwordPair". But what is this value as it's not the class name ("PasswordPair") or method parameters value ("password")?
The second question is if I want to add several validators do I need to define multiple #InitBinder("value") methods or is there a less cumbersome way to do it?
And the final question, maybe it's better to use annotation based validation for everything, to validate separate fields and implement type level custom annotations with ConstraintValidator to perform more complicated validation? It's a bit confusing what are the pros and cons of these approaches.
You have to provided an argument to your #InitBinder annotation.
Please refer this question
Above question also answers your other question on registering multiple validators.
I believe the reason this happens is because the #InitBinder method will be called every time a request is being processed and thus for all the methods you have that correspond to HTTP verbs.
The only way I know that you can limit the times the method annotated with #InitBinder gets called is by using the value argument that the annotation takes. I admit that I am also a bit confused on what that value is or how it is interpreted.
Spring boot uses supports to check if a validator can be used every time initBinder() gets called but will throw an exception when it doesn't fit. This happens when initBinder() get called when a Request is processed. So even if you have multiple validators from which one is valid for the request body it will fail
If someone could help with how we can correctly apply validators in Spring boot I would also appreciate it. In C# I know that you can register beans as in middleware and based on the class you register the validator with, the correct validator gets called. (I am not well versed in C# but this is what I remember). Isn't something like this also possible in Java?

Spring Webflux Bean Validation

I have a simple rest controller (using spring web-FLUX), that get a bean to save in database. But as usual, I would like to validate some fields of it before saving.
I have a validation method to be called before save the bean. But how could I do that in a more functional (and appropriate) manner?
I have tried something like:
public void save(Mono<MyBean> myBean) {
myBean.map(this::validateBean).map(myRepository::save)
}
But the method validateBean is not being called, only when I do something like
public void save(Mono<MyBean> myBean) {
myBean.map(this::validateBean)
.map(myRepository::save)
.subscribe();
}
I don't know if the subscribe part is the most correct one (I believe it isn't), but I think it works because is kind of a terminal operation. Am I right?
Even so, that does not solve my problem, because my validation method throws a BusinessException when something is wrong with the bean. And that is exactly what I wanna do.
[EDITED]
This is my rest controller would me something like:
#PostMapping(value = "/something")
public Mono<ResponseEntity> salvar(#RequestBody MyBean myBean) {
return myService.salvar(myBean)
.map(RestResponses::ok)
.defaultIfEmpty(RestResponses.empty());
}
I know this is not working because my service ir no returning anything. But I do not know what would be the correct way. So I just post an idea. Thanks for understanding...
Could you guys give me some help?

Global Exception Handling in Jersey

Is there a way to have global exception handling in Jersey? Instead of individual resources having try/catch blocks and then calling some method that then sanitizes all of the exceptions to be sent back to the client, I was hoping there was a way to put this where the resources are actually called. Is this even possible? If so, how?
Instead of, where sanitize(e) would throw some sort of Jersey-configured exception to the Jersey servlet:
#GET
public Object getStuff() {
try {
doStuff();
} catch (Exception e) {
ExceptionHandler.sanitize(e);
}
}
Having:
#GET
public Object getStuff() throws Exception {
doStuff();
}
where the exception would get thrown to something that I can intercept and call sanitize(e) from there.
This is really just to simplify all the Jersey resources and to guarantee that the exceptions going back to the client are always in some sort of understandable form.
Yes. JAX-RS has a concept of ExceptionMappers. You can create your own ExceptionMapper interface to map any exception to a response. For more info see: https://jersey.github.io/documentation/latest/representations.html#d0e6352
javax.ws.rs.ext.ExceptionMapper is your friend.
Source: https://jersey.java.net/documentation/latest/representations.html#d0e6665
Example:
#Provider
public class EntityNotFoundMapper implements ExceptionMapper<javax.persistence.EntityNotFoundException> {
public Response toResponse(javax.persistence.EntityNotFoundException ex) {
return Response.status(404).
entity(ex.getMessage()).
type("text/plain").
build();
}
}
All the answers above are still valid. But with latest versions of spring Boot consider one of below approaches.
Approach 1 :
#ExceptionHandler- Annotate a method in a controller with this annotation.
Drawback of this approach is we need to write a method with this annotation in each controller.
We can work around this solution by extending all controllers with base controller (that base controller can have a method annotated with #ExceptionHandler. But it may not be possible all the times.
Approach 2 :
Annotating a class with #ControllerAdvice and define methods with #ExceptionHandler
This is similar to Controller based exception (refer approach 1) but this is used when controller class is not handling the exception.
This approach is good for global handling of exceptions in Rest Api

using multiple values HttpStatus in #ResponseStatus

I am using the Spring annotation #ResponseStatus in my Exception like
#ResponseStatus(value=HttpStatus.UNAUTHORIZED)
public class UnauthorizedException extends Exception{
}
Problem is I want to throw the same error for a number of values like HttpStatus.SC_SERVICE_UNAVAILABLE, etc..
Is there any way to use multiple values in #ResponseStatus? Thanks in advance.
No. You can't have multiple http status codes. Check http spec
If you actually want to set different status codes in different scenarios (but only one status code per response), then remove the annotation, and add it via code:
public X method(HttpServletResponse response) {
if (..) {
response.setStatus(..);
} else {
response.setStatus(..);
}
}
The only workaround that comes to mind is not using the #ResponseStatus annotation. Consider writing your own error handling code in the controller that catches the relevant exception sets the error code in the way you would prefer for that class. If it's in several controllers, consider writing an interceptor or using AOP.
You can set the response code in the HttpServletResponse class with the .setStatus() method, that you could get from the applicationContext.
Why not just create multiple exception classes and throw the appropriate one?

Categories

Resources