I'm using the ASP.NET membership provider on my website. It works fine while using the Login Control in Visual Studio. However, I feel the Login Control has its limitation and I'm having a hard time making it fit to the design of my page. So instead of using that Login control, I'd like to be able to just create two TextBox's and a Button myself and use that to login instead. So my question is, can I create a custom login page with by creating my own textbox's and buttons? The code behind Login.aspx that I use with the login control right now looks like this:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Membership.ValidateUser(Login1.UserName, Login1.Password) == true)
{
Login1.Visible = true;
Session["user"] = User.Identity.Name;
FormsAuthentication.RedirectFromLoginPage(Login1.UserName, true);
}
else
{
Response.Write("Invalid Login");
}
}
I tried changing Login1.UserName to TextBox1.Text and so on, but that didn't work. Any help is appreciated, thanks!
You should be removing Login1_Authenticate event and have a login button event to validate the credentials.
Or depending on how you submit back to server, such as ajax calls etc.
You can also use fiddler to see what's exactly being posted back to server.
PS. Why do not use ASP.net MVC?
Related
I am a new bee creating an asp.net web application for my application. I will have different users and i didn't use any special forms or methods to do the login. I have access db , in there i have some user role, company,username , and password.
In my login page through text box i will get company username and password inputting by the end user. then i will check for the company and username (which is primary key in the table.) if the password matches then will find the user role and redirect to the pages for each user.
that works fine now.
I have a log out button which is sitting in the sitemaster page and
<div id="logout" runat="server" visible="false" class="navbar-brand1">
<a id="lo" runat="server" href="/Default">Log Out </a>
</div>
then in the pages where i want to show the log out i will call the code
Master.FindControl("logout").Visible = true;
it was working fine in respect of login in and login out . but infact the log out button just redirects to the first page on site and if we do the back arrow in the browser i can go back to the prevs page i was on. Is there any way i can do it neatly so that after log out even though if i go back on the browser it will ask for log in .
Any help will be really appreciated. I made a mistake and created complete application now i am worried about this feature so technically i am not logging out :(
Whenever a user opens a page in the system use below code to check if the session is valid
if (!IsPostBack)
{
if (Convert.ToString(Session["UserName"]).Length <= 0)
{
Response.Redirect("Login.aspx");
}
}
When the user clicks on SignOut button, make redirection to a SignOut.aspx page. Use below code in the form load event of SignOut.aspx to clear the session.
protected void Page_Load(object sender, EventArgs e)
{
Session.Abandon();
Session.Contents.RemoveAll();
System.Web.Security.FormsAuthentication.SignOut();
Response.Redirect("Login.aspx");
}
Well, your question is how to do the
proper login
The proper way is not to reinvent the wheel, but use the framework that is built in in ASP.NET
https://msdn.microsoft.com/en-us/library/ms731049%28v=vs.110%29.aspx
It will give you a lot of extra features, like using OpenAuth etc.
Example
"https://msdn.microsoft.com/en-us/library/aa354509%28v=vs.110%29.aspx
As #Chathuranga Ranasinghe mentioned I used session varibale to store the username details and i will check if the session variable empty then go to my default page otherwise continue.
if (((string)Session["iden"]) )
{
Response.Redirect("/Default.aspx");
}
i used this on the pages comes after logged in and it works fine for me now.
Reason i'd like to add additional text is because, for whatever reason when i try to login and it wants me to add "#domain.local".
Is it possible to add that automatically? I tried converting it to a template and used UserName_TextChanged but it didn't like what i was trying to do.
Any ideas?
Thanks.
Based on the information on the web.config you are using Forms Authentication with an LDAP provider. I am going to make the assumption that you are using the ASP.NET Login control on your page.
In order to handle the appending of #domain.local to a user name prior to login you should handle the LoggingIn Event from the control with something similar to the following:
void OnLoggingIn(object sender, System.Web.UI.WebControls.LoginCancelEventArgs e)
{
if (Login1.UserName.IndexOf("#domain.local", StringComparison.OrdinalIgnoreCase) == -1)
{
Login1.UserName += "#domain.local";
}
}
Of course you probably need a more precise process to determine the proper way to handle the user name.
You can find more information about the login control and its events here:
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.login.loggingin(v=vs.110).aspx
For each page in my ASP.Net WebForms app I check the user's access like this:
protected void Page_Load(object sender, EventArgs e) {
if (!UserCanAccessPage())
RedirectToAccessNotPermitted();
// < if user has access, set up the page >
}
My question is, is that single check enough or should I check at all other handlers:
protected void seriousDeleteButton_Click(object sender, EventArgs e) {
// ** DO I NEED TO CHECK ACCESS AGAIN HERE? **
// < do stuff that only some users have access to >
}
I know under a normal page lifecycle the Page_Load() should always be called before the event handlers, but I'm wondering if there's a tricky way to hit other ASP.NET endpoints with curl or mucking around with javascript or something.
(I'm only talking about regular WebForms-style postbacks, no explicit AJAX stuff. But of course UpdatePanel uses asynchronous javascript and I'm sure other controls do to.)
Yes, it is enough, because Page_Load will be called every time a user requests a new page or posts back the page. You do not need to check again in button click events.
However, it is fine with a website with a couple of pages. In other words, if you have multiple pages, maintenance is will be nightmare.
Normally, you want to use Form Authentication, and restrict acesss to pages by using web.config.
I wonder if I can simulate the action of the button
(source: xonefm.com)
in this website by VB.NET code ?
http://www2.xonefm.com/hot10/index_in.aspx
From server code you could use ClientScriptManager.GetPostBackEventReference which renders out a postback event reference
heres a link on msdn http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackeventreference.aspx
heres a sample
Allows selecting gridview row without select column.
protected override void Render(HtmlTextWriter writer)
{
GridView g = GridView1;
foreach (GridViewRow r in g.Rows)
{
if(DataControlRowType.DataRow == r.RowType)
{
r.Attributes["onMouseOver"] = "this.style.cursor='pointer';this.style.cursor='hand'";
r.Attributes["OnClick"] = ClientScript.GetPostBackEventReference(g, "Select$" + r.RowIndex, true);
}
}
base.Render(writer);
}
Is this your web site? If so, you can probably just call the click event for the button directly (assuming it causes a postback).
Are you scraping someone else's site? In that case, use a System.Net.WebClient or System.Net.HttpWebRequest object to send a similar request to the server that the browser would send if you click the button. There are two ways to find out what the request will be:
Study the source of the page in question until you understand what http request is sent when you click the button. This can be especially tricky for asp.net sites because of the hidden ViewState field.
Use something like WireShark to sniff the packet sent and work backwards from that.
I have a search form in an app I'm currently developing, and I would like for it to be the equivalent of method="GET".
Thus, when clicking the search button, the user goes to search.aspx?q=the+query+he+entered
The reason I want this is simply bookmarkable URLs, plus it feels cleaner to do it this way.
I also don't want the viewstate hidden field value appended to the URL either.
The best I could come up with for this is:
Capture the server-side click event of the button and Response.Redirect.
Attach a Javascript onclick handler to the button that fires a window.location.replace.
Both feel quirky and sub-optimal...
Can you think of a better approach?
Use a plain old html form, not a server side form (runat=server), and you should indeed be able to make it work.
This could however be a problem if you have an out of the box visual studio master page which wraps the entire page in a server side form, because you can't nest forms.
Web forms don't have to suck, but the default implementations often do. You don't have to use web forms for everything. Sometimes plain old post/get and process request code will do just fine.
I worked on a web site that had to post to a 3rd party site to do the search on the client's web site. I ended up doing a simple Response.Redirect and passed in the search parameters through the query string like so:
protected void Button1_Click(object sender, EventArgs e)
{
string SearchQueryStringParameters = #"?SearchParameters=";
string SearchURL = "Search.aspx" + SearchQueryStringParameters;
Response.Redirect(SearchURL);
}
And on your Search.aspx page in your pageload...
protected void Page_Load(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(Request.QueryString["SearchParameters"]))
{
// prefill your search textbox
this.txtSearch.Text = Request.QueryString["SearchParameters"];
// run your code that does a search and fill your repeater/datagrid/whatever here
}
else
{
// do nothing but show the search page
}
}
Hope this helps.
This function permits to submit a page using the GET method.
To submit a page using the get method you need to:
add this code Form.Method="get"; in the Page_Load method
Use this code < asp:Button runat="server" ID="btnGenerate" /> as a submit button
add rel="do-not-submit" attribute to all form elements that you don't want to include in your query string
change the codebehind logic of your page using Request.QueryString
disable the page viewstate with EnableViewState="false" (unless it's used for other purposes)
Code
$(document).ready(function(){ enableSubmitFormByGet(); });
function enableSubmitFormByGet(){
if($("form").attr("method") == "get"){
$("form").submit(function() {
$("[name^=" + "ctl00" + "]").each(function(i){
var myName = $(this).attr("name");
var newName = "p" + (i-1);
$(this).attr("name", newName);
});
var qs =$(this).find("input[rel!='do-not-submit'],textarea[rel!='do-not-submit'],select[rel!='do-not-submit'],hidden[rel!='do-not-submit']").not("#__VIEWSTATE,#__EVENTVALIDATION,#__EVENTTARGET,#__EVENTARGUMENT").serialize();
window.document.location.href = "?" + qs;
return false;
});
I would do (b) since (a) would require two round trips for a single query. Alternatively, you could disable viewstate on the page, remove any other hidden fields via javascript, and also use javascript to modify the form method from post to get. I've never done this for real, but my toy page using the included sample worked like a charm. It's arguably easier than encoding the search string and doing the get via javascript.
Actually, it sounds like you would be happier with ASP.NET MVC since this is easily doable there by simply setting the form method to GET in the view.
sample code using jquery
$(document).ready( function() {
$('input[type=hidden]').remove();
$('form').attr('method','get');
});
EDIT: It seems like you ought to be able to do the same thing server-side, too. Maybe in OnPreRenderComplete. Don't have access to Visual Studio right now to check.
I have always used Response.Redirect as it "works".
I don't think there is an optimal method.
Just use this in your .click event before the form submission:
$("#__VIEWSTATE").remove();
$("#__EVENTVALIDATION").remove();