How to get Session ID in Swift 3 - ios

I made a login application with 2 text field username, password and web view for after login. Here url
var request = URLRequest(url: URL(string: "https://website.com/tr/webservicelogin?_username=\(vc.username)&_password=\(vc.password)&status=login&mobil=true")!)
When I enter the username and password these are display session id on webview page. I want to get this session id from cookie after login. Any idea?

The backend is the one who is responsible for session management. When you are requesting the backend for login, backend creates a session for you and passes you the session identifier back. Since this moment, your other requests inside your client headers should contain session identifier, according to which backend identifies session user.
Apple has created NSHTTPCookieStorage API for managing that in a client side: API Reference.
In case you are creating a sample login application, you shouldn't mess with cookies.
P.S. You don't want to send user credentials unencrypted (security violation).

Related

Sharing a session between a WKWebView and Safari

I have an iOS app that authenticates for api access and I have a request to throw the user into safari, not a WKWebView but still keep them authenticated.
Is there anyway to securely share the session between an iOS app and full safari?
I have looked into WKProcesspools but I am not sure that will quite do it.
Not sure about WKProcesspools, but you can share the session using Query parmaters.
Format your weburl to include verification token as a query parameter.
When you verify user via API, you must get the token from response. Pass this token as a query parameter in your url and redirect to Safari.
URL - https://www.example.com/page1
URL with token - https://www.example.com/page1?token=asdfv12324fvfropfc23as
Extra care to prevent copy/paste of token:
When creating token, pass IP Address or MAC Address as parameter of your API and based on these addresses you can check if the request is coming from same address. This will take care of the device authentication.

Refresh token with Twitter API

I'm wondering if Twitter has an API endpoint that exchanges an expired access token with an active one. The way that I have the login flow working right now goes something like this.
// Request a token and redirect to the authorization page
$token = $this->twitter->getRequestToken();
// Set the session data
$this->session->set_userdata('oauth_token', $token['oauth_token']);
$this->session->set_userdata('oauth_token_secret', $token['oauth_token_secret']);
// Redirect the user to the authorization page
header('Location: https://api.twitter.com/oauth/authorize?oauth_token='.$token['oauth_token']);
The page that the user is redirected to will prompt the user to authorize my app each and every time they want a valid access token. Upon accepting the authorization, the user will be redirected to the callback URL. At my callback URL, the following happens
// Get the parameters from the URL
$token = $this->input->get('oauth_token');
$verifier = $this->input->get('oauth_verifier');
$oauthToken = $this->session->oauth_token;
$oauthSecret = $this->session->oauth_token_secret;
// Get the access token
$access = $this->twitter->getAccessToken($verifier, $oauthToken, $oauthSecret);
Does such a way exist for an access token to be generated without having to authorize my app each and every time?
According to Twitter's OAuth FAQ, tokens don't expire unless a user explicitly rejects your application or an admin suspends your application.
If you want your users to be able to login repeatedly without having to reauthorize, you'll need to come up with a mechanism for storing the tokens (cookies, database, etc.).

check if user session has expired asp web api

I am experimenting in developing Single Page Application using Asp Mvc 4 / Web Api and angularjs.
I am using the mvc controller actions to return views and web api actions to return json.
As the web api part is restfull and it has no state, I am wondering how to check if a user session has expired. For example: a user is clicking on a button and this leads to request to the web api action to get some json data. But when the request hits the server I want to check if the user session has expired.
As I said I am rather new to this combination of technologies and I am wondering how can this be achieved. Any example will be greatly appreciated. Thanks in advance.
Web API introduced an Attribute [Authorize] to provide security. This can be set globally (global.asx)
public static void Register(HttpConfiguration config)
{
config.Filters.Add(new AuthorizeAttribute());
}
Or per controller:
[Authorize]
public class ValuesController : ApiController{
...
If your user is authenticated(session has not expired) the service will work normally if not an http 401 unauthorized is returned.
This is how I did it in my project: First instantiate a session on client sidei.e in your MVC Application if the user logs in , once the session is created,with each request you should add a unique identifyable token or session id in the header of your WebApi request which you are going to send, If the user sends a request without logging in there would be no token present in the header of the request.
If in your service you get an authentication token which you can verify, that means the request is authenticated and hence session was still in place otherwise the user sent the request without a session in place and hence no token present in the header of the request.
You could add headers with your request like this :
HttpClient httpClient = new HttpClient();
// Add a new Request Message
HttpRequestMessage requestMessage = new HttpRequestMessage(...);
// Add your custom headers
requestMessage.Headers.Add("authToken", "SessionId");
or
requestMessage.Headers.Add("authToken", "encryptedUsername:encryptedPassword");
And then in your WebApi Service read those headers, if you can uniquely identify or verify the authToken then that means the session was in place else unauthenticated request , generate an error response.
I dont know if this is the best practise or not but I did it this way. I actually store the encrypted username & password in my session and attach it with every request and in my WebApi I extract these header values and recheck them with my database and then further process the request. I know many people would not be too much happy about storing passwords in the session but I think its not that bad, they are in encrypted form atleast. Rest is upto you , you could store a sessionId instead or a unique identifier or a flag that may indicate that the session was actually in place and request is authenticated.

How do I retrieve user based on session token in the Parse REST API?

Using the Parse REST API, once I have authenticated a user with username and password, I get a session token. I store that session token in the user's cookie's, but how do I fetch a user with that session token?
My web app is in Ruby on Rails. I'm using gem parse-ruby-client.
Parse::User.authenticate('cooldude6', PASSWORD)
returns
{"username"=>"cooldude6",
"createdAt"=>"2013-01-31T15:22:40.339Z",
"objectId"=>"2bMfWZQ9Ob",
"sessionToken"=>"zrGuvs3psdndaqswhf0smupsodflkqbFdwRs"}
How do I then use that sessionToken to retrieve the current user from Parse?
Either query the _User table (endpoint: /1/users) for the user with the "cooldude6" username, or get the user directly with its object id (endpoint: /1/users/2bMfWZQ9Ob). You'd only use the session token to authenticate REST API requests as the user via the X-Parse-SessionToken header, which would let you read and write data based on the user's ACL.
You can validate a session token by making a GET request to the /1/users/me endpoint with the token in the X-Parse-Session-Token header. I’m unfamiliar with that Ruby gem, but perhaps you could use one of its User queries?
However you make the request, Parse will return the full user object if the session token is still valid, or {"code":101,"error":"invalid session"} otherwise.

OAuth 2.0 for MVC - How does the RequestToken work?

I'm working with OAuth 2.0 for MVC, found here: http://community.codesmithtools.com/CodeSmith_Community/b/tdupont/archive/2011/03/18/oauth-2-0-for-mvc-two-legged-implementation.aspx
For anyone who's worked with this - I'm confused about the RequestToken. There is a controller implemented that lets you get a request token, which expires in 5 minutes, and you pass that token back in to get an AccessToken. But it never checks the request token for validity - it seems like you can pass in any access token you want to. What is the idea for the RequestToken here - are you supposed to create your own method of storing, referencing, and then deleting that token for those 5 minutes?
Thanks,
Andy
This is all about how OAuth works in conjunction with your application Id, application secret key and valid domains for your application. Here is the process in general
Your application sends a request to the OAuth provider using your application Id and secret along with a callback (return Url).
The OAuth provider gets the request, checks your application Id and secret and validates that the callback url is from a domain that you have specified for your application.
2a. If the callback url is not from a domain that you have specified, then the request is rejected with error.
2b If the callback url is from your domain, it returns a temporary request key to your server.
Given that you received a request key, you send that back to the OAuth provider to get the actual access token for the user.
Now, as to why the request key step is in place, this is to prevent and help protect 'bad people' from attempting to use your application id to falsely authenticate other users. By sending the request token to you (a callback URL that you have approved), the OAuth provider has confidence that the request actually came from your servers.
You most certainly could send any string back instead of the request token, but you would quickly get an error back from the OAuth provider as that request token does not correspond to any existing authentication request from any known application.
Lastly, I am not clear on what you mean by 'validating the request token'? You did not generate the token not probably do not have insight into the algorithm to generate the request token. Given that, I am not sure how you would validate this. If you are concerned about validating the first step, take a look at the Facebook OAuth process. In there, they recommend sending a request key as part of your return Url(as a query string parameter). That request key will come back to your application which you could then use as a validation that, indeed, this is a response to a request that you made. How you store and track that request key is up to you (session, database). In the PHP samples, they use a 'state' variable to track a unique/arbitrary string: Facebook OAuth Server Side Login Example (in PHP)

Resources