Login control won't login - asp.net

I've been using VS 2013 and created an Asp.Net web forms application using the template with Bootstrap. I have a login control that does all of the default behaviour using AspNet tables within SQL. When I run within the IDE I have no problems in any browser logging into the site (IE, Chrome) I was manly using IE when running.
However, I have deployed the site to my local server for testing and it stops working in IE. What happens is it goes through the validation of the user name/password fine, gets to the redirect but the user is never logged in.
If I browse to the server using chrome on my pc it will work fine if I do the same within IE it won't work 95% of the time but I have managed to login occasionally. I have asked other colleague's to try, Chrome doesn't work for most of them or IE. I have also tried on my ipad chrome will work but safari won't!
So in file startup.auth.vb
Partial Public Class Startup
' For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
Public Sub ConfigureAuth(app As IAppBuilder)
'Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(AddressOf ApplicationDbContext.Create)
app.CreatePerOwinContext(Of ApplicationUserManager)(AddressOf ApplicationUserManager.Create)
app.CreatePerOwinContext(Of ApplicationSignInManager)(AddressOf ApplicationSignInManager.Create)
' Enable the application to use a cookie to store information for the signed in user
app.UseCookieAuthentication(New CookieAuthenticationOptions() With {
.AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
.Provider = New CookieAuthenticationProvider() With {
.OnValidateIdentity = SecurityStampValidator.OnValidateIdentity(Of ApplicationUserManager, ApplicationUser)(
validateInterval:=TimeSpan.FromMinutes(10),
regenerateIdentity:=Function(manager, user) user.GenerateUserIdentityAsync(manager))},
.LoginPath = New PathString("/Account/Login")})
' Use a cookie to temporarily store information about a user logging in with a third party login provider
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie)
' Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5))
' Enables the application to remember the second login verification factor such as phone or email.
' Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
' This is similar to the RememberMe option when you log in.
app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie)
End Sub
End Class
Then on my login button
Protected Sub LogIn(sender As Object, e As EventArgs)
If IsValid Then
' Validate the user password
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim signinManager = Context.GetOwinContext().GetUserManager(Of ApplicationSignInManager)()
' This doen't count login failures towards account lockout
' To enable password failures to trigger lockout, change to shouldLockout := True
Dim result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout:=True)
Select Case result
Case SignInStatus.Success
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Exit Select
Case SignInStatus.LockedOut
Response.Redirect("/Account/Lockout")
Exit Select
Case SignInStatus.RequiresVerification
Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
Request.QueryString("ReturnUrl"),
RememberMe.Checked),
True)
Exit Select
Case Else
FailureText.Text = "Invalid login attempt"
ErrorMessage.Visible = True
Exit Select
End Select
End If
End Sub
End Class

Related

asp.net User not authenticated after successful login and redirect to homepage

I have ASP.NET website that hosted on shared web hosting
my issue user login using correct username and password and the server redirect the user after success login to another page but after redirect user showing not signed and user must sign in again and keep not working without any error
i am using vb.net and i new to web developing
i have already tried restarting hosting server and it work but after while it stuck again
Protected Sub LogIn(sender As Object, e As EventArgs)
Try
If IsValid Then
' Validate the user password
Dim manager = Context.GetOwinContext().GetUserManager(Of ApplicationUserManager)()
Dim signinManager = Context.GetOwinContext().GetUserManager(Of ApplicationSignInManager)()
' This doen't count login failures towards account lockout
' To enable password failures to trigger lockout, change to shouldLockout := True
Dim result = signinManager.PasswordSignIn(Email.Text, Password.Text, RememberMe.Checked, shouldLockout:=False)
Select Case result
Case SignInStatus.Success
IdentityHelper.RedirectToReturnUrl(Request.QueryString("ReturnUrl"), Response)
Exit Select
Case SignInStatus.LockedOut
Response.Redirect("/Account/Lockout")
Exit Select
Case SignInStatus.RequiresVerification
Response.Redirect(String.Format("/Account/TwoFactorAuthenticationSignIn?ReturnUrl={0}&RememberMe={1}",
Request.QueryString("ReturnUrl"),
RememberMe.Checked),
True)
Exit Select
Case Else
FailureText.Text = "Invalid login attempt"
ErrorMessage.Visible = True
Exit Select
End Select
End If
Catch ex As Exception
FailureText.Text = ex.Message
End Try
End Sub
I Solve my issue with login by deleting every reportviewer from all pages

How do I log a user back in after change of Email/Username? - Asp.net/VB.Net

I found this code on a site which was written for me and works, and I'm trying to use it on a new site. The code checks that a emailAddress doesn't already exist when a user edits their account details, and because the emailAddress is also used as the underlying .NET membership username it needs to change that too. So far I've managed to get it to change the email address in tblAccounts which is done with this call:
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
Then it needs to check if the user changing the email is the logged in user and re-log them back in. This doesn't seem to work as I get this error from the siteMaster when it tries to redirect to the homepage:
System.NullReferenceException: Object reference not set to an instance of an object.
The error is caused in the siteMaster when it tries to check messages for logged in user and it flags up the last line of this as where the error occurs:
If HttpContext.Current.User.Identity.IsAuthenticated Then
hypSettings.visible=true
Dim counter As Integer = messaging.CheckUnreadMessages(Membership.GetUser.ProviderUserKey)
It therefore looks like the email address is being updated where it should, but the site isn't logging the user back in correctly. As I say, it works on the site where I took the code from and there isn't much difference between the sites, but I don't understand memberships and cookies too well so I'm not sure if something needs altering elsewhere?
Here's the code for changing the users email address:
'Check if the Role has been changed
Membership.ApplicationName = "/OCBS"
Dim userID As Guid = Guid.Parse(Request.QueryString("aID"))
Dim usr As MembershipUser = Membership.GetUser(userID, False)
'Now check if the email address has been changed, because the email address is used for the username then the underlying .NET membership username needs changing
If txtEmailAddress.Text <> lblEmailAddress.Text Then
'Email has been changed, update the username for this user
Dim acc As New accounts(Guid.Empty)
acc.UpdateUsername(txtEmailAddress.Text, lblEmailAddress.Text)
'Check if the user changing the email is the logged in user and re-log them back in
If User.Identity.Name = lblEmailAddress.Text Then
'FormsAuthentication.SetAuthCookie(txtEmailAddress.Text, False)
Response.Cookies.Clear()
Dim expiryDate As DateTime = DateTime.Now.AddDays(100)
Dim ticket As New FormsAuthenticationTicket(2, txtEmailAddress.Text, DateTime.Now, expiryDate, True, [String].Empty)
Dim encryptedTicket As String = FormsAuthentication.Encrypt(ticket)
Dim authenticationCookie As New HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket)
authenticationCookie.Expires = ticket.Expiration
Response.Cookies.Add(authenticationCookie)
End If
End If
Oooh, I've managed it.. I added this..
Session.Abandon()
FormsAuthentication.SignOut()
after line: Response.Cookies.Clear()

"Validation of viewstate MAC failed" only when posting back from a mobile browser that has been idle for sometime

I know that this question has been asked frequently on StackOverflow but my case is a bit different. I checked all the answers related to this issue and none solved my problem as in my case it only happens with browsers on mobile devices.
I only get the "Validation of ViewState MAC failed" error when posting back from a mobile browser that has been left open for some time. The error never appears when submitting a form from a computer browser. It neither appears when submitting from a mobile browser most of the time. It only appears when I open a mobile tab that was already submitted from some time and click the submit button again.
However, It happens all the time as well when I close my browser (so that it is not running in the mobile background), open it again and re-submit the form. I guess this is the main problem behind this error (re-launching the browser is causing page-reload on mobile before clicking on anything).
I tried the below solutions and none of them worked:
Manually set MachineKey to my web.config
Use aspnet_regiis utility to run the managed application where machine keys will be persisted.
Solutions proposed in this article
set LoadUserProfile = True in the application pool
Set the SessionTimeout = 0 in IIS application pool.
Secured my cookies over http.
Note: I know that setting enableViewStateMac="false" in my web.config will solve my problem, but I really don't wish to do so to avoid security depreciation in my application.
After a couple of tests, I noticed that the error only generates when the mobile browser force-reload/relaunch the page. For example, if I re-submit the form that has been already submitted from a mobile, most of the times it does not generate an error. However, sometimes, when I open the browser on the mobile, it force-reload/relaunches the page before I click on anything. Now when I click on the submit button, the error appears.
Possibly, this force-reload/relaunch is causing this error since the ViewState is being altered.
Another possibility is that the mobile is expiring the sessions even though I've set the sessions to not expire in my IIS.
Yet, another possibility would be that the mobile does not allow the browser to run in the background resulting in force-reload to re-construct the page when the user opens the browser again.
I am using the below code in my application:
Partial Class MasterPage
Inherits System.Web.UI.MasterPage
Private Const AntiXsrfTokenKey As String = "__AntiXsrfToken"
Private Const AntiXsrfUserNameKey As String = "__AntiXsrfUserName"
Private _antiXsrfTokenValue As String
Protected Sub Page_Init(sender As Object, e As EventArgs)
' The code below helps to protect against XSRF attacks
Dim requestCookie = Request.Cookies(AntiXsrfTokenKey)
Dim requestCookieGuidValue As Guid
If requestCookie IsNot Nothing AndAlso Guid.TryParse(requestCookie.Value, requestCookieGuidValue) Then
' Use the Anti-XSRF token from the cookie
_antiXsrfTokenValue = requestCookie.Value
Page.ViewStateUserKey = _antiXsrfTokenValue
Else
' Generate a new Anti-XSRF token and save to the cookie
_antiXsrfTokenValue = Guid.NewGuid().ToString("N")
Page.ViewStateUserKey = _antiXsrfTokenValue
Dim responseCookie = New HttpCookie(AntiXsrfTokenKey) With {
.HttpOnly = True,
.Value = _antiXsrfTokenValue
}
If FormsAuthentication.RequireSSL AndAlso Request.IsSecureConnection Then
responseCookie.Secure = True
End If
Response.Cookies.[Set](responseCookie)
End If
AddHandler Page.PreLoad, AddressOf master_Page_PreLoad
End Sub
Protected Sub master_Page_PreLoad(sender As Object, e As EventArgs)
If Not IsPostBack Then
' Set Anti-XSRF token
ViewState(AntiXsrfTokenKey) = Page.ViewStateUserKey
ViewState(AntiXsrfUserNameKey) = If(Context.User.Identity.Name, [String].Empty)
Else
' Validate the Anti-XSRF token
If DirectCast(ViewState(AntiXsrfTokenKey), String) <> _antiXsrfTokenValue OrElse DirectCast(ViewState(AntiXsrfUserNameKey), String) <> (If(Context.User.Identity.Name, [String].Empty)) Then
Throw New InvalidOperationException("Validation of Anti-XSRF token failed.")
End If
End If
End Sub
Private Sub MasterPage_Load(sender As Object, e As EventArgs) Handles Me.Load
'Add Base Path and Canonical URL
Dim strBasePath = "<base href='" & AppSettings("LivePath") & "' />"
Page.Header.Controls.Add(New LiteralControl(strBasePath))
End Sub
End Class
I hope there is a solution to this since I don't want to end up setting enableViewStateMac="false" in my web.config
[Update]
Potential Solution:
My current potential solution for this is to handle the "Validation of ViewState MAC failed" error and prompt a custom message to the user explaining the form validation failure. This way security and usability is balanced.
I was inspired by this article for this likely short-lived solution.

SSO with Azure ADFS and OWIN

Thank you for providing help. I have a site that can authenticate with Active Directory Federated Services for Single Sign On. Currently, the way my site works is that, by default, when a user hits my site, my code attempts to log then into SSO (I use the OWIN library for this). If the user is not on our network, it fails to authenticate, and they are redirected to my companies login page, where they can provide their company credentials.
I would like to change this behavior, though. Instead, when the user hits my page, if they authenticate, it should continue as normal and they should be redirected to my site. But, if they do not authenticate, I do not want them redirected to our login page. instead, I want them to be redirected back to my site, where my code will determine what they can and cannot do on the site. I then would want to provide a link, so that they could decide to go to the login page.
I want this behavior because the majority of users of this site will not be a part of the companies network and will not be able to authenticate. SO, they should, by default, just see our home page. But, there may be times when a company member might be working from home, so wont be on our network to auto authenticate. In this case, they would then use the link that sends them to the Azure login page.
Here is the code that I am currently using (site is ASP.net, form web page (not MVC)):
Startup.Auth.vb:
Partial Public Class Startup
Dim appSettings = ConfigurationManager.AppSettings
Private realm As String
Private aadInstance As String
Private tenant As String
Private metadata As String
Private authority As String
Public Sub ConfigureAuth(app As IAppBuilder)
Try
Dim appSettings = ConfigurationManager.AppSettings
If (appSettings("releaseVersion") = "DEBUG") Then
realm = ConfigurationManager.AppSettings("test_ida:RPIdentifier")
aadInstance = ConfigurationManager.AppSettings("test_ida:AADInstance")
tenant = ConfigurationManager.AppSettings("test_ida:Tenant")
ElseIf (appSettings("releaseVersion") = "PROD") Then
realm = ConfigurationManager.AppSettings("ida:RPIdentifier")
aadInstance = ConfigurationManager.AppSettings("ida:AADInstance")
tenant = ConfigurationManager.AppSettings("ida:Tenant")
End If
metadata = String.Format("{0}/FederationMetadata/2007-06/FederationMetadata.xml", aadInstance)
authority = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant)
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
Dim authOption As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions()
Dim fn = Function(context)
context.HandleResponse()
context.Response.Redirect("Home/Error?message=" + context.Exception.Message)
Return Task.FromResult(0)
End Function
Dim auth_not As WsFederationAuthenticationNotifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = fn
}
Dim auth_opt As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions() With {
.Wtrealm = realm,
.MetadataAddress = metadata,
.Notifications = auth_not
}
If (Not auth_opt.Wtrealm Is Nothing) Then
app.UseWsFederationAuthentication(auth_opt)
Else
End If
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
Then, on my Default.aspx.vb page load event, I do this:
If (Not Request.IsAuthenticated) Then
Try
Dim newAuth As AuthenticationProperties = New AuthenticationProperties()
newAuth.RedirectUri = "/"
HttpContext.Current.GetOwinContext().Authentication.Challenge(newAuth, WsFederationAuthenticationDefaults.AuthenticationType)
Catch ex As Exception
Throw ex
End Try
End If
The problem is, I do not know how to attempt to authenticate the user, determine if they are authenticated, and redirect them accordingly. Any help would be greatly appreciated.
thanks
There is not solid/correct way how to check if anonymous user is inside your network(or I am not aware of one). Possible way is to check IP address (range) users inside your network have publicly on the Internet. This is something you can check with network administrator(s). They may tell you public IP address (range).
Once you know public IP address (range) you can check incoming request to compare if the request is coming from the known reange of IP address (range) inside RedirectToIdentityProvider function.
Dim redirectToIdentityProvider = Function(context)
Dim isCompanyNetworkUser = companyIPAddress == context.Request.RemoteIpAddress
' Or relevant check for range
' Dim isCompanyNetworkUser = (companyIPAddressRangeStart < context.Request.RemoteIpAddress AndAlso companyIPAddressRangeEnd > context.Request.RemoteIpAddress
If Not isCompanyNetworkUser Then
context.State = NotificationResultState.Skipped
context.HandleResponse()
End If
End Function
Dim auth_not As WsFederationAuthenticationNotifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = fn
.RedirectToIdentityProvider = redirectToIdentityProvider
}
You may want to tweak it a bit as I didn't try it, but may point you to right direction.
Sorry to not providing full code example, but in my opinion :
You may try to bypass the sign-in page prompts, take a look here, which explain you how to :
bypass the sign-in page prompts by adding your company’s existing federated domain name to the end of the Windows Azure Management Portal URL
You may also find usefull information relative to Azure Active Directory Pass-through Authentication which allow that:
When users sign in using Azure AD, this feature validates users' passwords directly against your on-premises Active Directory.
You may also make appear your website as an "application" then added this app to your Azure Active Directory application gallery. then Managing single sign-on for enterprise apps
I found finally that this question may be relative to your question.

ASP.net using OWIN for Azure Active Directory Federation Services Single Sign On

I am working on a project, based on this solution: https://github.com/Azure-Samples/active-directory-dotnet-webapp-wsfederation
Currently, the way I have the user authenticate is by default. When the page loads, I call my login script:
Public Sub SignIn()
If (Not Request.IsAuthenticated) Then
Try
Dim newAuth As AuthenticationProperties = New AuthenticationProperties()
newAuth.RedirectUri = "/"
HttpContext.Current.GetOwinContext().Authentication.Challenge(newAuth, WsFederationAuthenticationDefaults.AuthenticationType)
Catch ex As Exception
End Try
End If
End Sub
EDIT
To add more context, here is my code for APP_START/Startup.Auth.vb:
Partial Public Class Startup
Private realm As String = ConfigurationManager.AppSettings("ida:RPIdentifier")
Private aadInstance As String = ConfigurationManager.AppSettings("ida:AADInstance")
Private tenant As String = ConfigurationManager.AppSettings("ida:Tenant")
Private metadata As String = String.Format("{0}/FederationMetadata/2007-06/FederationMetadata.xml", aadInstance)
Private authority As String = String.Format(CultureInfo.InvariantCulture, aadInstance, tenant)
Public Sub ConfigureAuth(app As IAppBuilder)
Try
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType)
app.UseCookieAuthentication(New CookieAuthenticationOptions())
Dim authOption As WsFederationAuthenticationOptions = New WsFederationAuthenticationOptions()
app.UseWsFederationAuthentication(New WsFederationAuthenticationOptions() With {
.Wtrealm = realm,
.MetadataAddress = metadata,
.Notifications = New WsFederationAuthenticationNotifications() With {
.AuthenticationFailed = Function(context)
context.HandleResponse()
context.Response.Redirect("Home/Error?message=" + context.Exception.Message)
Return Task.FromResult(0)
End Function
}
})
Catch ex As Exception
Throw ex
End Try
End Sub
End Class
What I want to avoid, though, is if someone from outside our network views the site, I don't want them to be redirected to the Azure Single Sign On login page. I just want them to proceed to the website, where my code will handle what they can see and do. I will, eventually, add a login button that will take them to the login page, in the event they are just off site. But, for now, how do I skip the login page?
Second, I want to handle the possibility that Azure ADFS is down. In this case, I just want the user to be redirected to the website, as un-authenticated users. I test this by disconnecting from the Internets and running my app. I've tried using Try blocks, but I still get these errors:
The remote name could not be resolved: 'adfs.myCompany.com'
IOException: Unable to get document from:
https://adfs.myCompany.com/FederationMetadata/2007-06/FederationMetadata.xml
[InvalidOperationException: IDX10803: Unable to create to obtain
configuration from:
'https://adfs.myCompany.com/FederationMetadata/2007-06/FederationMetadata.xml'.]
Are these settings in Azure I should be making or in my code? Any help, with either of these issues, would be great. I needed, I can also add my Start.Auth.vb code, as well.
thanks
Unfortunately, using the samples Microsoft provides will enforce auto-sign on.
That being said, there are two options:
Choose a different authentication scheme
Use a an Azure application with an oAuth code flow to sign in when a user clicks the login in link, then read the user's profile and determine their authorization rights.
If I misunderstood, please let me know. Hope this helps!

Resources