User authentication response - java

I have an user authentication API which returns an object containing some data including status code, for ex. 200.Even if the credentials are incorrect i am sending 200 status message but the response object's status field has status 401 and message "Incorrect Credentials".So my question is, which response is proper?The one where even when the credentials are incorrect i am sending 200 status message and then inside the response object i have to check again for whether the credentials were correct or not or second where if the credentials are incorrect i am sending status 401 along with the response object?

I think it's better to return it in the HTTP header. In this way the client can know that an error has ocurred in an easier way. In the end it is more straightforward.

Preferable way is propably to return the http status and code in the header. This way the user can use native methods to react to the responses. In case there is a unexpected error in your service and you cannot form a pretty response object out of it, the user is still able to handle it since the response will have the proper HTTP status code. If the user always expects your API to return an object, he/she is in trouble in that situation. Of course, you could tell them to take that into account, but then the user would have to implement additional logic to handle two kind of responses.
But:
You could do something like I did: Let the user choose!
I put a variable in the url that tells the service whether to return the http response with proper codes or not.
The url looks something like this:
/some_path/{real_http_code}/some_path_or_data
Where the {real_http_code} is a true/false -text. If it's true, our service knows to return the response with the proper HTTP status code. If false, service will always return 200 OK -response, and the user has to check the response if something went wrong.
So, the url could look something like this:
/some_path/true/some_path_or_data
Ups and downs:
+Gives the user the freedom to choose
-Additional logic must be implemented into the service

Related

REST API - how to deal with post and functional errors

I have a REST service which is a POST to create a user, if the user does not exist, the user is created, and the service returns a 200 with the user in a json format.
Case 1: What if the user exists already, do I return a functionnal exception, so a json containing an error (all of this managed by the error handling of spring boot), and what about the http status code
Some people say to send a 303 or a 409 ... many different answers, and what about the response body in that case?
Case 2: What if in the backend we have let say a rule on the name (like containing a space) which returns an error (space not allowed in a name), same questions, do i have to return a functionnal exception and what about the http status code in this case
Somehow I want the API consumer to know what kind of json structure to handle and i guess the http status code helps for that ?
It all depends on how one interprets the various http status codes and how user friendly do you want your HTTP payload responses to be. Below are few suggestions:
NEW USER CREATED : If its a new user and gets created successfully in the backend then you return http status code 201. This is a technical status code. You can also return a functional status in the response body mentioning "User created"
https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
USER ALREADY EXISTS : If the user already exists, you should respond with http status code 200 with a response payload body mentioning a functional status "User already exists"
USER CREATION FAILED : If the new user rules are not satisfied at the backend service and it throws an error then the http status code of 400 can be used and functional status in response payload of "User creation failed, please conform to the user name rules" https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
For an API Consumer to know everything about your API's, you may want to provide a API specification document. You may use open API spec(previously known as swagger) https://swagger.io/specification/
Somehow I want the API consumer to know what kind of json structure to handle and i guess the http status code helps for that ?
Not quite.
The HTTP status code is meta data in the transfer documents over a network domain. It communicates the overall semantics of the response (for instance, is the body of the message a representation of a resource, or a representation of an error? is this response cachable? and so on).
For unsafe requests in particular, cache invalidation is sensitive to "non-error status codes". The difference between 303 (non-error status code) and 409 (error status code) can be significant.
The Content-Type header gives you a mechanism to describe the kind (schema) of the message you are returning (ex: application/problem+json).
The way I think about it: the information for your bespoke consumer belongs in the message-body; we lift data from the message-body to the HTTP metadata so that general-purpose components can take advantage of that information (for example, by invalidating cache entries).
So we would normally start by defining the schema and semantics of the message body, and making sure that we have intelligent ways to communicate all of the things we want the caller to know. In other words, we are defining the documents that we pass to the client, and how to extract information from them.
Information that HTTP components need to know get copied from our bespoke document into the standardized forms (status code, headers).
Where things get complicated: the fact that something is an "error" in your domain, that doesn't necessarily mean that it should also be considered to be an "error" in the transfer of documents over a network domain.
A common case: we are using our API to navigate some work through a process; that process has a happy path, and also some exceptional paths that we normally try to avoid (accounts are overdrawn, items are out of stock, etc).
An HTTP request can move work from the happy path to an exception path and still be a "success" in the transfer of documents domain.
The easiest heuristic I know is to think about previously cached copies of responses by the same target URI. If those responses are still re-usable, then you are probably looking at a 4xx status code. If the responses should be invalidated, then you are probably looking at a 2xx or 3xx status code.

Which HTTP status code is correct for Subscription cancel exception?

Which HTTP status code is correct for Subscription Canceled exception?
I need to throw an exception when the user tries to accesses a certain page.
I checked a few statuses like Payment Required, but it's not satisfying the requirement. Any suggestion?
Which HTTP status code is correct for Subscription cancel exception?
HTTP status codes belong to the transfer documents over a network domain.
So the specifics of what is going on in your domain don't particularly matter - the idea is to understand the error condition in terms of document transfer, and work from there.
In this case, the best fit is likely 403 Forbidden
The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).
It may help to imagine how this example would play out on a web site. For the human user, you would return a bunch of HTML explaining that their subscription had been cancelled, perhaps with links to resources that would allow the user to re-subscribe, and so on.
For the browser, you would have the HTTP meta data, including the status code, so that the browser would understand the general purpose semantics of the message (for instance, should earlier representations of the resource be invalidated in the cache).
it's a API request from front-end.
This doesn't really enter into the discussion; the motivation for the uniform interface is that we can swap out the implementations at either end of the conversation and the semantics of the self descriptive messages don't change.
I would say that correct Response code is:
401 Unauthorized
Since by the definition the user Cancelled his subscription and cannot more access paid content, therefore user is Unauthorized for that.
In the other words User is Authenticated but Unaouthorized to do this request.
I'd like to offer an alternative solution. 403 errors make a lot of sense here, as access is denied for a resource. However, this could be difficult to handle in the front-end, because it's indiscernible from a 403 error caused by lacking permissions or roles. A 402 error is non-standard, but "Payment Required" would be easier to program around. If using a non-standard HTTP code is allowed, I believe this to be a more suitable status to return from an API based on a cancelled subscription, or a lack of a valid subscription in general.

Best practise to write a boolean API in Java Sturts 2 server?

I need to write an API to check if a user name already exists in a database.
I want my server (Struts Action class instance in tomcat server) to return true/false.
Its something like this
checkUserName?userName=john
I want to know what is the standard way to do this?
Shall I return a JSON response with just one boolean value ... seems like a overkill.
Shall I do something like manually setting the HTTP header to 200 or 404 (for true/false), but that seems to violate the actual purpose of using the headers which I believe must only be used to indicate network failures etc.
(Too long for a comment.)
I don't see any reason not to return a standard JSON response with something indicating whether or not the user name exists. That's what APIs do: there's nothing "overkill" about providing a response useful across clients.
To your second point: headers do a lot more than "indicate network problems". A 404 isn't a network problem, it means the requested resource doesn't exist. It is not appropriate in your case, because you're not requesting a resource: the resource is checkUserName, which does exist. If instead your request was /userByName/john a 404 would be appropriate if the user didn't exist. That's not an appropriate request in this case, because you don't want to return the user.
A 401 isn't a network problem, it's an authentication issue. A 302 isn't a network problem, it's a redirect. Etc. Using HTTP response codes is entirely appropriate, if they match your requests.

How to be sure of the accuracy of HttpClient response?

Please tell me what is the better trick to be sure of a HttpClient response, for example, if we do a login through HttpClient and we need to tell the user of success or failure of his login operation.
Thank you in advance!
PS.: I don't need just to know response Http Status, I need to be sure that I am in the right page after response, example : login.php ==> home.php, if I post my request to login.php, how can I be sure that I am now in hom.php (login success) or I always stay in login.php (login failed)
HttpClient.execute() is going to return a HttpResponse
HttpResponse.getStatusLine().getStatusCode() will give you the HTTP response code as an int.
See:
http://developer.android.com/reference/org/apache/http/client/HttpClient.html
http://developer.android.com/reference/org/apache/http/HttpResponse.html
http://developer.android.com/reference/org/apache/http/StatusLine.html
Edit to add from comments below:
You're not using a web browser. The only way you're going to be "on another page" is if you received a 302 redirect and then sent a request for the other page. In which case ... you know which page you have.
If the PHP login script is utterly broken and just returns two different pages depending on whether you logged in or not, you're on your own. Parse the response and hope for the best. More than likely there's going to be a cookie or custom header in the response if that's the case, and you're going to have to look for it.

Does the server send response only when its HTTP 200?

im writing a java application that sends a post request to a server and expect a json from the server. Now when i need to get the response from the server do i only need to get it from the inputStream when the http code is 200 (HTTP OK) or is there any other cases ? , example :
//...
if (urlConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
// only here try to get the response
}
//...
It depends on how the server is implemented. Check the API, if the server has one. If it's internal, ask your server guy.
Generally speaking, if your response code is either 2xx or 3xx, I would check the response anyway...
If the server your communicating with is following the spec then either 200 or 201 responses are valid to contain an entity. A 204 response is successful but has no data in the response.
See section 9.5 here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9.5 for details of acceptable responses to a POST. Extract below:
The action performed by the POST method might not result in a resource
that can be identified by a URI. In this case, either 200 (OK) or 204
(No Content) is the appropriate response status, depending on whether
or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response
SHOULD be 201 (Created) and contain an entity which describes the
status of the request and refers to the new resource, and a Location
header (see section 14.30).
There are three things to consider:
All 2xx codes denote success of some sort. But depending on the exact code, your reading code might be different. (204 for example means success but no content.)
There are redirecting codes (3xx). These are usually automatically followed by the http client library but you can also set them not to, in which case you need to have custom code that handles these cases.
There can be valuable information returned in the stream even if you get a code that denotes an error. Whether you want to process it depends on your exact needs.

Categories

Resources