Introduction
Here, I will explain about how to implement Foursquare
authentication in ASP.NET MVC. In order to use Foursquare
API in our web application, first you need to create an application in Foursquare Developer Page. The following are the steps to follow to create an application in Foursquare
.
Step 1: Create Your App to Obtain Its Foursquare API Credentials
Foursquare
Once your app is created, Client ID, the Client Secret API credentials will be generated so that we can use them for the authentication.
Step 2: Implementing Authentication
Create a login button with Foursquare
logo, which will be found here. Now we are using the OAuth 2.0 flow for the user authentication. We will direct users to the following url for login:
https://foursquare.com/oauth2/authenticate?client_id=YOUR_CLIENT_ID
&response_type=code
&redirect_uri=YOUR_REGISTERED_REDIRECT_URI
If the user accepts, they will be redirected back to:
https://REDIRECT_URI_APP/?code=CODE
Once we get the code, we will exchange the code for an access token. To get the access token, we should make a request for the following URL:
https: &client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code
&redirect_uri=REDIRECT_URI
&code=CODE
Now, we will use the above flow in ASP.NET MVC.
<a href="https://foursquare.com/oauth2/authenticate?client_id=CLIENTID
&response_type=code
&redirect_uri=http://localhost:51361/home/index">
<img src="~/Content/foursquare.png" />
</a>
Once the user authenticated, use the following code to get the access token:
public ActionResult Index(string code)
{
if (!string.IsNullOrEmpty(code))
{
WebClient client = new WebClient();
string reply =
client.DownloadString(
"https://foursquare.com/oauth2/access_token?
client_id=ZWZW4WMV13ZIXF1QODU0QNBU2PWNCCTNRA4NQSLREBE41BIY&
client_secret=IWQI2YGXNZX21NXAUZRDOLOHZTQVXPH3FHTIWXBETMXAEBFE&
grant_type=authorization_code&redirect_uri=http://localhost:51361/home/index&code=" +
code);
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<Dictionary<string, string>>(reply);
Session["access_token"] = dict["access_token"];
}
return View();
}
Save the access token in a session. Once you have an access token, it is easy use any of the endpoints, by just adding oauth_token=ACCESS_TOKEN
to your GET
or POST
request.
Get the user profile using access token:
var acessToken = Session["access_token"];
WebClient client = new WebClient();
var reply =
client.DownloadString(
"https://api.foursquare.com/v2/users/self?oauth_token=" +
acessToken + "&v=20141112");
The post Implement Foursquare authentication in ASP.NET MVC appeared first on Venkat Baggu Blog.