How to create a permanent access token for a StrongLoop API. Now for every user login it creates an access token. And unnecessary entry in my db
I can increase the validity of access token(ttl) as mentioned here.
But still it will generate for new login.
Loopback has an option that will allow you to create a permanent access token:
allowEternalTokens Boolean Allow access tokens that never expire.
https://loopback.io/doc/en/lb3/Model-definition-JSON-file.html#advanced-options
Here's what I did:
Enable allowEternalTokens for the User model
In server/model-config.json:
"User": {
"dataSource": "db",
"options": {
"validateUpsert": true,
"allowEternalTokens": true
}
},
When logging in, set ttl to -1
User.login(
{
email: email,
password: password,
ttl: -1,
},
As you've already figured out, every time you log in a new (different) access token will be created. So if you want to reuse the same access token, log in only once. You can get the access token from the AccessToken model (or directly from the database)
AccessToken.findOne(
{
where: {
userId: userId,
},
},
If you have a custom user model, you can set allowEternalTokens directly in the model definition file. In addition, if you have a custom user model you'll also need to update the relations of the AccessToken model (either the built-in one or your custom one if you have it) to point to the custom user model.
More info on custom user/access token models here: http://loopback.io/doc/en/lb3/Authentication-authorization-and-permissions.html#preparing-access-control-models
You are mixing up 2 different things. The AccessToken entry creation and the ttl value for the AccessToken.
When a user logs in a new AccessToken is created. If the user logs out the AccessToken is removed. If the user logs in 2 times, for example from 2 different devices, then you will get 2 AccessTokens, so this way the user will be able to access your app from the 2 devices simultaneously.
If the user wants to log in from the same device and he already has a valid token, your app should recognise this and log him in automatically.
Obviously if the ttl value is expired, the token will not be valid any more. This token will be removed if is tried to be used. I guess if you don't want this records in your database, you could create a custom cron job that removes expired tokens.
Regarding the permanent access token, it will require to disable the ttl value, and that is not possible at the moment for the default AccessToken model. I created a pull request to support that, if you are interested you could chime in and see if it gets merged.
Related
I'm working on a project where tickets are assigned to users based on their presence in Slack. This presence can be Active or Away, but one can also manually set this presence to Away. A clever user can manually set his or her presence and avoid being assigned work. This is something I would like to avoid.
For the moment I use the users.getPresence method which works fine, but I would like to retrieve the "true" presence of users.
The users.getPresence documentation page has the following info:
If you are requesting presence information for the authed user, this method returns the current presence, along with details on how it was calculated:
{
"ok": true,
"presence": "active",
"online": true,
"auto_away": false,
"manual_away": false,
"connection_count": 1,
"last_activity": 1419027078
}
This method provides information regarding the connection count and if a user has manually changed his status to Away. My assumption is that, using this information, I can see if a user is online but he is being sneaky.
However, I have no idea how to retrieve this information. What is this 'authed' user and can you only get this information for this user?
Furthermore, I accidentally retrieved this 'extended' getPresence data when I send a request to my app using an email address as input, instead of a Slack ID. However, the response is always the same:
{
"ok": true,
"presence": "away",
"online": false,
"auto_away": false,
"manual_away": false,
"connection_count": 0
}
It doesn't matter if I'm active or manually away, the response is always the same.
Has anybody here figured out how this 'extended' getPresence works? I would love to know you did it.
If anybody has an idea on how to retrieve the "true" online status in Slack, please let me know :D
Authed user is the user that allowed their account data to be accessed, it is a breach of privacy for the API to allow an application to have access to user's "true" online status when they obviously do not want it known and have not consented to it.
How do you guys deal with the same user on multiple devices? Won't data such as {admin: true} become stale except for the device that changed it?
Should this even be in a JWT? If not, and we resort to only putting the user ID, won't that be just like a cookie-based session since we store the state on the server?
The JWT RFC establishes three classes of claims:
Registered claims like sub, iss, exp or nbf
Public claims with public names or names registered by IANA which contain values that should be unique like email, address or phone_number. See full list
Private claims to use in your own context and values can collision
None of these claims are mandatory
A JWT is self-contained and should avoid use the server session providing the necessary data to perform the authentication (no need of server storage and database access). Therefore, role info can be included in JWT.
When using several devices there are several reasons to revoke tokens before expiration, for example when user changes password, permissions or account deleted by admin. In this case you would need a blacklist or an alternative mechanism to reject the tokens
A blacklist can include the token unique ID jti or simply set an entry (sub - iss) after updating critical data on user (password, persmissions, etc) and currentTime - maxExpiryTime < last iss. The entry can be discarded when currentTime - maxExpiryTime > last_modified (no more non-expired tokens sent).
Registered Claims
The following Claim Names are registered in the IANA "JSON Web Token Claims" registry established by Section 10.1.
iss (issuer): identifies the principal that issued the JWT.
sub (subject): identifies the principal that is the subject of the JWT. Must be unique
aud (audience): identifies the recipients that the JWT is intended for (array of strings/uri)
exp (expiration time): identifies the expiration time (UTC Unix) after which you must no longer accept this token. It should be after the issued-at time.
nbf(not before): identifies the UTC Unix time before which the JWT must not be accepted
iat (issued at): identifies the UTC Unix time at which the JWT was issued
jti (JWT ID): provides a unique identifier for the JWT.
Example
{
"iss": "stackoverflow",
"sub": "joe",
"aud": ["all"],
"iat": 1300819370,
"exp": 1300819380,
"jti": "3F2504E0-4F89-11D3-9A0C-0305E82C3301"
"context": {
"user": {
"key": "joe",
"displayName": "Joe Smith"
},
"roles":["admin","finaluser"]
}
}
See alternatives here https://stackoverflow.com/a/37520125/6371459
Hello i'm kinda new to laravel and i have a question concerning authentication. I have the following function in my authentication controller:
public function signout()
{
// set logged in status to zero in database
$l = Login::where('user_id', Session::get('user')->user_id)
->where('logged_in', 1)->first();
$l->logged_in = 0;
if ($l->save())
{
// log user out
Auth::logout();
// Forget user session data
Session::forget('user');
// redirect user to login page
return Redirect::to('/account/signin');
}
}
Now in my session config, i have set sessions to expire after 60mins after which the user will obviously be logged out of the system. However that will occur without my other functions executing like setting user logged in status to zero in database or forgetting the user session array. Is there a way i can trigger those functions to execute after login session expire? Thank you in advance.
Update: I've been looking around again ever since i got a down vote for my question to see if there was already a solution to this, from reading the docs i got excited when i came to the "Events" section because i thought i had found a solution however i found out later on that there was no such thing as a "Session::expire" event in laravel, neither is there a function to check whether another user is logged in or not.
Your whole premise is wrong: sessions should have an expiry timestamp that's set when user logs in, and updated on every request if you want to have something like "session times out after 1h of inactivity".
Then you can basically:
Check if session is still valid when user performs a request, by checking the timestamp
Delete expired sessions using a scheduled task, so you keep things clean and tidy in the background
Anyway, if for some reason you end up needing to trigger some actions to happen when a user signs out Laravel actually has an Event that's triggered on user logout: 'auth.logout'
In the latest Meteor release (version 0.5.8), Session has been removed from the server-side code.
Previously I've used Session to store client-specific variables for the server; what is the replacement for this functionality?
Example case: User One opens a browser, User Two opens a browser. One calls a method on the server setting some token, the other calls a method on the server doing the same. I then need to access this when the client requests something. How do I differentiate between the two?
You'll want to save your tokens to a collection in the database.
You could use a Session on the server if you wanted to simply by copying the session package into your application's packages directory and changing its package.js to also load on the server. But a Session is an in-memory data structure, and so won't work if you have multiple server instances; and you wouldn't be able to restart the server without losing your user's tokens.
If you store your tokens in the database they'll persist across server restarts, and will work with a future version of Meteor which is able to scale an application by adding more server instances when needed.
If you need to expire your tokens (so that your collection doesn't grow without bound), you could add a "lastUsed" Date field to your token collection, and periodically remove tokens that haven't been used for longer than your chosen expiration period.
You can use each one's session id which is unique to the tab too. Not too sure how to get the current session id but it should be there somewhere (you can see it in Meteor.default_server.sessions, so there is still a way:
Client js
Meteor.call("test", Meteor.default_connection._lastSessionId, function(err,result) {
console.log(result);
});
Server side Js
Session = {
set : function(key, value, sessionid) {
console.log(Meteor.default_server.sessions[sessionid]);
if(!Meteor.default_server.sessions[sessionid].session_hash) Meteor.default_server.sessions[sessionid].session_hash = {};
Meteor.default_server.sessions[sessionid].session_hash.key = value;
},
get : function(key, sessionid) {
if(Meteor.default_server.sessions[sessionid].session_hash)
return Meteor.default_server.sessions[sessionid].session_hash.key;
},
equals: function(key, value, sessionid) {
return (this.get(key, sessionid) == value)
},
listAllSessionids: function() {
return _.pluck(Meteor.default_server.sessions, "id");
}
};
Meteor.methods({
test:function(sessionid) {
if(!Session.get("initial_load", sessionid)) Session.set("initial_load", new Date().getTime(), sessionid);
return Session.get("initial_load", sessionid);
}
});
I hook into Meteor.default_connection._sessions to store the values so that theres some type of garbage collection involved when the session isn't valid anymore (i.e the user has closed his tabs) to prevent memory being wasted. In livedata_server.js these old sessions get destroyed after 1 minute of no activity on the DDP wire (like the heartbeat).
Because the server can see everyone's session you can use the sessionid to access another user's session data. and listAllSessionids to give out an array of all the sessionids currently active.
Automatically set session like this.userId in a Method without using a param in a call
It looks like there is functionality for this this but its not fully hooked up. The session id would be stored in this.sessionData but its likely still unfinished. Its there to be called in method but theres nowhere that its being set yet (in livedata_connection.js & livedata_server.js)
I have only ever made single page webapps in the past; with these, as soon as a user connected, I would read the password hash stored in their cookies and match it to the value stored in my database to determine if the user was already logged in.
I am now wanting to make a site with multiple web pages though, and I have just realized that it would required querying the database every time a user goes to a new page; this seems extremely inefficient to me. Is there any better way to maintain an ongoing session with a client without straining my database/server in the process?
Take a look at using a session object Eg HttpContext.Session["UserAuth"] = true;
When you authenticate the user on your first page Eg Login, you can then create a session like in the example above. Then once you redirect to the next page, just check to see if the session does indeed exists and is valid.
Checking session:
if(HttpContext.Session["UserAuth"] != null)
{
if(HttpContxt.Session["UserAuth"].toString() == "true")
{
//Session is valid and user is logged in.
}
else{
//Session is invalid and user is not logged in.
}
}
So each page you want to check if the user is valid you can do the above check. As long as you have created the session on the first page at time of database authentication.
Please note the above code is just to give you an idea of how you can do this.
"UserAuth" is simply a the name you give to the Session that you are storing. It can be absolutely anything. The value you are storing in the Session in this case is 'true'.
So when you retrieve the value of the Session you simply get 'true', meaning the user is logged in.
When you log the user out for example you can change the value of the session "UserAuth" to false in the same manner in which you originally created it.
Eg
HttpContext.Session["UserAuth"] = false;