iOS: How to authenticate a user after login (for auto login)? - iphone

I'd like to use an auto-login function. So when the user opens the app, he gets delegated to a "login screen". When he logged in successfully he should be directed to his account. I call this the "account screen". Now when the user restarts the app, he should directly get directed to his account, without seeing the "login screen".
The login function already works fine in my project (username and password are saved in UserDefault), but every time I close the app, I have to login again. So my question is: How do auto login the user? Or better said: How do I check if the data (saved in UserDefault) is the same as in the database (MYSQL)?

For the first time when the user login, you save the user
credentials in iPhone's keychain.
When the app is opened again, you check whether user credentials are
present in keychain and if yes, you code should call the login
logic and do auto login and go to screen after login screen. If no,
then you should show login screen. You can do this logic in AppDelegates applicationDidFinishLaunching.
Whenever user clicks the logout button, remove user credentials from
keychain first, and go back to login controller.
Simply you add login credentials to keychain when user logs in and only remove it once user clicks the logout button. If user quits the app without logout then the credentials will still be in keychain and you can retrieve them when user returns to the app.
EDIT: I think I must add one more thing..If your login logic takes time (like you login using web request or something), put the login logic code in your Login ViewController rather than ApplicationDelegate, and use any Activity Indicator during auto login process.
EDIT : I edited the entire answer, replaced NSUserDefault with Keychain. This thread explains why.

While saving Username and Password, it is highly advised to save in Keychain rather than the NSUserDefaults. Refer this post for a better understanding.

To answer the question: if you want to auto-login with keychain data, use the free framework "SFHFKeychainUtils". It saves username, password and servicename in keychain. if you want to retrieve it, just save the username in NSUserDefaults and you can get the password with ease.
Here we go:
SiFi HiFi Framework: https://github.com/ldandersen/scifihifi-iphone/tree/master/security
SiFi Hifi Framework (ARC compatible): https://stackoverflow.com/a/10348964/1011125
How to use SFHFKeychainUtils: http://gorgando.com/blog/technology/iphone_development/simple-iphone-tutorial-password-management-using-the-keychain-by-using-sfhfkeychainutils

I used a combination of NSUserDefaults and SSKeychain. I used NSUserDefaults to store the username nad SSKeychain to store the password.
This is the code I used to save the credentials
NSString *user = self.username.text;
NSString *password = self.pass.text;
[SSKeychain setPassword:password forService:#"achat" account:user];
NSUserDefaults *dUser = [NSUserDefaults standardUserDefaults];
[dUser setObject:user forKey:#"user"];
[dUser synchronize];
This is the code I used to retrieve the credentials
NSUserDefaults *eUser = [NSUserDefaults standardUserDefaults];
NSString *savedUser = [eUser objectForKey:#"user"];
if (!savedUser) {
UIAlertView *uhoh = [[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Please enter your username and password." delegate:self cancelButtonTitle:#"Okay" otherButtonTitles:nil, nil];
[uhoh show];
}
else {
NSString *savedPass = [SSKeychain passwordForService:#"achat" account:savedUser];
self.username.text = savedUser;
self.pass.text = savedPass;
}

Related

One login view, sign up or login

I want to be able to have just one login screen. The user will enter the username, email and password every time they login. I am having the problem where I sign up, logout and then try to login using the same credentials and I just get an error back saying that the username is already taken. How can I just log them in if they give me the correct credentials?
PFUser *user = [PFUser user];
user.email = emailEntry;
user.username = nickNameEntry;
user.password = passwordEntry;
[user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (!error)
{
[MYAlertView showAlertWithTitle:#"Successful login"
message:#"success"
cancelButtonTitle:#"OK"];
}
else
{
NSString *errorString = [[error userInfo] objectForKey:#"error"];
[MyAlertView showAlertWithTitle:#"There was an error signing up."
message:errorString
cancelButtonTitle:#"OK"];
}
}];
If user needs to sign up (first time), you need to use –signUpInBackgroundWithBlock:, as you are doing.
However, if he is already signed up, I guess you should use +logInWithUsernameInBackground:password:block:.
I'm getting this infos from this page, however, I never used this SDK.
The easier way to do that is :
Having two buttons, that pushes different view controllers, one for signing up, the other for logging in
The same form, and two buttons, one which calls a methods that calls –signUpInBackgroundWithBlock:, and the other that calls +logInWithUsernameInBackground:password:block:.
With the second solution, the problem is that if you have the same form, you can't ask special informations (name, date of birth, etc.) on sign up.
EDIT :
You might want to have a look at :
PFSignUpViewControllerDelegate,
PFLoginViewControllerDelegate,
Parse API Documentation (where I've found the two links above).

storing username and password in session iphone

I want to store username and password in a session , if a user login successfully then he will be directed to the welcome screen where a logout button is exist.
now if user close the application without log out the account and restart the app the he must be directed to the welcome screen skipping the login screen. and if user restart the app after logout then he must enter the username and password to come on welcome screen. help me out. i am new to iphone.
you may store the username and password in User Defaults or in Keychain (if want to keep it secure ). So on loading the app if you find username and password stored in Userdefaults , you may directly login to welcome screen and if not stored then show the login screen...
see this is the same as you want help with iphone session login
you can store whole array in the Userdefault, UserDefault is a one type of session in the iPhone...
here you can store any value or array in the UserDefaul..
In AppDelegate.h file just declare variable...
NSUserDefaults *userDefaults;
here it not compulsory to global declare this userDefault, you can direct use the userdefault where you want
after...
In AppDelegate.m Fille in applicationDidFinishLonching: Method or anywhere which you want to store username and pssword
userDefaults = [NSUserDefaults standardUserDefaults];
[userDefault setObject:yourName forKey:#"UserName"];
[userDefault setObject:yourPassword forKey:#"Password"];
[userDefault synchronize];
after that when you want get data from this UserDefaults Use Bellow Code...
NSString *userName = [[NSUserDefaults standardUserDefaults] valueForKey:#"UserName"];
NSString *password = [[NSUserDefaults standardUserDefaults] valueForKey:#"Password"];
i hope this helpful to you...
:)

How to implement log in and Log out in an app

I am using XCode4 for development.
In my applicaion I need login to a website to get the information. then by using that I have to perform some task.
I am accessing the website by REST service call. After the ASIHttpRequest passed
I am setting the user name & password like this.
[request setuserName:#"usernameString"];
[request setpassword:#"Passwordstring"];
But I am not aware of whether any session created or not.
So at the time of log out I only redirect the controller to log in screen & made the userName and password field blank.
But after logout it is taking wrong user name and password to login again.
My question:
Whether I have to create a session while log in and time out the session at the time of log out. How to do that?
In iphone application how Log in & Log out generally done?
you best choice will be using NSUserDefaults class, example:
// saving your data.
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
[standardUserDefaults setObject:myUsername forKey:#"username"];
// retrieve your data
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *username = [standardUserDefaults objectForKey:#"username"];
you can also use NSUserDefaults to store the Log in status of the current session by for example storing a Boolean key for isLoggedIn key
[standardUserDefaults setBOOL:TRUE forKey:#"isLoggedIn"];
When the user wishes to log out just set the value to FALSE to offer the user the log in view again as if this is the first time the user is using the app.
You don't need to set timeout session for the logged in users, unless your design or the requirements said so, but you can also do that easily by using NSUserDefaults by storing the date and time of the user log in, and check that continuously to validate the session timeout, but I don't recommend to do such a thing, but everything is possible here.
Thanks all. This problem is solved.
At the time of log in, ASIHTTPRequest is creating a cookie object on successful log in. If a user did not spend 1 minute inside the application and came out by tapping sign out. After that it was taking any userId and password (garbage data) to login again. It happened because the previous cookie was taking care for that.
But, now at the time of sign out, I am deleting the cookie which is created at the time of log in.
I have added below code in sign out:-
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie *each in [[[cookieStorage cookiesForURL:YOUR_URL] copy] autorelease])
{
// NSLog(#"cookie deleted==%#",each);
[cookieStorage deleteCookie:each];
}
AhmadTK's answer is fine, just a couple of points:
Always make sure you call [standardUserDefaults synchronize]; after setting values.
Initiate a check of the isLoggedIn item when the application starts, and if false, present the login screen for the user
Handle the logout process in the reverse (set the isLoggedIn value to NO)

How to use NSUserDefaults for creating the auto login settings for application

I know this very regular question But i didn't get that's way ask here I hope people will me out .
I have application which have the login page .And when ever I login I get Token_ID from server .I get this TokenID with help of JSON.
But I want to add the Auto Login function to my application .For that My application look like this
It has the two text field (username and password)
one check box for auto login And login button
I need when ever user click on the check box which is for auto login It must store TokenID in application and when I close my application .And start the application again It must not ask for login me again.It start the same application with same TokenID which I store for that user not a new one .And if I click the log out button it must logout from application And release the TokenID from my application .And after that if start the application it must ask for login with out that it must not go further in application
For that I do R&D from two days .And I found that I must use the NSUserDefaults for storing the TokenID which I am getting at the time of login .I want know how can I store the TokenID
into application and How can check it out the user logout or not .And if user not logout it start the application.And if user logout than it must ask for login to start the application
OR is that any idea please give And explain me
Thank you
First result at google for "NSUSerDefaults Example"
On logout just overwrite the keys with nil and check on starting of the app if the key is nil
you can save username information
-(void)saveToUserDefaults:(NSString*)myString
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
if (standardUserDefaults) {
[standardUserDefaults setObject:myString forKey:#"username"];
[standardUserDefaults synchronize];
}
}
if you have username information on NSUserDefaults, you can get your username information
-(NSString*)retrieveFromUserDefaults
{
NSUserDefaults *standardUserDefaults = [NSUserDefaults standardUserDefaults];
NSString *val = nil;
if (standardUserDefaults)
val = [standardUserDefaults objectForKey:#"username"];
return val;
}

How to keep me logged in with facebook connect on iPhone?

Hey, I am using facebook connect sdk for iPhone, every time I start my app and click login, there would be a login screen asking me to input my name and password.
Is there any way to keep me logged in once I input my name and password, that's to say, I needn't to input my name and password again the next time I start my app?
According to the Platform Guidelines 1.3, you are not allowed to store a Facebook user's credentials. The best you can hope for is that your user checks the "Keep me logged in" option. She should be able to post without having to login any time soon, even if she restarts your app.
The following snippet works with the above scenario:
NSString *fbAPIKey = ...;
NSString *fbApplicationSecret = ...;
_session = [[FBSession sessionForApplication:fbAPIKey secret:fbApplicationSecret delegate:self] retain];
// checks whether session can be resumed - whether login is required
if (![_session resume]) {
FBLoginDialog *loginDialog = [[[FBLoginDialog alloc] initWithSession:_session] autorelease];
[loginDialog show];
}
Store the password (or the requisite hash of it) somewhere.
You need to use the keychain. Have a look to this article: http://log.scifihifi.com/post/55837387/simple-iphone-keychain-code