Laravel 5.2 - How to implement register with api token without session? - api

I'm looking for a way to create a api token after registration without session
And I also have a question:
Regular site have session to identify the current user
But in api How can I identify the current user if we do not create for him a session?
I'm having trouble with these questions

The main concept is that in login request you send e-mail and password and you get the token.
In all next request you send always this token (so you know which user makes the request) and for this you also send other data (if they are necessary).
Of course you need to make sure this token is somehow unique so you can now exactly which user is making the request.
You can implement it on your own or you can take advantage on some ready components.
In fact in Laravel 5.2 you have TokenGuard built in so you can create simple token authentication out of the box. You can watch this movie on Laracasts for further details.
You can also use some other packages for example JWT Auth

Related

Creating a "pre-signed/tokenized" URL which skips the login step (Json Web Tokens)

I'm working on an application where an administrator will send a unique link to a user for them to fill out a form. The system requires authentication in order to fill out a form, however I would like this unique link to "skip" the login step for the user. ie when the user receives the link, they can simply click it and fill out the form without logging in, but behind the scenes the user is actually authenticated with a Json Web token. Ideally I would like the link to never expire, or possibly after 1 year so the user could use the link 6 months down the road and the link will seamlessly still work for the user.
The most obvious solution would be to generate a JWT token with a lengthy expiry when the admin generates the link and just include the token in the url that is sent to the user. When the user receives the link, they already have a JWT token so they don't need to login. However this feels like it may be insecure because now the user has a JWT token for their user with a long expiry sitting in their email inbox.
I think I might be able to include information in the JWT token that would restrict it for that specific purpose (filling out the form), but I'm not even sure if I'm on the right path here.
What is the best way to do this, is there any other recommended ways to create sort of a "pre-signed" url that skips the login step?
I'm using ASP.NET Core as the backend, but I'm not sure if it's relevant as this is more of a general authentication / JWT problem.
doesn't matter what precautions you take, anyone who gets a hold of the email would be authenticated. I would consider PGP (or the like) in sending email to user.

Get userid from auth0 session localStorage

I'm in the process of implementing auth0 login in my project, and to be as fast as possible I'm using a hosted login page. Following the auth0 vue docs I've got up and running quickly and I can login and logout users.
Now, I'm trying to create a user profile page with a route of user/:id. For the :id part I want to use the user_id of the user profile, but I'm having issues understanding the optimal way to get it. I realize I can use the auth0 api users endpoint but I'm not sure that's the correct way. Do I actually need to make an API call to the users endpoint each time an user clicks their profile? Is there no better way to get the user_id, maybe from the id_token which is set in localStorage upon login?
Even better, is there a way to get actual user ids? I know that if I would setup my own login with my own db, I'd have an auto incrementing id which I'd use for user id. This does not seem possible with Auth0, or am I wrong about that?
Disclosure: I work for Auth0.
The idToken returned at the end of the authentication / authorization is a JSON Web Token. This token contains the Auth0 user_id as the sub (subject) claim (property).
If you are using Auth0.js or our AuthService tutorial, Auth0.js will decode this token and give it to you as idTokenPayload object in the authResult. This can be used to identify the user as idTokenPayload.sub.
You can store this object as a whole in localStorage or simply decode the token that you accquired from localStorage. However, please note that you should validate the token after accquiring it from localStorage aswell.
To avoid all the above, you can simply use the checkSession method each time your application bootstraps to get a new copy of the accessToken / idToken and rely on that directly :)

User registration/authentication flow on a REST API

I know this is not the first time the topic is treated in StackOverflow, however, I have some questions I couldn't find an answer to or other questions have opposed answers.
I am doing a rather simple REST API (Silex-PHP) to be consumed initially by just one SPA (backbone app). I don't want to comment all the several authentication methods in this question as that topic is already fully covered on SO. I'll basically create a token for each user, and this token will be attached in every request that requires authentication by the SPA. All the SPA-Server transactions will run under HTTPS. For now, my decision is that the token doesn't expire. Tokens that expire/tokens per session are not complying with the statelessness of REST, right? I understand there's a lot of room for security improvement but that's my scope for now.
I have a model for Tokens, and thus a table in the database for tokens with a FK to user_id. By this I mean the token is not part of my user model.
REGISTER
I have a POST /users (requires no authentication) that creates a user in the database and returns the new user. This complies with the one request one resource rule. However, this brings me certain doubts:
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
If I decided to return the token together with the user, then I believe POST /users would be confusing for the API consumer, and then something like POST /auth/register appears. Once more, I dislike this idea because involves a verb. I really like the simplicity offered in this answer. But then again, I'd need to do two requests together, a POST /users and a POST /tokens. How wrong is it to do two requests together and also, how would I exactly send the relevant information for the token to be attached to a certain user if both requests are sent together?
For now my flow works like follows:
1. Register form makes a POST /users request
2. Server creates a new user and a new token, returns both in the response (break REST rule)
3. Client now attaches token to every Request that needs Authorization
The token never expires, preserving REST statelessness.
EMAIL VALIDATION
Most of the current webapps require email validation without breaking the UX for the users, i.e the users can immediately use the webapp after registering. On the other side, if I return the token with the register request as suggested above, users will immediately have access to every resource without validating emails.
Normally I'd go for the following workflow:
1. Register form sends POST /users request.
2. Server creates a new user with validated_email set to false and stores an email_validation_token. Additionally, the server sends an email generating an URL that contains the email_validation_token.
3. The user clicks on the URL that makes a request: For example POST /users/email_validation/{email_validation_token}
4. Server validates email, sets validated_email to true, generates a token and returns it in the response, redirecting the user to his home page at the same time.
This looks overcomplicated and totally ruins the UX. How'd you go about it?
LOGIN
This is quite simple, for now I am doing it this way so please correct me if wrong:
1. User fills a log in form which makes a request to POST /login sending Basic Auth credentials.
2. Server checks Basic Auth credentials and returns token for the given user.
3. Web app attached the given token to every future request.
login is a verb and thus breaks a REST rule, everyone seems to agree on doing it this way though.
LOGOUT
Why does everyone seem to need a /auth/logout endpoint? From my point of view clicking on "logout" in the web app should basically remove the token from the application and not send it in further requests. The server plays no role in this.
As it is possible that the token is kept in localStorage to prevent losing the token on a possible page refresh, logout would also imply removing the token from the localStorage. But still, this doesn't affect the server. I understand people who need to have a POST /logout are basically working with session tokens, which again break the statelessness of REST.
REMEMBER ME
I understand the remember me basically refers to saving the returned token to the localStorage or not in my case. Is this right?
If you'd recommend any further reading on this topic I'd very much appreciate it. Thanks!
REGISTER
Tokens that expire/tokens per session are not complying with the statelessness of REST, right?
No, there's nothing wrong with that. Many HTTP authentication schemes do have expiring tokens. OAuth2 is super popular for REST services, and many OAuth2 implementations force the client to refresh the access token from time to time.
My idea is that at the time to create a new user, create a new token for the user, to immediately return it with the Response, and thus, improving the UX. The user will immediately be able to start using the web app. However, returning the token for such response would break the rule of returning just the resource. Should I instead make two requests together? One to create the user and one to retrieve the token without the user needing to reenter credentials?
Typically, if you create a new resource following REST best practices, you don't return something in response to a POST like this. Doing this would make the call more RPC-like, so I would agree with you here... it's not perfectly RESTful. I'll offer two solutions to this:
Ignore this, break the best practices. Maybe it's for the best in this case, and making exceptions if they make a lot more sense is sometimes the best thing to do (after careful consideration).
If you want be more RESTful, I'll offer an alternative.
Lets assume you want to use OAuth2 (not a bad idea!). The OAuth2 API is not really RESTful for a number of reasons. I'm my mind it is still better to use a well-defined authentication API, over rolling your own for the sake of being RESTful.
That still leaves you with the problem of creating a user on your API, and in response to this (POST) call, returning a secret which can be used as an access/refresh token.
My alternative is as follows:
You don't need to have a user in order to start a session.
What you can do instead is start the session before you create the user. This guarantees that for any future call, you know you are talking to the same client.
If you start your OAuth2 process and receive your access/refresh token, you can simply do an authenticated POST request on /users. What this means is that your system needs to be aware of 2 types of authenticated users:
Users that logged in with a username/password (`grant_type = passsword1).
Users that logged in 'anonymously' and intend to create a user after the fact. (grant_type = client_credentials).
Once the user is created, you can assign your previously anonymous session with the newly created user entity, thus you don't need to do any access/refresh token exchanges after creation.
EMAIL VALIDATION
Both your suggestions to either:
Prevent the user from using the application until email validation is completed.
Allow the user to use the application immediately
Are done by applications. Which one is more appropriate really depends on your application and what's best for you. Is there any risk associated with a user starting to use an account with an email they don't own? If no, then maybe it's fine to allow the user in right away.
Here's an example where you don't want to do this: Say if the email address is used by other members of your system to add a user as a friend, the email address is a type of identity. If you don't force users to validate their emails, it means I can act on behalf of someone with a different email address. This is similar to being able to receive invitations, etc. Is this an attack vector? Then you might want to consider blocking the user from using the application until the email is validated.
You might also consider only blocking certain features in your application for which the email address might be sensitive. In the previous example, you could prevent people from seeing invitations from other users until the email is validated.
There's no right answer here, it just depends on how you intend to use the email address.
LOGIN
Please just use OAuth2. The flow you describe is already fairly close to how OAuth2 works. Take it one step further an actually use OAuth2. It's pretty great and once you get over the initial hurdle of understanding the protocol, you'll find that it's easier than you thought and fairly straightforward to just implement the bits you specifically need for your API.
Most of the PHP OAuth2 server implementations are not great. They do too much and are somewhat hard to integrate with. Rolling your own is not that hard and you're already fairly close to building something similar.
LOGOUT
The two reasons you might want a logout endpoint are:
If you use cookie/session based authentication and want to tell the server to forget the session. It sounds like this is not an issue for you.
If you want to tell the server to expire the access/refresh token earlier. Yes, you can just remove them from localstorage, and that might be good enough. Forcing to expire them server-side might give you that little extra confidence. What if someone was able to MITM your browser and now has access to your tokens? I might want to quickly logout and expire all existing tokens. It's an edge case, and I personally have never done this, but that could be a reason why you would want it.
REMEMBER ME
Yea, implementing "remember me" with local storage sounds like a good idea.
I originally took the /LOGON and /LOGOUT approach. I'm starting to explore /PRESENCE. It seems it would help me combine both knowing someone's status and authentication.
0 = Offline
1 = Available
2 = Busy
Going from Offline to anything else should include initial validation (aka require username/password). You could use PATCH or PUT for this (depending how you see it).
You are right, SESSION is not allowed in REST, hence there is no need to login or logout in REST service and /login, /logout are not nouns.
For authentication you could use
Basic authentication over SSL
Digest authentication
OAuth 2
HMAC, etc.
I prefer to use PUBLIC KEY and PRIVATE KEY [HMAC]
Private key will never be transmitted over web and I don't care about public key. The public key will be used to make the user specific actions [Who is holding the api key]
Private key will be know by client app and the server. The private key will be used to create signature. You generate a signature token using private key and add the key into the header. The server will also generate the signature and validate the request for handshake.
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
Now how you will get private key? you have to do it manually like you put facebook, twitter or google api key on you app.
However, in some case you can also return [not recommended] the key only for once like Amazon S3 does. They provide "AWS secret access key" at the registration response.

Problems configuring user authentication by external API on Symfony2

I have a problem authenticating users for my new Symfony2 application.
This applications gets all the info through an API, so no database is used. When a user goes to login page, he introduce the user and password in the login form. Then, I have to authenticate him using an API call. This API call returns "false" if it's not a user, and return a token key and a token secret if its a correct user. With this token key and secret, during the user session, I can make all the API requests I need for rendering all the pages of the application. Once the user session is over and token key and secret are erased, the user has to login again.
I don't know really how ti implement that. I read this http://symfony.com/doc/current/cookbook/security/custom_provider.html and that http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html, and I'm still so lost... :(
Can any one help me?
Thank you so much :)
If you want to write custom authentication you have found the correct links. As an example you can see the implementation of the OAuth authorization HWIOAuthBundle. But keep in mind that this type of authentication creates a user on your system. If you do not use a database, you must make a request to the API every time user send a request.
First you need to understand that there is no magic. On every request symfony checks if url matches one of the specified firewalls (see secutity.yml). Listener that fired you can see in the firewall factory. If matches are found, the action switches to the corresponding AuthenticationListener. Listener attempts to authenticate the credewntials by creating Token, which is sended to AuthenticationProvider
$this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));
in AuthenticationProvider
public function authenticate(TokenInterface $token) {
...
}
AuthenticationProvider try to get user via UserProvider. In case of success, Token stored in the session. On subsequent requests, ContextListener comes into play first, checks the session, extract token and send it to AuthenticationProvider similar.
In general terms, the scheme looks like that. More info you can find examining the source code of Symfony Security component.
Really good starting point is a UsernamePasswordFormAuthenticationListener. It just take login and password from request and make simplest UsernamePasswordToken.
protected function attemptAuthentication(Request $request)
{
...
}
Good luck!

What's the simplest way to do authentication with a web API?

I've got a web API that provides data to users without authentication (the website lets users post data, after they've logged in using traditional cookies & sessions). Someone wants to develop an iPhone app that adds things to my database, so I want a user to authenticate on the iPhone, and then the api will allow posting.
So, what should I look in to do this easily? The API as it stands is RESTful, it'd be nice to keep it that way. Obviously I'm new to this but there seem to be so many standards I don't know where to start. If I can code it up in less than an hour, that'd be ideal.
Much appreciated!
A decent way to implement this would be to provide the app creator with a token as well as an app id, and have them use that token as salt for an agreed upon encryption method to send username and password (plus app id) to a new API call for a new session.
Upon receiving the request for a new session, you would look up their token based on the appid provided, and try and decrypt the user/pass using the token.
If the user/pass are accepted, then you create a new session and return the session id to them, which they can send along with any new requests.
This prevents the app from having to send authentication for every request, and allows you to expire sessions at a given time.
WebSecurity was introduced in ASP.NET MVC 4. It relies on the SimpleMembershipProvider. It uses FormsAuthentication to manage cookies
WebMatrix.WebData.WebSecurity is provides security and authentication features for ASP.NET Web Pages applications, including the ability to create user accounts, log users in and out, reset or change passwords, and perform related tasks.
You must create or initialize an WebSecurity database before you can use the WebSecurity object in your code.
In the root of your web, create a page (or edit the page ) named _AppStart.cshtml.
_AppStart.cshtml
#{
WebSecurity.InitializeDatabaseConnection("Users", "UserProfile", "UserId", "Email", true);
}
you can authenticate your request by following code.
WebSecurity.Login(LoginName, Password, true)
once authenticated successed , you will get value of WebSecurity.IsAuthenticated is true and you will get user's identity
you can also use "SimpleRoleProvider" for manage roles in your application