Quantcast
Channel: Security
Viewing all articles
Browse latest Browse all 4737

Asp.NET - Unable to login via Facebook (error message: object reference not set to an object instance)

$
0
0

Hi All,

 

I am trying hard to allow authentication via Facebook by using the Visual Studio 2013 template (New Website > Web Forms Asp.NET).

 

The good thing of this template is that it gives you all the necessary code to use the .NET Identity with apparently easy customizable Facebook (and other providers)'s login capabilities.

 

I have followed thoroughly the instructions provided in the ASP.NET site but I still get the same error message:

 

"object reference not set to an object instance"

 

Line 35:         If Not IsPostBack Then
Line 36:             Dim manager = New UserManager()
Line 37:             Dim loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo()
Line 38:             If loginInfo Is Nothing Then
Line 39:                 Response.Redirect("~/Account/Login")
[NullReferenceException: Object reference not set to an object instance.]
   Microsoft.Owin.Security.AuthenticationManagerExtensions.GetExternalLoginInfo(AuthenticateResult result) +81
   Microsoft.Owin.Security.<GetExternalLoginInfoAsync>d__7.MoveNext() +193
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +159
   Microsoft.Owin.Security.AuthenticationManagerExtensions.GetExternalLoginInfo(IAuthenticationManager manager) +71
   Account_RegisterExternalLogin.Page_Load() in C:\Users\Claudio\Desktop\HP_New\Account\RegisterExternalLogin.aspx.vb:37
   Account_RegisterExternalLogin._Lambda$__2(Object a0, EventArgs a1) in C:\Users\Claudio\AppData\Local\Temp\Temporary ASP.NET Files\root\fc5c92b6\b8f80282\App_Web_533f4fdd.4.vb:0
   System.EventHandler.Invoke(Object sender, EventArgs e) +0
   System.Web.UI.Control.OnLoad(EventArgs e) +74
   System.Web.UI.<LoadRecursiveAsync>d__4.MoveNext() +228
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Web.Util.WithinCancellableCallbackTaskAwaiter.GetResult() +30
   System.Web.UI.<ProcessRequestMainAsync>d__14.MoveNext() +4310

In my Login Page's code behind I am using the following code:

Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports Microsoft.Owin.Security

Public Partial Class Account_Login
    Inherits Page
    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        RegisterHyperLink.NavigateUrl = "Register"
        OpenAuthLogin.ReturnUrl = Request.QueryString("ReturnUrl")
        Dim returnUrl = HttpUtility.UrlEncode(Request.QueryString("ReturnUrl"))
        If Not [String].IsNullOrEmpty(returnUrl) Then
            RegisterHyperLink.NavigateUrl += "?ReturnUrl=" & returnUrl
        End If
    End Sub

    Protected Sub LogIn(sender As Object, e As EventArgs)
        If IsValid Then
            ' Convalidare la password utente
            Dim manager = New UserManager()
            Dim user As ApplicationUser = manager.Find(UserName.Text, Password.Text)
            If user IsNot Nothing Then
                IdentityHelper.SignIn(manager, user, RememberMe.Checked)
                IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
            Else
                FailureText.Text = "Nome utente o password non valida."
                ErrorMessage.Visible = True
            End If
        End If
    End Sub
End Class

While in my Register page's code behind I am using the following code:

Imports Microsoft.AspNet.Identity
Imports Microsoft.AspNet.Identity.EntityFramework
Imports Microsoft.AspNet.Identity.Owin
Imports System.Security.Claims
Imports System.Web
Imports Microsoft.Owin.Security

Public Partial Class Account_RegisterExternalLogin
    Inherits System.Web.UI.Page
    Protected Property ProviderName() As String
        Get
            Return If(DirectCast(ViewState("ProviderName"), String), [String].Empty)
        End Get
        Private Set(value As String)
            ViewState("ProviderName") = value
        End Set
    End Property

    Protected Property ProviderAccountKey() As String
        Get
            Return If(DirectCast(ViewState("ProviderAccountKey"), String), [String].Empty)
        End Get
        Private Set(value As String)
            ViewState("ProviderAccountKey") = value
        End Set
    End Property

    Protected Sub Page_Load() Handles Me.Load
        ' Elaborare il risultato fornito da un provider di autenticazione nella richiesta
        ProviderName = IdentityHelper.GetProviderNameFromRequest(Request)
        If [String].IsNullOrEmpty(ProviderName) Then
            Response.Redirect("~/Account/Login")
        End If

        If Not IsPostBack Then
            Dim manager = New UserManager()
            Dim loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo()
            If loginInfo Is Nothing Then
                Response.Redirect("~/Account/Login")
            End If
            Dim appuser = manager.Find(loginInfo.Login)
            If appuser IsNot Nothing Then
                IdentityHelper.SignIn(manager, appuser, isPersistent:=False)
                IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
            ElseIf User.Identity.IsAuthenticated Then
                Dim verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId())
                If verifiedloginInfo Is Nothing Then
                    Response.Redirect("~/Account/Login")
                End If

                Dim result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login)
                If result.Succeeded Then
                    IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
                Else
                    AddErrors(result)
                    Return
                End If
            Else
                userName.Text = loginInfo.DefaultUserName
            End If
        End If
    End Sub

    Protected Sub LogIn_Click(sender As Object, e As EventArgs)
        CreateAndLoginUser()
    End Sub

    Private Sub CreateAndLoginUser()
        If Not IsValid Then
            Return
        End If
        Dim manager = New UserManager()
        Dim user = New ApplicationUser() With {.UserName = userName.Text}
        Dim result = manager.Create(user)
        If Not result.Succeeded Then
            AddErrors(result)
            Return
        End If
        Dim loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo()
        If loginInfo Is Nothing Then
            Response.Redirect("~/Account/Login")
            Return
        End If
        result = manager.AddLogin(user.Id, loginInfo.Login)
        If Not result.Succeeded Then
            AddErrors(result)
            Return
        End If
        IdentityHelper.SignIn(manager, user, False)
        IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
        Return
    End Sub

    Private Sub AddErrors(result As IdentityResult)
        For Each [error] As String In result.Errors
            ModelState.AddModelError("", [error])
        Next
    End Sub
End Class

It's been now days that I am trying to make it work but I cant find a solution.

A help is much appreciated.

Thanks



 

 


Viewing all articles
Browse latest Browse all 4737

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>