Avançar para o conteúdo principal

Google OAuth 2.0 in ASPX

In this post I will demonstrate how to use Google OAuth in a ASPX webform with C#.

This project uses Visual Studio 2015 and as a option for the user to sign-up and other to check the sign-in.

Let's start by creating a new project.
Next pick Empty.

And now the database. The users data will be recorded in a table of a SQL Server database.

First create the database.

Next enter the name and the database type.

Yes it's a new database.

That's it, and now add a new table.
The SQL script is this:

Click update and check for errors.

Let's check that the new table is in the database.

The data structure is done. Go to the Google Developer Console and select Credentials, on the left side.

After that Create a project.

Give it a name and click create.
Next select the type of credentials to be create, in this case it's OAuth Client ID.

In the next step you pick Web application e click configure consent screen, wish is the web page the user sees when he login's for the first time.

In the consent screen set the app name.

The redirect links must be set using the http port of your IIS express.

In the end we get the credentials to be used in our project (the secrets present were deleted).

The google account.

Do not forget the activate the Google+ API.
Without this last step nothing works.

Back to Visual Studio add a Owin Startup class.

This class will be responsible for the configuration of the application, including the credentials we get from Google.

The sign-up page is the next step.

Set the name.
And the html.

Now we have to add some NuGet packages, for that we need to open the console, so go to Tools -> NuGet Package Manager -> Package Manager Console.
In the new window insert the following lines:

install-package microsoft.owin.security.cookies
install-package microsoft.owin.host.systemweb
install-package microsoft.owin.security.google

The button that will start the sign-up process has this code.

This code will open the Google login page and redirect the user to a handler.

But first let's create a connection string so we can use the database.
In the web.config insert the tags.

<connectionStrings>
    <add name="sql" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=googleoauth.mdf;Integrated Security=True;Connect Timeout=30"/>
  </connectionStrings>

To interact with the database base we will use a separated class with the name bd.
The construct of the class will establish the connect and the destruct will close it.

Some generic functions will make it easy to select and insert data from the database.

 public DataTable devolveconsulta(string sql)
        {

            SqlCommand comando = new SqlCommand(sql, ligacaoBD);
            DataTable registos = new DataTable();


            SqlDataReader dados = comando.ExecuteReader();
            registos.Load(dados);
            comando.Dispose();
            return registos;

        }

        public DataTable devolveconsulta(string sql, List<SqlParameter> parametros)
        {

            SqlCommand comando = new SqlCommand(sql, ligacaoBD);
            comando.Parameters.AddRange(parametros.ToArray());
            DataTable registos = new DataTable();


            SqlDataReader dados = comando.ExecuteReader();
            registos.Load(dados);
            comando.Dispose();
            return registos;

        }
        public bool executacomando(string sql)
        {
            try
            {
                SqlCommand comando = new SqlCommand(sql, ligacaoBD);
                comando.ExecuteNonQuery();
                comando.Dispose();
            }
            catch (Exception erro)
            {
                Console.Write(erro.Message);
                return false;
            }
            return true;
        }

        public bool executacomando(string sql, List<SqlParameter> parametros)
        {

            try
            {
                SqlCommand comando = new SqlCommand(sql, ligacaoBD);
                comando.Parameters.AddRange(parametros.ToArray());
                comando.ExecuteNonQuery();
                comando.Dispose();
            }
            catch (Exception erro)
            {
                Console.Write(erro.Message);
                return false;
            }
            return true;
        }

The handler that get's called after the user login to Google is create like this.
With this code.

Now the page that add's the user to the database, after the login to his Google account.

With the sign-up page working we can make the sign-in page like this:
And with this code:
And the handler:

And finally the page that checks the user information with the data in the database:

The project is available on GitHub.

Comentários

Mensagens populares deste blogue

New Unity 3D Project

Today I will present a new project that I started. From the post about the car I am building a game with cars, or transportation. The idea is very simple: the player starts with a car and a mission, when he is done with the mission he gets some cash that can be spent buying a new vehicle. Here are some pics: - the car in Unity - the car in Blender - working in the texture - looks great - a wheel - the texture in Gimp - back in Unity testing different materials  like water - and code

Let's make a car in Unity 3D

In this post we will make a simple car in Unity 3D. The Unity 3D physics engine is used in order to give the car a real behavior. This are the steps: [1] - Create a new Project

Single Page App with C# WPF/XAML

 In this post we are going to create a single page app. The app will have multiple pages that get rendered in the main window. We will be using Visual Studio, C#, WPF and XAML. Let's start by creating a new project in Visual Studio of this type: Next, in the MainWindow, we define the interface structure. On the left side we place a menu and on the right side a DockPanel with a Frame in it. The Frame is the element that is used to render de pages content. Now let's add the new pages. In this example I will add two pages. Click in the Solution Explorer with the mouse right button, then choose Add and Page. The project looks like this. The app content goes on the recently create pages. Because this is just an example I will just change the background color and add a small text. Page1 Page2 Finally the code. Back to the MainWindow we need to create the click events on the menu items. So, in the MenuItem line add the click event and pick New Event Handler. If that option doesn't...