Asp.net MVC Capture user name from authentication popup - c#

I created Asp.Net Mvc web application w/c is using windows authentication.
My requirement is capture and log invalid login attempts but don't know how to do it. Tried to google but no luck.
List item
How to capture user name input from authentication popup?
List item
Is there setting to limit login pop up after consecutive login failed.
It works on Internet Explorer (IE),It display 401 unauthorized after 3 consecutive login attempts but Firefox and Mozilla do not have limits.
Here is what i tried so far.
Using below code,
List item
I'm trying to capture unauthorized error unfortunately event only fire when i click cancel for Firefox and Mozilla.
List item
It fires after 3 invalid attempts in IE but don't know how to get user name input.
Global.asax
protected void Application_EndRequest(Object sender, EventArgs e)
{
HttpContext context = HttpContext.Current;
if (context.Response.Status.Substring(0, 3).Equals("401"))
{
//Capture user name for further processing
//
context.Response.ClearContent();
context.Response.Write("You are un authorized ");
}
}
Thanks in advance, hope someone can help.

Finally made it work, totally get rid of my first code using Application_EndRequest event.
Thanks to derloopkat.
Code on Global.asax Session_Start event.
protected void Session_Start(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
string currentUser = HttpContext.Current.User.Identity.Name;
Int32 expiryMin = Convert.ToInt32(ConfigurationManager.AppSettings["CacheExpirationInMinutes"]);
// call our procedure
auditLog(currentUser);
bool IsActive = accessMaintenance.IsActive(currentUser);
if (IsActive)
{
// handling if user is valid/not locked...
}
else
{
// Other handling if user is locked...
}
}
}
auditLog Procedure
private void auditLog(string user)
{
// Get logs from event viewer
string userName = ExtractUserAlias(user);
EventLog securityLog = new EventLog("Security");
var logOnAttempts = (
from log in securityLog.Entries.Cast<EventLogEntry>()
where log.EventID == 4625 || log.EventID== 4624 && log.ReplacementStrings[5] == userName
orderby log.TimeGenerated descending
select log
).Take(20).ToList();
//Store user logs to db if logs does not exists.
//Store in DB for reporting purposes
DataAccess db = new DataAccess();
foreach (var x in logOnAttempts)
{
string entryType = "";
switch (x.EntryType)
{
case EventLogEntryType.SuccessAudit:
entryType = "SuccessAudit";
break;
case EventLogEntryType.FailureAudit:
entryType = "FailureAudit";
break;
}
SqlCommand com = new SqlCommand();
com.CommandType = System.Data.CommandType.StoredProcedure;
com.CommandText = "Sp_LogUser";
com.Parameters.AddWithValue("#UserName", userName);
com.Parameters.AddWithValue("#EntryType", entryType);
com.Parameters.AddWithValue("#TimeGenerated", x.TimeGenerated);
com.Parameters.AddWithValue("#Details", x.Message);
db.ExecuteNonQuery(com);
}
// logic to to validate and lock user
SqlCommand com2 = new SqlCommand();
com2.CommandType = System.Data.CommandType.StoredProcedure;
com2.CommandText = "Sp_validateAndLockUser";
com2.Parameters.AddWithValue("#Username", #userName);
db.ExecuteNonQuery(com2);
}

Windows is already capturing and logging invalid logon attempts in Windows Event Log. This can be seen using the application Event Viewer under Windows Logs/Security. But we also can retrieve these logs using C#.
Open Visual Studio as administrator and add this code. Just for testing we're going to get last 10 records.
EventLog securityLog = new EventLog("Security");
var logOnAttempts = (from log in securityLog.Entries.Cast<EventLogEntry>()
where log.EntryType==EventLogEntryType.SuccessAudit
orderby log.TimeGenerated descending
select log
).Take(10).ToList();
Property Message of my last log says:
A logon was attempted using explicit credentials.
Subject:
Security ID: S-1-5-21-3657345512-3965846940-1053971979-1002
Account Name: Daniel_2
Account Domain: Acer
Logon ID: 0x29058
Account Whose Credentials Were Used:
Account Name: jjjjj
Account Domain:
Where "jjjjj" is the user name I typed when trying to log into the page, and Daniel_2 is my Windows account. This value can be easily extracted by means of property ReplacementStrings. In my case ReplacementStrings[5] gets me "jjjjj". I think the query for EventLog entries needs to be filtered by application and date time, so it only shows logons to your web application once it's deployed in IIS.

Related

C# Can not add user to Active Directory. It show error There is no such object on the server

I want to use C# add user to Active Directory from my computer.
AD install in server 10.1.1.5
Username and password for login to AD is "Administrator", "Pass12345678".
I create OU name Guest on AD.
This is my code to add user to AD.
private void Btn_ok_Click(object sender, EventArgs e)
{
UserInfo newUserInfo;
newUserInfo.firstName = "TestName" ;
newUserInfo.lastName = "TestLastName";
newUserInfo.displayName = "TestName Lastname";
newUserInfo.username = "TestName.t";
newUserInfo.sAMAccountName = "TestName.t";
DirectoryEntry adUserFolder = new DirectoryEntry("LDAP://10.1.1.5/CN=Users,OU=Guest,DC=myhome,DC=com", "Administrator", "Pass12345678");
/******** It show error this line **********/
if(adUserFolder.SchemaEntry.Name == "container")
{
DirectoryEntry newUser = adUserFolder.Children.Add("CN=" + newUserInfo.username, "User");
if (DirectoryEntry.Exists(newUser.Path))
{
//Remove exist user
adUserFolder.Children.Remove(new DirectoryEntry(newUser.Path));
}
newUser.Properties["sAMAccountName"].Value = newUserInfo.sAMAccountName;
newUser.Properties["givenName"].Value = newUserInfo.firstName;
newUser.Properties["sn"].Value = newUserInfo.lastName;
newUser.Properties["displayName"].Value = newUserInfo.displayName;
newUser.CommitChanges();
newUser.Invoke("setpassword", "Test123456");
newUser.CommitChanges();
}
}
when I click OK button it show error.
System.DirectoryServices.DirectoryServicesCOMException: 'There is no
such object on the server. '
at line
if(adUserFolder.SchemaEntry.Name == "container")
How to fix it ?
The DirectoryEntry constructor will never throw an exception. It doesn't actually connect to AD until you start using it. Since that line is the first time you are using adUserFolder, that's when it first connects to AD.
The error means what it says: there is no object with a distinguishedName of CN=Users,OU=Guest,DC=myhome,DC=com.
Are you sure you have that right? It seems like you are looking for a container called Users inside of an OU called Guest. Is that what you are trying to do?
Is Users a container or an OU?
You can confirm the distinguishedName by using AD Users and Computers: navigate to the object you want -> right-click -> 'Properties' -> Attribute Editor tab and look at the distinguishedName attribute.
For creating user objects in active directory I've always used UserPrincipals as opposed to DirectoryEntries:
public void create(string lanid, string new_password, string container)
{
using (UserPrincipal new_user = new UserPrincipal(new PrincipalContext(ContextType.Domain, this.domain_string, container)))
{
new_user.SamAccountName = lanid;
new_user.SetPassword(new_password);
new_user.Enabled = true;
new_user.Save();
}
}
In that example "container" would be something like:
"OU=container,OU=container,OU=container,OU=container,DC=domain,DC=domain,DC=domain";
As for your original error with the DirectoryEntries I'd step through it and see if the object is actually set to anything:
The string:
"LDAP://10.1.1.5/CN=Users,OU=Guest,DC=myhome,DC=com"
Doesn't look right to me;
"LDAP://CN=10.1.1.5,CN=Users,OU=Guest,DC=myhome,DC=com"
May work...

The current user has insufficient permissions to perform this operation. Add Termset in sharepoint

I am trying to bind a field to a termset, and if the termset does not exist I want to create it by code. However, even when the code is running with elevated privileges I get the following exception.
The current user has insufficient permissions to perform this operation.
public static void BindTaxonomyField(string taxonomyFieldId, string taxonomyNoteFieldId, string termSetName, string termGroup, SPWeb web)
{
try
{
if (web != null)
{
// get the taxonomyfield from the sitecollection
var field = web.Fields[new Guid(taxonomyFieldId)] as TaxonomyField;
if (field != null)
{
// attach the note field
field.TextField = new Guid(taxonomyNoteFieldId);
// set up the field for my termstore
var session = new TaxonomySession(web.Site);
if (session.TermStores.Count > 0)
{
// get termstore values
TermStore ts = session.TermStores[0];
Group group = GetGroup(termGroup, ts);
if (group == null)
{
ts.CreateGroup(termGroup);
//throw new Exception("Group was not found in the termstore");
}
// ReSharper disable PossibleNullReferenceException
TermSet termSet = group.TermSets.Any(s => s.Name == termSetName) ? group.TermSets[termSetName] : group.CreateTermSet(termSetName);
// ReSharper restore PossibleNullReferenceException
//TermSet termSet = group.TermSets[termSetName];
// actually setup the field for using the TermStore
field.SspId = ts.Id;
field.TermSetId = termSet.Id;
}
field.Update();
}
}
}
catch (Exception ex)
{
}
}
private void BindColumnsToTermStore(string url)
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate
{
using (var site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
if (!web.AllowUnsafeUpdates)
web.AllowUnsafeUpdates = true;
BindTaxonomyField("EF810CD2-F2D2-4BD2-9ABF-C19815F13568",
"67E6E777-0D1E-4840-B858-17400CFABD14",
"Business Audience", "IctDocumentation",
web);
web.AllowUnsafeUpdates = false;
}
}
});
}
If you go in to central administration and navigate to your term store(this is in the left hand nav) in the main container of the page there is a box with a few usernames. Is the account you are running the code in listed? If not stick them in there.
i think the path is something like Central admin -> Manage service application -> Managed meta data service - and the are on the page is call Term store Administrators
There is also one more place you must check but check this first and them run again.
The next place to check is to highlight your Manage metadata service which is located
Central admin -> Manage service application
and click on permissions on the ribbon and make sure the users your running the code with has the correct access.
I always start by making sure i know who i am running the code as first of all then do the checks

C# Facebook SDK: How to

I have tried to find answers on following questions for at least one hour but with no success.
I have WPF project (C#) and I have webBrowser control to navigate to my Facebook page http://www.facebook.com/TennisHelper and I want to do next few things:
I want to avoid login by creating user settings in my application which will contain email and password, but I don't know how to do that with C# Facebook SDK,
I want to make able for my user to post textual posts on that page via textBox control,
I want to make able for my user to post photos from his computer directly to that page, but with not creating new albums. Just to post image on page wall.
I was searching Google for all those problems but with no success
Let me know actually what is your requirement.I think your first requirement is to add a facebook login(or register with facebook page) button in your Website login page.
step1:You need to register a new facebook application on facebook.
step 2:install facebook c# sdk .You can either download the zip file manually or install it using nuget.I recommend the second option.I am using c# sdk 5.4.1 What is nuget? How to install a package using nuget?
step 3:Now you can add name space facebook to the page
step 4:Insert a login button(simply a button with text login) in login page(say login.aspx).Let it be button1
step 5:On click button redire to another page (let login1.aspx)
here is a sample code for login 1
using Facebook;//
FacebookOAuthClient fb = new FacebookOAuthClient();
UriBuilder red = new UriBuilder("www.example.com/Login1.aspx");
protected void Page_Load(object sender, EventArgs e)
{
string appid = "{your app id}";
string appsecret = "{your app secret}";
string permissions = "publish_stream";
if(Request.QueryString["code"] == null)
{
try
{
Response.Redirect("https://www.facebook.com/dialog/oauth?client_id=" + appid + "&redirect_uri=" + red.Uri.ToString() + "&scope=" + permissions +"&state=djfjfdjj");
}
catch (Exception b)
{
Label1.Text = b.ToString();
}
}
else
{
try
{
FacebookOAuthClient cl = new FacebookOAuthClient();
cl.RedirectUri = red.Uri;
cl.AppId = appid;
cl.AppSecret = appsecret;
dynamic result = cl.ExchangeCodeForAccessToken(Request.QueryString["code"]);
Label1.Text = Convert.ToString(result);
if (result["access_token"] != null)
{
Session["access_token"] = result["access_token"].ToString();//Now you have access token
Response.Redirect("Welcome.aspx");//replace welcome.aspx
}
else
{
Label1.Text = "Unable to authenticate\n Please try again later";
}
}
catch(Exception b)
{
Label1.Text = b.ToString();
}
}
}
Now you have access token saved in session.
for getting basic information of the client
dynamic me=fb.Get("\me");
it in cludes first name, last name ,email address,location,image url etc. of the current user.Now you can use this e-mail or name to verify your user or register new user etc.(its up to you ).
posting on that page is possible but diffiult How can I use the Facebook C# SDK to post on Facebook Pages
You should register an application on Facebook in order to use Facebook log in.navigate to
http://developers.facebook.com
create an appllication.You will get an application id and application secret.Use it as appid,appsecret

Problems using captured access token to retrieve user's facebook information

I have been attempting to code a windows form application that interacts with facebook to retrieve the access token that has permissions to get some of the user's information. I have been trying to get the birthday of myself using the following code but it keeps giving me the 400 bad request error. Basically after running this code, and logging in at the authentication it is suppose to show a messagebox containing the user's birthday. In this case, I am using my own user id in the api.GET method. It seems to be the access token issue as when I don't pass in any tokens, i can view public available information such as id using the same code but I print out the access token to check and it seems to be alright. Any help would be much appreciated. First time posting here
public partial class AccessTokenRetrieval : Form
{
private string accessToken=null;
public AccessTokenRetrieval()
{
InitializeComponent();
}
private void accessTokenButton_Click(object sender, EventArgs e)
{
string getAccessTokenURL = #"https://graph.facebook.com/oauth/authorize?client_id=223055627757352&redirect_uri=http://www.facebook.com/connect/login_success.html&type=user_agent&display=popup&grant_type=client_credentials&scope=user_photos,offline_access";
getAccessTokenWebBrowser.Navigate(getAccessTokenURL);
}
private void getAccessTokenWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
{
string successUrl = #"http://www.facebook.com/connect/login_success.html";
string urlContainingUserAuthKey = e.Url.ToString();
MessageBox.Show(urlContainingUserAuthKey);
int searchInt = urlContainingUserAuthKey.IndexOf(successUrl);
MessageBox.Show(searchInt.ToString());
if (urlContainingUserAuthKey.IndexOf(successUrl) == -1)
{
string accessTokenString;
accessTokenString = Regex.Match(urlContainingUserAuthKey, "access_token=.*&").ToString();
this.accessToken = accessTokenString.Substring(13, accessTokenString.Length - 14);
//100001067570373
//MessageBox.Show(accessToken);
accessTokenTextBox.Text = this.accessToken;
Facebook.FacebookAPI api = new Facebook.FacebookAPI(this.accessToken);
JSONObject me = api.Get("/100001067570373");
MessageBox.Show(me.Dictionary["user_birthday"].String);
}
}
#
I would request you to try http://facebooksdk.codeplex.com and checkout the samples folder.
It includes sample for WinForms authentication and also making various request to Facebook.
Here are other useful links that I would recommend you to read.
http://blog.prabir.me/post/Facebook-CSharp-SDK-Writing-your-first-Facebook-Application.aspx
http://blog.prabir.me/post/Facebook-CSharp-SDK-Making-Requests.aspx

When user hit's the site the custom error page is shown. Why? This is to few users and sporadic

Could somebody please help me?
We are developing a asp.net application using asp.net 2.0 framework. The issue is sporadic. As soon as a particular user hits the site in production a custom error page is shown. I been told that this user could get in successfully some times and after some idle time he is getting this error page. We not even not yet log in to site. Just as soon as i hit the site Ex:- www.Mywebsite.com the custom error is dispalyed. Could somebody help me on this. One more thing i have on my local machine .net 3.5 service pack1 installed and in production on only once server the service pack is installed. Could this be the cause of the problem?. some times it is showing the page and some users custom error. They not even visited the login screen yet. As soon as some users hit the site they see the customer error page, instead of login page. As i told this is happening as the user hitting the site I started checking my load code of index.aspx (page set up in virtual directories documents as start up page) and this is the code i am using.
My each .aspx page is inheriting the PageBase class which has the below method overriden and with the below code. If you see carefully the expiration of "langCookie" been given as 30 minutes. Will this be a problem? Below is a little code of my PageBase and my index.aspx. I am not sure what user's are doing. I heard it comes sporadically, so became hard to reproduce. One more thing since this is mix of asp and aspx pages i used below in web.config, Otherwise i am gettinig the sqaure characters in classic asp pages when i open them.
PageBase.cs Code:-
protected override void InitializeCulture()
{
base.InitializeCulture();
HttpCookie langCookie = null;
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
foreach (string s in Request.Cookies)
{
if (HttpUtility.UrlDecode(Request.Cookies[s].Name) == SESSION_KEY_LANGUAGE)
{
langCookie = new HttpCookie(SESSION_KEY_LANGUAGE);
langCookie.Value = HttpUtility.UrlDecode(Request.Cookies[s].Value); langCookie.Expires = DateTime.Now.AddMinutes(30.0);
Response.Cookies.Add(langCookie);
break;
}
}
}
else
{
langCookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null != langCookie)
{
if (langCookie.Value != "")
{
CultureInfo cultureInfo = new CultureInfo(langCookie.Value);
ApplyNewLanguage(cultureInfo);
}
}
}
index.aspx.cs:- The starting page in virtual is set as index.aspx
protected void Page_Load(object sender, EventArgs e)
{
//Set sign button as default button for login (press enter)
Page.Form.DefaultButton = "ButtonSignIn";
//Get Cookie Language
if (null == Request.Cookies[SESSION_KEY_LANGUAGE])
{
cookie = new HttpCookie(SESSION_KEY_LANGUAGE);
}
else
{
cookie = Request.Cookies[SESSION_KEY_LANGUAGE];
}
if (null == Request.Cookies[SESSION_KEY_LANGUAGE_FORASP])
{
cookieASP = new HttpCookie(SESSION_KEY_LANGUAGE_FORASP);
}
else
{
cookieASP = Request.Cookies[SESSION_KEY_LANGUAGE_FORASP];
}
if (!IsPostBack)
{
//check if chkbtaccess cookies exists
if (null != Request.Cookies[CHECKACCESS])
{
HttpCookie cookieCheckAccess = Request.Cookies[CHECKACCESS];
string strCKBTC = DecryptUsernamePass(cookieCheckAccess.Value.ToString());
if (String.Compare(strCKBTC, string.Empty) != 0)
{
string[] aryCKBTC = strCKBTC.Split(Convert.ToChar(","));
TextBoxUsername.Text = aryCKBTC[0];
TextBoxPassword.Text = aryCKBTC[1];
CheckBoxRememberMe.Checked = true;
}
}
private string DecryptUsernamePassword(string strText)
{
string strDecryptedUsernamePassword = string.Empty;
strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Default));
//strDecryptedUsernamePassword = CommonUtil.EncryptDecryptHelper.Decrypt(HttpUtility.UrlDecode(strText, Encoding.Unicode));
return strDecryptedUsernamePassword;
}
private string EncryptUsernamePassword(string strText)
{
string strEncryptedUsernamePassword = string.Empty;
strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Default);
//strEncryptedUsernamePassword = HttpUtility.UrlEncode(CommonUtil.EncryptDecryptHelper.Encrypt(strText), Encoding.Unicode);
return strEncryptedUsernamePassword;
}
As a starting point, you should add some logging and exception handling in this code so that you can narrow down what the error could be. It would also make your code more robust and tolerant to invalid cookie values.
An easy way to do this would be to implement the error handler in Global.asax:
protected void Application_Error(Object sender, EventArgs e)
{
Exception exception = Server.GetLastError();
}
This should give you the exception that occurred, which you can then examine (eg. in the debugger, log it to a file, etc...) to see what is causing the error.
For a temporary measure, you could turn off custom errors in web.config:
<customErrors mode="Off"/>
This will enable you to see the exception in your web browser when it occurs. I wouldn't recommend that you use that setting on a live site though.

Categories