How to login without using the Identity standard?

Asked

Viewed 605 times

7

An update on Api of Facebook made the default login form of Identity stop working. The way I’m doing that stopped working is like this:

public void ConfigureAuth(IAppBuilder app)
{
   app.CreatePerOwinContext(ApplicationDbContext.Create);
   app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
   app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
   app.UseCookieAuthentication(new CookieAuthenticationOptions
   {
      AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
      LoginPath = new PathString("/Account/Login"),
      Provider = new CookieAuthenticationProvider
      {
          OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, Usuario,Guid>(
          validateInterval: TimeSpan.FromMinutes(30),
          regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
          getUserIdCallback: (ci) => new Guid(ci.GetUserId()))
            }
        });            
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);          app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);
        app.UseFacebookAuthentication(new FacebookAuthenticationOptions
        {
            AppId = "*",
            AppSecret = "*",
            CallbackPath = new PathString("/Account/ExternalLoginCallback"),
            Provider = new FacebookAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    return Task.FromResult(true);
                }
            }
        });
   }
}

I want to know, a way that doesn’t use the standard implementation of identity, to log in applications ASP.NET MVC

1 answer

9


I will respond with the premise that you already have the facebook app configured correctly, including with valid return Uris.

First, let’s look at the Facebook API (the others like Google follows the same premise):

How it works?

  • 1: Customer requests access and permissions via SDK and Login Dialog;

  • 2: User performs authentication and approves requested permissions;

  • 3: Facebook returns the Access token to the client.

See the flow prepared by Facebook in the image below:

inserir a descrição da imagem aqui

What does that mean in code?

To request access, Facebook says you need to do the following request:

https://www.facebook.com/v2.8/dialog/oauth?
      client_id={app-id}
      &redirect_uri={redirect-uri}

An example of code would be this:

<a class="btn btn-primary"
            href="https://www.facebook.com/dialog/oauth?client_id=APPID&response_type=code&scope=email&redirect_uri=http://localhost:51133/Conta/Facebook">
            <i class="fa fa-facebook" aria-hidden="true"></i>
            Entrar com Facebook
        </a>

client_id. The identification number of your application, found in the application panel.

redirect_uri. The URL you want to redirect the person logging in to. This URL captures the answer from the Login dialog box. If you are using it in a Webview in a desktop application, it should be set to https://www.facebook.com/connect/login_success.html. To confirm that the URL is set for your application, go to the App Dashboard, click Login to Facebook in the menu on the right, and check the valid Oauth redirect Uris in the Client’s Oauth Settings section.

By doing this, you will already go to the page where the user logs into Facebook and accepts the permissions of the application. After this acceptance, facebook will return the code to request the user’s authorization.

code. Response data is included as URL parameters and contains code parameters (an encryption string unique to each login request). This is the default behavior if this parameter is not specified. It is most useful when your server is dealing with the token.

Where are we?

By the time you have requested access to the user, he has already logged in and Facebook has returned the unique code of that login.

But now, what do I do with that code?

The next step is to get the access_token user’s.

How to get Access Token?

To achieve the Acess Token you must make a request POST to the following URI:

https://graph.facebook.com/v2.3/oauth/access_token

How we are working with , I will demonstrate how to make the request using the facebook pack:

    FacebookClient client = new FacebookClient();
    dynamic result = client.Get("oauth/access_token", new
    {
        client_id = "{app-id}",
        redirect_uri = "{redirect-uri}",
        client_secret = "{app-secret}",
        code = "{code-parameter}"
    });

The return will be a JSON like that:

{  
   "access_token":"access_code_aqui",
   "token_type":"bearer",
   "expires_in":5181174
}

With this you can already search the user data, as I explained in this answer. But, remembering, just make a request for the data you want to get.

 var fb = new FacebookClient(result.access_token);
 dynamic informacoesFacebook = fb.Get("/me?fields=id,cover,name,first_name,last_name,age_range,link,gender,locale,picture,email");

Done this, you already have the email and user data. Now just check whether it already has registration or not. You can use any data for this, from the email to the facebook id, so I’ll leave it to you.

If the user has a registration, you only authenticate it, if you do not have it, you register and after that, you authenticate. An example would be:

var fb = new FacebookClient(result.access_token);
dynamic informacoesFacebook = fb.Get("/me?fields=id,cover,name,first_name,last_name,age_range,link,gender,locale,picture,email");

string email = informacoesFacebook[10];

var user = db.Users.FirstOrDefault(u => u.Email == email);

if (user == null)
{
    //Cadastra o usuário aqui
}
else
{
    //Realiza o login aqui
}

You do not need to use the Facebook Pack, but would have to manually request Facebook.

  • @Renancarlos The parameter code that Facebook returns to you

  • @Renancarlos In this example, it will return the code here: http://localhost:51133/Conta/Facebook

  • @Renancarlos The code facebook will return to your Controller. Look at the Login/Facebook that is in your controller that it has a code parameter, like this: Public ActionResult Facebook(string code)

  • really the code comes as null for me.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.