How to customize #RequestParam error 400 response in Spring MVC - spring-mvc

Is there a way to customize what gets displayed when a required #RequestParam is not sent to the request handler? I always get HTTP Status 400 with a description "The request sent by the client was syntactically incorrect ()." in this case.

Yes, there is a way you should catch MissingServletRequestParameterException
You can do it in several ways:
1)
#ExceptionHandler(MissingServletRequestParameterException.class)
public String handleMyException(Exception exception) {
return "yourErrorViewName";
}
2)
<error-page>
<exception-type>org.springframework.web.bind.MissingServletRequestParameterException</exception-type>
<location>/WEB-INF/pages/myError.jsp</location>
</error-page>
Hope it helps.

How I solved my problem:
#ResponseBody
#ExceptionHandler(MissingServletRequestParameterException.class)
public Object missingParamterHandler(Exception exception) {
// exception handle while specified arguments are not available requested service only. it handle when request is as api json service
return new HashMap() {{ put("result", "failed"); put("type", "required_parameter_missing");}};
}

Related

Handle Unauthorized Request and Return Status Code 404

I am developing a standalone .Net Core API targeting framework .Net Core 2.2.The authentication scheme is JWTBearerTokens connecting to our ADFS Identify server.
When I call an API endpoing decorated with the [Authorize] attribute I am getting a 401 Unauthorized response, which is expected and default behaviour.
What I want to do next is instead of having that same call return a 401, I would like to return the status code to be 404. (I don't want to get into great details of why 404. Simply, I do not want to expose that the endpoint exists if a valid token is not included in request)
In previous .Net Framework WebAPI you could create your own attribute and override the HandleUnauthorizedRequest method and return the status code you want.
I have reviewed the documentation on policy-based authorization, but have not tried the sample or tried implementing it. The policy handler looks more to do with handling (return success or fail) if a policy is not fulfilled. I do not see anywhere where you can return a different status code on failure. So that only would make sense if I start checking against actual Policies.
Any insights?
Returning 404 instead of 401 is bad practice(as mentioned in the comments by #Chris Pratt) and must be avoided. Consider these cases,
You're leaving the project to someone else and they can't figure why 404 is returned
A 404 is returned when you call the homepage/Index page. Poor ideology.
Later on in the project, you decide to allow post requests without authentication. So on and so forth.
Anyways, as part of the community, I'll give you the answer...
Add this to your global.asax
void Application_EndRequest(object source, System.EventArgs args)
{
if (Response.StatusCode == 401)
{
Response.ClearContent();
Response.RedirectToRoute("ErrorH", (RouteTable.Routes["ErrorH"] as Route).Defaults);
}
}
And in routeConfig, create a route for your errorHandler :
routes.MapRoute(
"ErrorH",
"Error/{action}/{errMsg}",
new { controller = "CustomController", action = "Change401To404", errMsg = UrlParameter.Optional }
);
And in your custom controller :
public class CustomController : Controller //or Base
{
public ActionResult Change401To404(){
//Do whatever you want
}
}
PS: This is not the only way, there are many other ways to do it. But at least in this method, you can differentiate real 404 responses from 401 responses.

How to found out url with which the request arrived at error handler?

I send following http request:
http://localhost:8081/member/createCompany/getSmallThumbnail/
On server side I hit into controller method:
#RequestMapping("/error")
public String error(Model model, HttpServletRequest request){
if(request.getRequestURI().contains("thumbnail")){
System.out.println("thumbnail accepted");
}
request.toString();
model.addAttribute("message", "page not found");
return "errorPage";
}
At this method I want to know url with which the request arrived.
If in debug I stop inside this method I see information needed for me:
But I cannot find method in request which will return this.
Please help to return url which I want.
P.S.
Actually I have not mapped controller in my spring mvc application(url is broken) for http://localhost:8081/member/createCompany/getSmallThumbnail/. This url("/error") configured in web.xml as error page.
Your request got redispatched to /error (presumably for error processing).
If this framework follows the normal Servlet error dispatching behavior, then your original request can be found in the HttpServletRequest.getAttributes() under the various javax.servlet.RequestDispatcher.ERROR_* keys.
ERROR_EXCEPTION - The exception object
ERROR_EXCEPTION_TYPE - The type of exception object
ERROR_MESSAGE - the exception message
ERROR_REQUEST_URI - the original request uri that caused the error dispatch
ERROR_SERVLET_NAME - the name of the servlet that caused the error
ERROR_STATUS_CODE - the response status code determined for this error dispatch
What you want is
String originalUri = (String) request.getAttribute(
RequestDispatcher.ERROR_REQUEST_URI)

Spring MVC binding request parameters

I wrote a spring-mvc controller method to get an array of values in the request parameter.The method looks like below
/**
Trying to get the value for request param foo which passes multiple values
**/
#RequestMapping(method=RequestMethod.GET)
public void performActionXX(HttpServletRequest request,
HttpServletResponse response,
#RequestParam("foo") String[] foo) {
......
......
}
The above method works fine when the request url is in below format
...?foo=1234&foo=0987&foo=5674.
However when the request url is in below format the server returns 400 error
...?foo[0]=1234&foo[1]=0987&foo[2]=5674
Any idea how to fix the method to cater to the second format request url?
This is not possible with #RequestParam. What you can do is implement and register your own HandlerMethodArgumentResolver to perform to resolve request parameters like
...?foo[0]=1234&foo[1]=0987&foo[2]=5674
into an array. You can always checkout the code of RequestParamMethodArgumentResolver to see how Spring does it.
Note that I recommend you change how the client creates the URL.
The server is supposed to define an API and the client is meant to follow it, that's why we have the 400 Bad Request status code.
I resolved this issue using the request.getParameterMap().Below is code.
Map<String,String> parameterMap= request.getParameterMap();
for(String key :parameterMap.keySet()){
if(key.startsWith("nameEntry")){
nameEntryLst.add(request.getParameter(key));
}
}

ASP.NET Web API removing HttpError from responses

I'm building RESTful service using Microsoft ASP.NET Web API.
My problem concerns HttpErrors that Web API throws back to user when something go wrong (e.g. 400 Bad Request or 404 Not Found).
The problem is, that I don't want to get serialized HttpError in response content, as it sometimes provides too much information, therefore it violates OWASP security rules, for example:
Request:
http://localhost/Service/api/something/555555555555555555555555555555555555555555555555555555555555555555555
As a response, I get 400 of course, but with following content information:
{
"$id": "1",
"Message": "The request is invalid.",
"MessageDetail": "The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'MyNamespaceAndMethodHere(Int32)' in 'Service.Controllers.MyController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter."
}
Something like this not only indicates that my WebService is based on ASP.NET WebAPI technology (which isn't that bad), but also it gives some information about my namespaces, method names, parameters, etc.
I tried to set IncludeErrorDetailPolicy in Global.asax
GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Never;
Yeah, that did somehow good, now the result doesn't contain MessageDetail section, but still, I don't want to get this HttpError at all.
I also built my custom DelegatingHandler, but it also affects 400s and 404s that I myself generate in controllers, which I don't want to happen.
My question is:
Is there any convinient way to get rid of serialized HttpError from response content? All I want user to get back for his bad requests is response code.
What about using a custom IHttpActionInvoker ?
Basically, you just have to send an empty HttpResponseMessage.
Here is a very basic example :
public class MyApiControllerActionInvoker : ApiControllerActionInvoker
{
public override Task<HttpResponseMessage> InvokeActionAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
{
var result = base.InvokeActionAsync(actionContext, cancellationToken);
if (result.Exception != null)
{
//Log critical error
Debug.WriteLine("unhandled Exception ");
return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(HttpStatusCode.InternalServerError));
}
else if (result.Result.StatusCode!= HttpStatusCode.OK)
{
//Log critical error
Debug.WriteLine("invalid response status");
return Task.Run<HttpResponseMessage>(() => new HttpResponseMessage(result.Result.StatusCode));
}
return result;
}
}
In Global.asax
GlobalConfiguration.Configuration.Services.Replace(typeof(IHttpActionInvoker), new MyApiControllerActionInvoker());
One other important thing you could do, not related to Web Api, is to remove excessive asp.net & IIS HTTP headers. Here is a good explanation.
I believe your approach of using the message handler is correct because regardless of the component in the Web API pipeline that sets the status code to 4xx, message handler can clear out response body. However, you do want to differentiate between the ones you explicitly set versus the ones set by the other components. Here is my suggestion and I admit it is a bit hacky. If you don't get any other better solution, give this a try.
In your ApiController classes, when you throw a HttpResponseException, set a flag in request properties, like so.
Request.Properties["myexception"] = true;
throw new HttpResponseException(...);
In the message handler, check for the property and do not clear the response body, if the property is set.
var response = await base.SendAsync(request, cancellationToken);
if((int)response.StatusCode > 399 && !request.Properties.Any(p => p.Key == "myException"))
response.Content = null;
return response;
You can package this a bit nicely by adding an extension method to HttpRequestMessage so that neither the ApiController nor the message handler knows anything about the hard-coded string "myException" that I use above.

Returning HTTP 403 in a WebAPI method

How do I return an HTTP 403 from a WebAPI method? I've tried throwing an HttpResponseException with HttpStatusCode.Forbidden, and I've tried
return request.CreateErrorResponse(HttpStatusCode.Forbidden, pEx);
Neither of which work. Both ALWAYS return an HTTP 200. What am I missing? It has to be something simple but I don't see it.
You might have a problem with your routing configuration. Below is a working sample. Put it in your controller and see if it works. If it doesn't, check your routing with a diagnostic tool (i.e. Cobisi Routing Assistant).
public HttpResponseMessage GetSomeString(int id)
{
// This method is not allowed!
return this.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "This method is not allowed!");
}

Resources