obtain current logged in user - asp.net

I'm using Activedirectory as membership provider. I want to store the current logged in user in a session.
protected void user_login_LoggedIn(object sender, EventArgs e)
{
MembershipUser user = Membership.GetUser();
}
the code above gives the error below
The parameter 'username' must not be empty.
Parameter name: username
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details:
System.ArgumentException: The parameter 'username' must not be empty.
Parameter name: username
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[ArgumentException: The parameter 'username' must not be empty.
Parameter name: username]
System.Web.Util.SecUtility.CheckParameter(String& param, Boolean checkForNull, Boolean checkIfEmpty, Boolean checkForCommas, Int32 maxSize, String paramName) +1976411
System.Web.Security.ActiveDirectoryMembershipProvider.CheckUserName(String& username, Int32 maxSize, String paramName) +30
System.Web.Security.ActiveDirectoryMembershipProvider.GetUser(String username, Boolean userIsOnline) +86
System.Web.Security.Membership.GetUser(String username, Boolean userIsOnline) +82
System.Web.Security.Membership.GetUser() +19
darts.login.user_login_LoggedIn(Object sender, EventArgs e) in E:\Projects\DARTS\source\darts\darts\login.aspx.cs:24
System.Web.UI.WebControls.Login.OnLoggedIn(EventArgs e) +111
System.Web.UI.WebControls.Login.AttemptLogin() +179
System.Web.UI.WebControls.Login.OnBubbleEvent(Object source, EventArgs e) +101
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.Button.OnCommand(CommandEventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +166
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565
Version Information: Microsoft .NET Framework Version:2.0.50727.4211; ASP

Edit:
Based upon using this from ASP.NET to get the login information about the currently authenticated user, I see a couple ways that this might work. First, if you are using Forms authentication with the Active Directory membership provider, you could capture the username there. Then you just put the username inside of the GetUser() method like so: GetUser(yourUser) and you should get the information needed.
If this isn't an option, I believe the username information is stored under your login control (in your case, I believe the name is user_login if you are indeed using a login control). You would simply say user_login.username and put that inside the GetUser() method.
Finally, you could try the old fallback of HttpContext.Current.User.Identity.Name and put that inside of your GetUser() method.

Related

How to allow my Azure web application to access Active Directory?

I have a WebForms application that uses Active Directory for authentication and authorization. It works just fine on localhost, but fails when I attempt to access the site once published to Azure. I have ensured that the application is registered with Azure Active Directory. The app launches and works as expected if I don't attempt to get the AD security groups of the current user. Here's the code in the Page_Load event of the Site Master that is causing the issues:
protected void Page_Load(object sender, EventArgs e)
{
PrincipalSearchResult<Principal> groups = UserPrincipal.Current.GetAuthorizationGroups();
IEnumerable<string> groupNames = groups.Select(x => x.Name);
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
HyperLink newphaud = LIV.FindControl("liaNewPhaud") as HyperLink;
HtmlGenericControl liadmin = LIV.FindControl("navAdminsDdl") as HtmlGenericControl;
newphaud.Visible = (groupNames.Contains("SG1") || groupNames.Contains("SG2"));
liadmin.Visible = groupNames.Contains("SG1");
}
}
Here's the exception detail:
System.Runtime.InteropServices.COMException: Access is denied.
Here's the stack trace:
[COMException (0x80070005): Access is denied.
]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +399115
System.DirectoryServices.DirectoryEntry.Bind() +36
System.DirectoryServices.DirectoryEntry.RefreshCache() +45
System.DirectoryServices.AccountManagement.PrincipalContext.DoMachineInit() +211
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() +128
System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx() +31
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate) +14
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, String identityValue) +90
System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue) +32
System.DirectoryServices.AccountManagement.UserPrincipal.get_Current() +191
phaud.SiteMaster.Page_Load(Object sender, EventArgs e) in C:\Users\user1\source\repos\phaud\phaud\Site.Master.cs:19
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +51
System.Web.UI.Control.OnLoad(EventArgs e) +95
System.Web.UI.Control.LoadRecursive() +59
System.Web.UI.Control.LoadRecursive() +131
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +678
What do I need to do to allow my Azure web app to access AD?
Please do note that Azure AD != Windows AD. From the code it does seems that your app is accessing the local Windows AD. So when you are in Azure you have basically two options
1) Use Azure AD API for authentication and get the User Info
2) You can have a separate Windows VM running the Windows AD which then would be accessed by your Azure Web App.
If I were you I would have explored the first option. Hope it helps

System.DirectoryServices.DirectoryServicesCOMException

I keep getting the following error when trying to run an application in the production environment with "anonymous" authentication and hardcoded username.
When I turn on basic authentication, which then prompts for username/password everything works like a charm. but I need to get the hardcoded version to work as well. Can't figure out whats going on.
Everything works perfectly on another server.
Exception Details: System.DirectoryServices.DirectoryServicesCOMException: An operations
error occurred.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[DirectoryServicesCOMException (0x80072020): An operations error occurred.]
System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail) +781
System.DirectoryServices.DirectoryEntry.Bind() +44
System.DirectoryServices.DirectoryEntry.get_SchemaEntry() +49
System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(DirectoryEntry
de) +62
System.DirectoryServices.AccountManagement.ADStoreCtx..ctor(DirectoryEntry
ctxBase, Boolean ownCtxBase, String username, String password,
ContextOptions options) +123
System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry
entry) +234
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
+497
[PrincipalOperationException: An operations error occurred.]
System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
+534256
System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
+61
System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
+141
System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
+42
System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext
context, Type principalType, Nullable`1 identityType, String
identityValue, DateTime refDate) +27
System.DirectoryServices.AccountManagement.GroupPrincipal.FindByIdentity(PrincipalContext
context, String identityValue) +95
SERT_BO.ADHelper.UserBelongsToGrp(String adGroup, String sAMAccountName, String& emailAddr, String& fullName) in
D:\SERT\BusinessObjects\SERT_BO\ADHelper.cs:199
SERT_BO.UserSession.GetUserSession(String userName) in D:\SERT\BusinessObjects\SERT_BO\UserSession.cs:44
SERT.SetUserSession.Page_Load(Object sender, EventArgs e) in D:\SERT\SERT\SERT\SetUserSession.aspx.cs:23
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +25
System.Web.UI.Control.LoadRecursive() +71
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
+3064
One thing to check is that the AppPool in which the ASP.NET app is running has the right privileges. As a quick test you can set the identity of the AppPool to Local System and see if this solves the issue. If the problem is here, then you can set the application pool identity to a (domain?) user that has enough privileges on this server.
looks like the issue was that the server was looking at the wrong AD controller. it had to be written out COMPLETELY.

Unknown error When Starting java.exe from an ASP.NET Application

On these lines of code:
// Run compiler
Process p = System.Diagnostics.Process.Start("java.exe", ex);
p.WaitForExit();
We get this error:
Server Error in '/' Application.
Unknown error (0xfffffffe)
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ComponentModel.Win32Exception: Unknown error (0xfffffffe)
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[Win32Exception (0x80004005): Unknown error (0xfffffffe)]
System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo) +912
System.Diagnostics.Process.Start() +136
System.Diagnostics.Process.Start(ProcessStartInfo startInfo) +49
Arcade.UploadFunctions.minifyC2Runtime(Int32 GameID) +333
Arcade.GameFunctions.createGame(Int32 CatID, String Name, String Description, String Instructions, Int32 UserId, Int32 Width, Int32 Height, Int32 ParentGameID) +1338
ArcadeSubmit.submitGame(Object sender, EventArgs e) +1329
System.Web.UI.WebControls.Button.OnClick(EventArgs e) +118
System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +112
System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +36
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +5563
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.272
As noted in my other question it would appear this is a permissions error. However, this error disappears if I recycle my app pool. It then starts throwing this error again within a couple of hours or so.
The apppool in question is running with LocalService identity. Anyone know what would be causing this to break?
Edit: More details error from event viewer
Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 2/29/2012 8:15:12 AM
Event time (UTC): 2/29/2012 8:15:12 AM
Event ID: 6b5770960c4f41b1a9ba10045b7b50d4
Event sequence: 131746
Event occurrence: 480
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/1/ROOT-26-129749512365140162
Trust level: Full
Application Virtual Path: /
Application Path: C:\inetpub\wwwroot\Scirra\
Machine name: WIN-MT04GJ7U5CB
Process information:
Process ID: 8276
Process name: w3wp.exe
Account name: NT AUTHORITY\LOCAL SERVICE
Exception information:
Exception type: Win32Exception
Exception message: Unknown error (0xfffffffe)
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Arcade.UploadFunctions.minifyC2Runtime(Int32 GameID)
at Arcade.GameFunctions.createGame(Int32 CatID, String Name, String Description, String Instructions, Int32 UserId, Int32 Width, Int32 Height, Int32 ParentGameID)
at ArcadeSubmit.submitGame(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Request information:
Request URL: http://www.scirra.com/ArcadeSubmit.aspx
Request path: /ArcadeSubmit.aspx
User host address: [censored]
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\LOCAL SERVICE
Thread information:
Thread ID: 5
Thread account name: NT AUTHORITY\LOCAL SERVICE
Is impersonating: False
Stack trace: at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
at Arcade.UploadFunctions.minifyC2Runtime(Int32 GameID)
at Arcade.GameFunctions.createGame(Int32 CatID, String Name, String Description, String Instructions, Int32 UserId, Int32 Width, Int32 Height, Int32 ParentGameID)
at ArcadeSubmit.submitGame(Object sender, EventArgs e)
at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Custom event details:

ASP.NET + NetworkCredentials, The logon attempt failed

I've got an ASP.NET app that requires Windows Integrated Security.
For some reason, I don't what to discuss that here, I need to create a WebRequest at runtime, call some other page in the app and process the result.
The application runs on a server for which we use a DNS alias, something like theapp.domain.com.
So I create a NetworkCredential with a predefined domain user and password and I attach it to the request.
This is what I get:
[Win32Exception (0x80004005): The logon attempt failed]
System.Net.NTAuthentication.GetOutgoingBlob(Byte[] incomingBlob, Boolean throwOnError, SecurityStatus& statusCode) +1404402
System.Net.NTAuthentication.GetOutgoingBlob(String incomingBlob) +78
System.Net.NegotiateClient.DoAuthenticate(String challenge, WebRequest webRequest, ICredentials credentials, Boolean preAuthenticate) +560
System.Net.NegotiateClient.Authenticate(String challenge, WebRequest webRequest, ICredentials credentials) +14
System.Net.AuthenticationManager.Authenticate(String challenge, WebRequest request, ICredentials credentials) +247
System.Net.AuthenticationState.AttemptAuthenticate(HttpWebRequest httpWebRequest, ICredentials authInfo) +243
System.Net.HttpWebRequest.CheckResubmitForAuth() +232
System.Net.HttpWebRequest.CheckResubmit(Exception& e) +5299747
[WebException: The remote server returned an error: (401) Unauthorized.]
System.Net.HttpWebRequest.GetResponse() +5313085
Entropy.Envoy.Web.Corporate.ExportFilter.GetTargetReportContent(Uri targetUrl, HttpCookieCollection cookies) +521
Entropy.Envoy.Web.Corporate.ExportFilter.Page_Load(Object sender, EventArgs e) +139
System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) +14
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +35
System.EventHandler.Invoke(Object sender, EventArgs e) +0
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
The same code works on other servers with similar setup though.
What is going on?
Found the answer to this one.
Turned out to be as simple as adding an SPN to Active Directory like so:
setspn -a HTTP//WebServer.domain.com customDomainAccount
setspn -a HTTP//servername customDomainAccount

NullReferenceException when running published website in IIS

I have a website that I published before adding it in IIS. After that I set the published website as the default website in IIS.
I got an error that the "Object reference is not set to the instance of an object" when I inserted values through form. There is no issues when the website is running in IIS without publishing. The error occurs when values are inserted using datagrid.
The error messages is as follows:
Server Error in '/' Application.
Object reference not set to an
instance of an object.
Description: An unhandled exception
occurred during the execution of the
current web request. Please review the
stack trace for more information about
the error and where it originated in
the code.
Exception Details:
System.NullReferenceException: Object
reference not set to an instance of an
object.
Source Error:
An unhandled exception was generated
during the execution of the current
web request. Information regarding the
origin and location of the exception
can be identified using the exception
stack trace below.
Stack Trace:
[NullReferenceException: Object
reference not set to an instance of an
object.]
Admin_MasterEntries.gvwMileStoneM_RowCommand(Object
sender, GridViewCommandEventArgs e)
+447 System.Web.UI.WebControls.GridView.OnRowCommand(GridViewCommandEventArgs
e) +105
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs
e, Boolean causesValidation, String
validationGroup) +76
System.Web.UI.WebControls.GridView.OnBubbleEvent(Object
source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object
source, EventArgs args) +35
System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object
source, EventArgs e) +117
System.Web.UI.Control.RaiseBubbleEvent(Object
source, EventArgs args) +35
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs
e) +115
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String
eventArgument) +163
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String
eventArgument) +7
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler
sourceControl, String eventArgument)
+11 System.Web.UI.Page.RaisePostBackEvent(NameValueCollection
postData) +174
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint) +5102
If any one knows please help me. Thank you.
That exception is caused by an object not being instantiated. Open the project and attach a debugger to the IIS process. A web service which is consuming the ASP.NET page is throwing the exception.
Try this:
Click your site in IIS
Open Pages and Controls section
Find ViewState group and check if ViewState is enabled.
Such solution helped me to solve null reference exception problem after publish.

Resources