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

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

PacMan 3D

In this post we will be making a simple and classic game, the Pacman, with Unity 3D. Let's create a new a new project

Upgrading Windows 10 Home to Pro

 So I have been thinking about upgrading my Windows 10 Home Edition to the Pro version, but I always get to the point where it seems that I had to reinstall the entire SO and quit. After some investigating I have done it this way: - following this post  on the microsoft site I use one of the default keys for Windows 10 Pro and went to Settings > Update & Security > Activation > Change the product key; - next, Windows will activate the Pro functionalities and asks to restart; - now you have the Pro version but it's not activated, so you have to buy a Windows Pro Key. I went to UR cdkeys  and bought a key for less then €20; - and with the new key went to Change the product key and activated; - and it's done. Disclaimer : I have nothing to do with UR cdkeys so you can use any site to buy you cd key and your experience may vary from mine.