How to log in without using the Identity pattern?

7

An update on Api of Facebook made the default login form of Identity stop working. The way I'm doing that stopped working looks 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 form that does not use the default implementation of identity , to log in to applications ASP.NET MVC

    
asked by anonymous 30.03.2017 / 01:16

1 answer

7
  

I will respond with the premise that you already have the properly configured Facebook APP, including valid return URIs.

First, let's look at the Facebook API (the rest as Google follows the same premise):

How does it work?

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

  • 2: User authenticates and approves requested permissions;

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

See the Facebook flow in the screenshot below:

Whatdoesthismeanincode?

Torequestaccess,Facebooksaysyouneedto the following request :

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

An example 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 ID number of your application, found in the application panel.

     

redirect_uri . The URL to which you want to redirect the person signing in. This URL captures the response from the Login dialog box. If you are using it in a WebView in a desktop application, it should be set to link . To confirm that the URL is set for your application, go to the Application Dashboard, click Login to Facebook on the right-hand menu, and check the valid OAuth redirect URIs in the Client's OAuth Settings section.

When you do this, you will go to the page where the user logs in to 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 (a unique encrypted string for each login request). This is the default behavior if this parameter was not specified. It is most useful when your server is handling the token.

Where are we?

So far you have already requested access to the user, he has already logged in and Facebook has returned the unique code for that login.

But now, what do I do with this code?

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

How to get the Access Token?

To get Acess Token you should make a POST request for the following URI:

  

link

Since we're working with , I'll demonstrate how to make the request using the Facebook package :

    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 JSON like this:

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

With this you can already perform the search of 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");

Once you've done this, you already have the email and the user data. Now just check if it already has a registration or not. You can use any data for this, from the email to the facebook id, so I'll leave that with you.

In case the user has a registration, you will only authenticate it, if you do not have it, you register and then you will 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 Package, but you would have to manually request Facebook.

    
30.03.2017 / 15:37