Correct HATEOAS response when creating a user account - json

I have a REST api written in node which uses HATEOAS. The user is required to have an account before they can access the bulk of it.
They register an account with login details, then login to obtain an access token, and then use that token in order to access any endpoints that aren't register or login.
Issuing a get to the root responds with a directory with available actions.
Q: What is the correct response from register, to tell the client what it can do next (i.e. login)?
register technically creates a new resource on the server so a 201 CREATED and a Location header would seem appopriate. However the login reference isn't the location of the newly created resource.
Should I return 201 Created with a Location pointing to the newly created user (e.g. /myaccount or /users/{id} and then include a login link in the response body?
{
_links: {
self: { href: "what goes here?" },
x:login: { href: "/login" }
}
}
Do I not tell the client at all, and require them to do a get on the application root in order to fetch a list of available endpoints. This should include login anyway. Assuming the client had to do that in the first place to get the register link it should already have login.
Expecting the client already to already have the login link feels uncomfortable as it relies on an assumption of the client's prior activity.
Requiring the client to issue another request to the root directory after registering seems mean, inefficient and unnecessary. If the client has just created a resource it seems only fair that the server should respond with what it can do with it next.

I like to have my api's act no differently than a webpage. If you want the UX of your application to be the user is taken to login after they register, then 302 them from a successful register to the login resource. And upon successful login, 302 to them to the appropriate destination (IE, if they tried to access something with no token, then take them to login, with a destination of the original requested resource). That's and important part to your #3. Having a link off the root that leads to login, but you need to protect all the other links such that they indicate (and link to) a login being required to access the resource. The client app should expect to get this login required response at any time as tokens can (and do) expire at any time.
Following on this, it might make sense to do the JWT as a cookie instead of as an Authorization Header, it would make it a bit easier for the client (they just have to setup a cookie jar)..if the client is say a native mobile app that maintains a single connection setup. If it's server to server, then auth header makes sense. I'd go about supporting both to cover both scenarios.
Continuing on the idea of thinking of the api as a web site. Why have them login after registration at all? Why not have the registering of an account end up with the login token being sent? they just set their user/pass, why make them enter it again? I realize with some more exotic architectures the register service can not perform the login action (perhaps it doesn't have the private key to sign the token), but if it is possible i'd consider it.
If you really want to stick to the 201 header (which is fine, just make sure the docs of your register relationship indicate that), then option 2 is the closest in my opinion. A location header to the URL of the account just created a 201 is pretty standard for creating a user. But, i'd not return what you've supposed there. You're kind of returning a account-created resource (the thing with the login link), but do you really need this custom resource? If you want to give some messaging back to the client (like "Account Created") in that resource then absolutely yes, but you could also just give them back the root resource.
tl;dr; Decide what you want your UX to be and then make your API implement your UX.

Related

How to POST to another site with just a url

A service provider is supposed to forward messages on to an endpoint (specified by me) but all I get to give them is a URL. How can I make this work.
I have signed up to a satellite service and I am trying make the first steps with their cloud API. I have hardware which sends simple messages over their satellite infrastructure to their cloud services. The provide the user (me) with a dashboard type interface to register the hardware as well as a desitnation (or multiple destinations) each destination is a single url. I dont get to specify usernames, passwords, code or anything just a single url. The service says
"the data will be forwarded to the pre-registered http(s) endpoint (the URL I have given them). Data is sent as a http POST request with Content-Type: application/json. All data is accompanied by an endpoint reference, timestamp, a unique identifier (UUID), and a digital signature that may be used to verify that the data originated from Myriota. Multiple packets may be batched into a single request."
I have a website so to start with I just want to get a single message to display on my page. I have completed and tested the code to display posts by GETing from https://www.mywebsite.com/wp-json/wp/v2/posts. This works.
the URL that I have given the service provider is the same as above. But none of the data reaches my site.
I dont really know how the data exchange or handshaking works here but I assume that for a third party to post to my site, they would need to include some sort of authentication. can this authentication data be included in the url? what is the authentication data? is it my Wordpress username and password? Is it safe send this data in a url? Can I turn off authentication so that anyone can post to my site? surely that isnt safe?
I have minimal experience with web development but plenty with embedded systems, I am working with a young software engineer and he is stumped also. together we have burned nearly a whole week on this so I have bit the bullet and turned to stackoverflow to see if anyone can help

Login Security using jsonwebtoken

I am currently working on a website using React where I want to be able to have user login. Right now my strategy is to send form data to the server (express) on submit, and if the info matches a user in my DB, the server sends back a signed JWT with no sensitive information (just the username).
Once the client receives the JWT, I am adding it to localStorage as well as adding the decoded data of it to my redux store. I plan to have my redux store holding the currently logged in user.
I believe there may be a security issue in my site because currently I have it so when the user first arrives at the site, If there is a JWT, it is added to my axios headers and the decoded JWT is set to be the current user. The code looks like this:
if(localStorage.jwtToken) { // If token present, most likely a user is signed in
setAuthorizationToken(localStorage.jwtToken) // Set that token to head all api calls
store.dispatch(setCurrentUser(jwt.decode(localStorage.jwtToken))) // Set user in redux store
}
Currently I've found that if someone just goes into my localStorage, copies my JWT and adds it to their localStorage then bam, they are me. I'm unsure if this is really a security flaw because the only way I've recreated this myself is by physically copying the token from one browser to another. But in general this seems very unsafe that just taking my token steals my identity.
If anyone knows a way to make this more secure or if there is a better strategy, or at least tell me what I'm doing wrong that would be highly appreciated.
How can another person get your token? Give expire time to token needed. Maybe try different way for securing token, especially give more security in API side. When logging in, store log activity in database and create unique field to identificate it such ip address or user-agent, or maybe detect is that user have been hit login endpoint before or not.

Service now api how to comment as specific user

I'm working on a project that consumes Service Now API (Rest). To do so our client has registered us as a user in order to login and make all service calls we need to. This project has an interface where users can login once they have an account on Service Now as well, the username they type to log in has nothing to do with service now by the way, but later they associate theirs service now users to it. They can do some operations through this interface, where all of them are done using the integration user/pass not their service now users theirselves, even because they do not need to share their passwords with us. But it's needed to track the correct user to register on service now and I'm in trouble specifically about commenting on an incident. The endpoint to comment is the following :
http://hostname/api/now/table/incident/{sys_id}
where request body is a json object just as simple as :
{
"comments": "My comment is foo bar"
}
but when this comment is registered on Service Now it is under integration user instead the user which commented. Is there any way I could keep a specific user, considering I already have the user id on Service Now ready to inform it on the request the way it should be.
I tried reading Service Now documentation but had no clue how to solve it, altought I've found something about impersonate
This is happening because you're being proxied through the "Integration User" instead of your own account. As long as this is the case, your comments are going to be attributed to the Integration User.
I can think of two ways to fix this issue.
Ask the client to log you into their system directly as a user.
Implement a special API (Scripted REST API, available in Geneva or later) that allows you to identify the Incident and enter the comment, and then the script forges the comment on your behalf, attributing authorship correctly.
The first solution can be expensive due to possible additional licensing costs.
The second solution will require a willing client to devote 2-3 hours of development time, depending on the programmer.
Firstly, you need an integration user with suffient rights. Our integration user has suffient rights out of the box, but your story could be different. A quick check is to try impersonate as other user using menu.
Login as integration user to ServiceNow instance.
Go to https://{instance}.service-now.com/nav_to.do
Click on username at top right corner. This is a drop down.
There should be at least three menu items: "Profile", "Impersonate User", and "Logout". If you do not have "Impersonate User" in this menu, your integration user miss some permissions. Contact system administrator if you miss this menu item to configure appropriate permissions.
Then you need to find sys_id of user that you want to impersonate. For example:
https://{instance}.service-now.com/api/now/table/sys_user?sysparm_query=user_name={username}&sysparm_fields=sys_id
If you have suffient privileges, you could invoke the folling endpoint with sys id of user that you want to impersonate:
HTTP POST to https://{instance}.service-now.com/api/now/ui/impersonate/{user_sys_id} with body "{}" and content type "application/json". You need to provide HTTP basic authentication to this query as your integration user.
The response code on success is 200. The response body could be ignored. The interesting result of this response is a set of cookies for impersonated user in response headers. These cookies could be used for subsequent REST API calls until they expire. Use some HTTP rest client dependent method to capture them and to provide them to next calls.
For Apache HTTP Client (Java), I'm creating http client context using:
HttpClientContext context = HttpClientContext.create();
context.setCookieStore(new BasicCookieStore());
Pass thing context to impersonation request and to subsequent API calls until I get 401 reply, after that I'm reaquiring cookies. Setting new cookie store is important, as otherwise some default cookies store is used.
Two things to note:
This API looks like internal one, so it could change at any time. If it happens, look for what "Impresonate User" menu item does, and repeat it youselves.
ServiceNow permissions are quite fine-grained, so the target user could lack permissions to perform operation. In some cases, if there is no permission to update the field the operation PATCH on object returns reponse 200, but field is not updated. This introduces a surprising mode of failure when you use impersonation.

Which authentication can be used for managing Box users through REST end points

I am working on an Identity management application, using which my goal is to manage users on Box application.
I was going through Box documentation, and there are two ways for authentication
OAuth 2.0, which has redirection URI as required parameter. And due to which I cannot make use of it, since I will not be able to enter username and password and Authorize dynamically using my Java code.
Reference: https://box-content.readme.io/reference#oauth-2
JWT authentication, this I can use in my code and successfully get Access token. But problem here is, this access token can only be used to manage App Users (who will not have login to Box website).
Reference: https://box-content.readme.io/docs/box-developer-edition
So, is there any other authentication mechanism which I can use for getting Access token for managing Box users?
Regards,
Sandeep
The current best option is #1 with a process like this:
Create a Box application with the 'Manage an Enterprise' scope enabled.
Use a web-based access token generator (such as this or this) to get an initial access/refresh token pair. Save these somewhere safe (flat file, DB).
Code your application to initialize itself with the access/refresh token pair from its saved location.
When the access/refresh token pair is refreshed, write them out to the save location.
If your application runs across multiple nodes/processes this approach will require some (painful) coordination between them. I believe Box is working on some improvements in this area, so you may not have to live with this for long.

box.com api OAuth authentication

Either I'm dense, or the docs assume I already know what they're telling me, but I need some clarification on doing authentication for a box.com app. I really don't understand whate's going on. As I read it:
the app running on the user's machine sends a request to Box, including all the little secrets (Which aren't all that secret any more if the user knows how to read the code).
The user is directed to the Box login page, which then sends the user to my server (with no page specified) attaching an authentication code.
The app somehow magically gets that code back from my server and sends a request to Box for the access token.
Box sends the access token to my server?
The app again magically gets the access token from my server and sends its APT requests.
Obviously I got lost somewhere.
And, why do I have to have a server involved in the process? The article on making a JavaScript app refers to a direct request for a token. Is there documentation on that somewhere?
You register your application on Box
After registration you receive clientId and clientSecret once on Box website
You hardcode your credentials somewhere in your application
First time your application needs to access Box API it should redirect user to https://www.box.com/api/oauth2/authorize, specifying your clientId, clientSecret and redirectURI as parameters. About redirectURI see below.
The box.com website opens. User enters his own credentials in the web form on box.com
User allows your application to access his files via API on the box.com website
Box redirects user back to you application using redirectURI specified before. One of the parameters to this request is "code". This is a very short-lived (30 seconds) access code that is only aligable for obtaining real access token.
During next 30 seconds your application should make another call to Box API to next URL: https://www.box.com/api/oauth2/token, specifying the previously obtained code. If everything was correct, your application receives an access_token, a refresh_token and "expires" values.
Now your application can make requests to Box API, specifying access_token every time
access_token expires in number of seconds, specified in "expires" field. It should be about 3600 seconds or 1 hour. Each time your application sees that access_token has expired, it should make another request to Box with the refresh_token and obtain a fresh access_token for another 1 hour.
refresh_token itself expires in 14 days
Note: if you develop a desktop application, then you should open browser for user on the step 4, redirectURI should be something like http://127.0.0.1:8080/Callback and you should run a small webserver just to catch the redirect with the code as in step 7.
Box requires that you specify a redirect_uri in your application's profile, and it must be an HTTPS URL.
As a result, it is not possible to use box with what google's oauth2 documentation calls "Client Side" or "Installed" applications, only "Web Server Applications" are allowed. Web Server applications do not have the secret leaking problem, because only the server knows the secret. You can pass the access token from your server to javascript on the client after
the oauth transaction is complete, if you want the client to make api requests directly.
In your question you are not totally clear in what you are actually trying to produce.
I however suspect that you are trying to write a client application what needs to authenticate to box using the OAUTH2 solution they have delivered in API V2.
If this is for an IPhone for example BOX has a great example of how to handle it.
In a WinForm application you would need to capture the resulting code sent back by box in the browser1.isnavigating event.
Windows console application you register a custom URI registration to collect the code.
Neither of these need to be registered in the API developers Application on box as you would pass the redirect required in the request to box.
If this does not point you in the right direction and your writing a .NET app then post again and I will try to clarify a little more.
Box requires some form user interaction which is short sighted in my opinion but try a web service that simulates a user interaction which then you can save/pass the token to your application to sync up with the Box "Cloud".