Integrate OpenAuth/OpenID with your existing ASP.NET MVC4 application

In this blog I am going to talk about how to integrate OpenAuth/OpenId with your existing asp.net mvc4 application in Visual studio 2012

Step 1: Create a new project

Go to File –> New Project –> Web –> Empty Asp.Net MVC 4 Application

Step 2: Add the following libraries

  • Use Nuget to get the following packages
    • DotNetOpenAuth.AspNet
      • This package is the core package for OAuth/OpenID protocol communication
    • Microsoft.AspNet.Providers.Core
      • This package brings in Universal Providers
    • Microsoft.AspNet.Providers.LocalDb
      • This package sets the connectionstring for the Universal Providers
    • Microsoft.AspNet.Membership.OpenAuth
      • This package provides the extension to integrate OAuth/OpenID with Membership providers

Step 3: Change web.config to use formsauthentication

Step 4: Adding AuthConfig

Add a new class called AuthConfig.cs to folder App_Start that class will contains the register functions for all services that we will integrate

Add the following code to AuthConfig.cs and don’t forget to get services Api keys from each service website

Register AuthConfig to application start Go to Global.asax and add the following line to Application_Start function

Step 5: Adding Login functionality

Add a new controller for Authentication functionality called it AuthController.cs
add Logon Action for login page

as you can notice that we user OAuthWebSecurity.RegisteredClientData as a model that object will contain all registered services that we put at AuthConfig class. Add a markup for login page

as you can notice that we are looping against the services that we already registered in a previous step each AuthenticationClientData represent a service so we create a button to call that service we are adding all the buttons inside single form that calling ExternalLogin action method

add ActionMethod ExternalLogin

as you can notice its a void action. we are using OAuthWebSecurity.RequestAuthentication this function is requesting the authentication from the requested provider service “Facebook – Twitter – etc.” then it returned to The URL to return to when authentication is successful. we are mentioned “ExternalLoginCallback” as a returned back action

First: we have to verify authentication to ensure that the account is successfully authenticated if not redirect users to ExternalLoginFailure action if user is authenticated then we are going to login user to the system using simple membership we are going to talk about that in later posts then check if the current user is logged in add the new account else user is new, ask for their desired membership name then redirect to ExternalLoginConfirmation action with user information at RegisterExternalLoginModel class

RegisterExternalLoginModel

Finally: your application is ready to give it a test

You can download a sample from here

Google Charts with MVC3

In this blog I am going to talk about how to add the powerfull Google Charts to your asp.net MVC 3 Application. Google Chart Tools provide a perfect way to visualize data on your website. From simple line charts to complex hierarchical tree maps, the chart galley provides a large number of well-designed chart types. Populating your data is easy using the provided client- and server-side tools.

Step 1: Create a new project

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application

Step 2:Javascript files and libraries

add the following javascript files to head of your page

Step 3: Add Client Javascript and Html

Note here we are making an ajax request to “/Home/GetData” to get data from server and assign data to google chart api

Step 4: Add ServerSide

That’s all. You can download the sample from here

Working examples using Signalr and asp.net MVC3

In this tutorial  I am going to talk about a real examples that we need to implement in most of projects.

Step 1: Create Application

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application “Internet Application” (Make sure it’s .Net Framework 4).

Step 2: Add SignalR Package

Right click on references and click Manage NuGet Packages. Search for SignalR and click install. Or use NuGet package manager concole and install the SignalR package using

Step 3: Add Hub

Create a new Class named Chat in a new folder in the solution “Name it as u want”

Note the attribute HubName above the class name, that attribute is for naming the hub during calls as we going to see later

Step 4: Add Sending Functions

You can notice that the function has three parameters a required parameter message,two optional parameters clientId and group so if we need to send message to all users live in the application we can send only message to send function and leave, if we need to send message to only one user all we have to do is to add client id with message if we want to send a message to a specific group send group name with message only

Step 5: Change user Id

the main problem for us now is the client id, Because it is changeable with each single request to the page so we need to identify users so we can add to helpers the following helper class that will help us to resetting the connection id in hub

because i am using membership to login and security i used membership.GetUser function to get user id. Remember id here is a Guid so if you are using your own implementation and not using membership you have to generate a unique Guid id for each person.

Step 6: Register new user id to Application

Now we have to register the newly generated user id to the application we are going to add the following code in Global.asax

Now in application start and while user opened a new session to your application the new Id we just made will be assigned to him and we can ue it to identify each user and send.

Step 7: Adding user to group

To add user to group i used action method in my HomeController to do that work

Step 8: Add client code

Append javascript references to the head of the page as follows

As you can notice there is a /signalr/hubs file included but its not in the project because its dynamically generated file in run time

Append the following javascript

I added commented lines above each line to declare how it works.

Append the following Html to your page

You can download the sample code from here

Creating RSS feed in ASP.net mvc3

In this toturial we are going through steps to create rss feed from a list of items using .NET’s built in SyndicatedFeed and SyndicatedItem class for content and two classes (Rss20FeedFormatter and Atom10FeedFormatter )  to handle XML generation with correct encoding, formatting and optional fields.

  1. Create an empty mvc3 application and name it “RSSFeed.Website” then add Home controller.
  2. Create a class and name it NewsItem  this class we will be used as a model for retrieving feed data from the database “i will fill it manually in a the next step ”
  3. Optional step, Fill in NewsItem list if you have items in database so there is no need to fill the list like that you can get the data from the database and return it in a list of items
  4. We have to build our FeedResult class
  5. We almost done we have to create our rss page so we are going to create an ActionResult called NewsRss in HomeController
  6. we are done now except just putting a link to home to open up our RSS

You can download a sample from here

 

Using Signalr with Asp.net MVC to create simple chat application part II

As we mentioned in the previous example here, we can create a simple asynchronous actions with the signalr library like chat, real-time streaming and so on. in this blog i am going to go with another library from signalr its PersistentConnection. A PersistentConnection is the base class that has an api for exposing a SignalR service over http.

we are going to complete in the the previous application we created

Step 1:Add AdvChatController

we are going to create a new controller called AdvChatController with two action methods Index and Adv. then add index view

Step 2: Create Signalr PersistentConnection

Create a class the derives from PersistentConnection

Step 3:Setup Routing

Make a route for your connection in Global.asax

If you are setting up other routes, the SignalR mapping needs to be done before the other ones.

Step 4: Adding receiving functionality in MyConnection

Add the following functions to MyConnection class

here as you notice we can manage the users that are connected to server first on connect action that action will be called when the user connects to the application so we can add the user to a certain group also on disconnect action that action will be called when user leaves the page so we can remove the user from group. also on received function to perform the sending action to certain group

step 5: Adding Client code

Append javascript references to the head of the page as follows

Append the following javascript

Append the following Html to your page

that’s all you can now run the application now in multiple browsers and test it

You can download the sample from here

 

Using Signalr with Asp.net MVC to create simple chat application

In this tutorial I am going to talk about creating a simple chat application using signalr library with asp.net MVC. If we are trying to do a chat application or any asynchronous actions with client so we have a lot of work to do using ajax and javascript. Now with signalr it’s so simple and easy.

Step 1: Create an Empty Asp.Net MVC 3 Application

Go to File –> New Project –> Web –> Asp.Net MVC 3 Application (Make sure it’s .Net Framework 4).

Step 2: Add SignalR Package

Right click on references and click Manage NuGet Packages. Search for SignalR and click install. Or use NuGet package manager concole and install the SignalR package using

Step 3: Add HomeController

Right click on Controllers folder and click Add –> Controller. Then add index view to index action result by right click on index action method –> add view.

Step 4: Create Signalr Hub

Create a class that derives from Hub

Step 5: Adding Client

Append javascript references to the head of the page as follows

As you can notice there is a /signalr/hubs file included but its not in the project because its dynamically generated file in run time

Append the following javascript

I added commented lines above each line to declare how it works.

Append the following Html to your page

And that’s it you can run the application now in multiple browsers and all magic starts

You can download a sample from here

 

Login via Twitter inside your application step by step

In this blog post i am going to explain how to login via twitter inside your web application step by step

Introduction:

  • Twitter uses OAuth to provide authorized access to its information and data which gives
    • Secure – Users are not required to share their passwords with 3rd party applications, increasing account security.
    • Standard – A wealth of client libraries and example code are compatible with Twitter’s OAuth implementation.

Implementation:

  1. Create twitter application in order to connect to twitter with
    1. Go to Create a new application in twitter
    2. After creation completed successfully twitter will redirected to the main application page the most important information is “Consumer key”,”Consumer secret”
  2. Create a new MVC application “if you have already existing application skip this step”.
  3. Open Application Web.config file and add to appSettings section the following
  4. Make sure that Authentication section is configured like that
  5. I’ve created three controllers “if you have already existing application just add the code in the appropriate place in your application”
    1. AuthController: To perform all authentication actions including normal login and login via twitter.
    2. HomeController: Landing page for the application with no Authentication
    3. AccountController:include pages that requires authorization
  6. At AuthController we will create all twitter login functionality
    1. First we need to create loginToTwitter() method which check if the current request is coming from twitter callback or its calling the authentication
    2. if user is authenticated we have to get AccessTokenForTheFirstTime
    3. if user request authorization so we have to redirect user to authorization page in twitter
    4. make sure that after Authorization you have to redirect user again using TwitterCallbackAddress that we specified before in web.config here i am redirecting the user to Auth/LoginWithTwitter action method
    5. then we link that action method with a button in our view
      Explanation: first the user will go to action method LoginWithTwitter for the first time with no “oauth_token”,”oauth_verifier” so user will redirected to twitter login page according to LoginToTwitter function then returns again to the same action method LoginWithTwitter according to the link we specifie in web.config but this time with “oauth_token” and “oauth_verifier” so user will be authenticated according to LoginToTwitter function through getting GetAccessToken function if user authenticated successfully Twitter API will return OAuthTokenResponse in this step we can set user as authenticated user and with getting user information from twitter using GetsTwitterUser function and redirect to AccountController
  7. At AccountController make sure that the controller is Authorized to allow only authorized users to see its content
  8. at Index page in Account use ViewBag To view user Twitter Screen Name

You can download the full sample from here

 

 

How to authenticate to FaceBook Graph Api – Part III

As I mentioned in the previous post we are going to complete how to connect to facebook graph Api programatically

  1. We are going to create a new web application and name it ConnectToFacebook
  2. In Default.aspx page we are going to but the login to facebook button and a label to show up the accesstoken after successfully login
  3. in code behind we implementing the code to connect to facebook
  4. we are going to explain the code we can begin with LoginToFacebook function
    we have to make sure that the user is authorized before getting access token if not so redirect user to authorize the application from facebook. After user authorize the application to access via facebook login page then facebook returned to the application via the return url which we specefied in the authorization url with code as a querystring

    so in page load i make a check on code querystring to make sure if the user loading the page after authorization or not if code querystring is exist so we can call GetAccessTokenFromRequest function,in this function we are going to connect to facebook by reading the stream of httpreqest to facebook and get accestoken and accesstoken time from the request.
  5. I usually store information about my api in web.config to be easy to change in the future if i want to do that, so i used

    to get facebook application id and application secret from web.config that keys which facebook generate after creating a new application as we described in a previous posts also there is scope users only grant your app access to their basic information. If you want to read additional data or write data to Facebook, you need to request additional permissions. In the various authentication flows, you should specify the additional permissions you require using the Scope parameter. so i put it in web.config to
  6. here is an example of web.config

    as we can see in the code sample I used HttpWebRequest and StreamReader to get data from facebook

You can download the sample from here ConnectToFacebook

How to authenticate to FaceBook Graph Api – Part II

As I mentioned in the previous post we are going to complete the basic information on how to authenticate Facebook Graph Api

In this post I will show you how to authenticate users via simple url requests without any programming language just to explain how are things going.
After creating Facebook Application as mentioned in the previous post you can request Facebook authentication dialog as following

https://www.facebook.com/dialog/oauth?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL

When invoking Facebook login dialog, you must pass in your app id that is generated when you create your application that we mention before (the client_id parameter) and the URL that the user’s browser will be redirected back to once app authorization is completed (the redirect_uri parameter). The redirect_uri must be within the same domain as the Site URL you specify in Web site tab of the Developer App that we just mention before.

After invoking Facebook dialog, If the user is already logged in, Facebook validate the login cookie which stored on the user’s browser, authenticating the user. If the user is not logged in, they are prompted to enter their credentials:After user login you will see another facebook screen asks for Application access but this time its your applicationnotice again that your application requests to access just basic information of user . A full list of permissions is available in facebook permissions reference. There is a strong inverse correlation between the number of permissions your app requests and the number of users that will allow those permissions.
If the user presses Don’t Allow, your app is not authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with the following error information:

http://YOUR_URL?error_reason=user_denied&
error=access_denied&error_description=The+user+denied+your+request.

If the user presses Allow, your app is authorized. The OAuth Dialog will redirect (via HTTP 302) the user’s browser to the URL you passed in the redirect_uri parameter with an authorization code:

http://YOUR_URL?code=A_CODE_GENERATED_BY_SERVER

In order to authenticate your app, you must pass the authorization code and your app secret to the Facebook Graph API token endpoint at https://graph.facebook.com/oauth/access_token. The app secret that we get from Facebook Application and should not be shared with anyone or embedded in any code that you will distribute.

https://graph.facebook.com/oauth/access_token?
client_id=YOUR_APP_ID&redirect_uri=YOUR_URL&
client_secret=YOUR_APP_SECRET&code=THE_CODE_FROM_ABOVE

If your app is successfully authenticated and the authorization code from the user is valid, the authorization server will return the access token:

Now you are successfully grant user and have the access token that is required for all the rest Facebook Graph Api needs to be continued ….

How to authenticate to FaceBook Graph Api – Part I

Facebook uses the OAuth 2.0 protocol for authentication and authorization. To begin use Facebook new Graph Api you have first to perform user authentication and authorization. As facebook mention in their documentation there are  two different OAuth 2.0 flows for user login: server-side (know as the authentication code flow in the specification) and client-side (known as the implicit flow). The server-side flow is used whenever you need to call the Graph API from your web server. The client-side flow is used when you need to make calls to the Graph API from a client, such as JavaScript running in a Web browser or from a native mobile or desktop app.
So, each OAuth flow (server-side or client-side) there are three different steps to pass

a- User authentication: ensures that the user is who they say they are
b- app authorization: ensures that the user knows exactly what data and capabilities they are providing to your app. Ex read permissions – write permissions – page permissions
c- app authentication: ensures that the user is giving their information to your app and not someone else

after completing this 3 steps your application is now granted user access token

Server-Side:
To authenticate user and application authorization you have to redirect user to facebook OAuth Dialog.
First of all you have to create facebook application just by go to https://developers.facebook.com/apps ,after login to facebook this page will appear to ensure that you want to allow Facebook Developer Application to access your data

If you notice that Facebook Developer Application asks for accessing you basic information. If you don’t allow the application, the application will forward you directly to nowhere because there is no redirect url. If you click on Allow then you will proceed to developer welcome page with some useful links that may help you in building applications

Let’s proceed to create your first Facebook Application just click on Create New App in the top right. You are just one step away from creating your first application by adding application name and continue, but before you continue there is two optional fields first is App Namespace that is an optional field for defining custom Open Graph actions and objects (e.g., namespace:action) and for the URL for Canvas apps used on Facebook (e.g., http://apps.facebook.com/namespace)

You have to enter security check pic 

And here is your First Facebook application 

Notice: you will use App Id and App Secret in your application to connect to Facebook.Also you have to define site url under web section you can  if you are working in localhost you can add site url as http://locahost:{port if exist}

Now you are ready to authenticate users by redirecting them to Facebook login page by any programming language to be continued ….