How to implement alternative login for asp.net forms authentication? - asp.net

I have an existing website using forms authentication with Sql provider. Now i am trying to integrate with another website and use their authentication mechanism. I am already able to validate a user and trying to silently login the user into my application. Here is the code for "silent" login:
if (user != null) // logged in!
{
IPrincipal principal = new MyPrincipal(user);
FormsAuthentication.SetAuthCookie(user.ScreenName, true);
HttpContext.Current.User = principal;
Response.Redirect("~/Default.aspx");
}
and it works with the exception that Forms Authentication overrides the HttpContext.Current.User by the time i make it "default.aspx". Is there a way to bypass forms role and membership providers?

If you are using a custom principal, the custom principal must be established on every request to the web server; it's not persisted. Adding code to reload it in global.asax would resolve it. Others have created an HTTP module to do this too.
HTH.

Related

How can I combine windows login and anonymous authentication by using AD in asp.net boilerplate (.net mvc)? IIS HTTP Error 404.15

I have followed the instructions like the guide said:
LDAP/Active Directory
and How to use LDAP in ASP.NET Boilerplate (Free Startup Template)
But with no success.
Below is my trial and error:
User Scenario:
Most of the users are from the domain, so those domain users should not see the login page and should be able to auto login the platform.
Some of the users are not domain users, for those who have access to the platform but not belong to the domain should pop out the login page and input username/password to login.
Here is a snap of my authentication code:
If(!HttpConetxt.User.Identity.IsAuthenticated)
{
var domainUserName = System.Web.HttpContext.Current.User.Identity.Name;
var entry = new DirectoryEntry("XXX");
var search = new DirectorySearcher(entry);
search.Filter = "(sameaccountname=)" + domainUserName + ")";
// Check if the user is in domain or not
var result = search.FindOne();
if(result != null)
{
//Domain user, find the mapping user in db and login using the db user
...
}
}
Since the website should support both anonymous and windows authentication, I enabled both authentication method:
And also add [AllowAnonymous] attribute to Login ActionResult.
Per my understanding, the request authentication is performed in global.aspx, So I guess my authentication logic should have something to do with this:
protected void Application_AuthenticateRequest()
{
...
}
But it just seems that I could not put my authentication code in there. Because anyway, I need to use the db user to manage user roles, but in the global.aspx, the UserManager is not even there.
I have tried to add this piece of code into Login ActionResult, but there's a problem: when domain user logs out, it will constantly login as it can not tell if the user is actually logged out or just comes to the website.
So:
Where is the right place to put those authentication code?
How does the Ldap work in this scenario? Does Ldap meet the requirements? I could never get the Ldap work in my project.

ASP.NET MVC authentication using http header

In my ASP.NET MVC 4 application I need to authenticate the user using an existing http header value which contains the username.
It works using form authentication : the user is redirected to a login page when he is not authenticated yet. The controller of the login page check the httpHeader value and connect the user using FormsAuthentication.SetAuthCookie(username,false) and redirect the user to the main page of my application.
But I want to avoid this redirection and directly try to authenticate the user when the event 'user not authenticated' is fired.
Axes :
FormsAuthentication_OnAuthenticate
Override AuthorizeAttribute
AuthenticateRequest
If i understood you correctly then you just need to set currentPrincipal with username
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user, "Basic"), new string[] {});
So from now it will work and you can access user as well User.Identity.Name

How set Authorization attribute role MVC4 to the user?

I'm trying to use the Authorize attribute on MVC 4 application,
[Authorize(Roles = "Administrator, Super-User")]
public JsonResult Remove(int id)
{
.
.
.
}
I know that only the roles "Administrator" and "Super-User" roles are authorized to execute the method Remove, but how I can set the role to the actual User of the application?
The answer is - somehow, so that HttpContext.Current.User is set and the IsInRole method returns true.
The easiest way to do this would be to follow one of built-in mechanisms of authentication/authorization: Forms authentication or Windows authentication.
The former requires that the request carries a valid forms cookie issued by the server. The latter requires that the request principal can be authenticated in the domain controller.
You are however free to implement a custom authentication module.
If you are just starting to learn this, probably you'd like to use Forms Authentication for this. Just let your users log in, issue the cookie and the cookie will automatically be carried by subsequent ajax request (assuming your server code is called from within javascript client-side ajax call).
You can Add the current user to a role using
Roles.AddUsersToRole(new string[]{HttpContext.Current.User.Identity.Name}, "Admin");
Roles class is available in System.Web.Security namespace.
if you want to add users and Roles
-Open your solution in Visual Studio
goto project->ASP.NET configuration->Security Tab
You can add a user to roles using a Role Provider.
var rolesProvider = (SimpleRoleProvider)Roles.Provider;
Check the role exists
if (!rolesProvider.RoleExists("SuperUser"))
{
rolesProvider.CreateRole("SuperUser");
}
Check if the user is in the role already, if not, add the user to the role
if (! rolesProvider.IsUserInRole("JohnSmith", "SuperUser"))
{
rolesProvider.AddUsersToRoles(new[] {"JohnSmith"}, new[] {"SuperUser"});
}

Login modes other than forms authentication is ASP.NET

Am trying to design login page for my website and I am looking for methods other than forms authentication. The way in which I am trying is to have a table in the database that stores user information and check for the user validity.
The point where I get struck is how do i set cookies and session variables and how will I carry it through out the system. Can anyone tell/suggest me where I can relevant material so as to move forward. And also is my idea of negating traditional forms authentication and going for a model I described, is it good also does any other better method exist?
You can do this even with forms authentication itself...
For Forms Authentication to work, you need not have to use the Complete Database Setup that MS uses to Authenticate. You can simply have your own Database and Validate a user yourself, and just set the cookie.
String UserName = "CoolGuy";
String PassWord = "Pwd"
Boolean isValidUser = YourClass.YourMethod(UserName, PassWord);
if (isValidUser)
{ FormsAuthentication.setAuthCookie(UserName, false); }
This will authenticate the user "CoolGuy" for the session, provided YourMethod returns true. And you need to put this code only in Login Page... and the user will automatically be authenticated for the entire session or whatever...
Please see my response to another similar question here... ASP.NET access controls

How to get the asp.net login control to auto authenticate a previously authenticated user?

I am trying to to set up the login control to remember the login credentials of a user who has previously entered their user name and password successfully. I set the remember me property to true, but it doesnt seem to triger any events where I could read the cookie and auto login the user.
Is there a straightforward mechanism to accomplish this?
You need to Google for Forms Authentication in ASP.NET 2.0
You will need to set up your application (via web.config) and may also need to alter IIS settings. While it's all quite straightforward, there are heaps of settings that can be used, so best is to read some of the articles. ScottGu has a
blog entry that goes into a lot of good detail.
There are also many good video's at www.asp.net including these Security Tutorials
try How to: Create an ASP.NET Login Page and Walkthrough: Creating a Web Site with Membership and User Login. If I recall, you still have to do the authentication yourself unless you use the Sql Server Membership provider. In that case you still have to set up the database and web.config.
Essentially, once you've set up configuration properly, you have a login page. In that login page you tell Forms Authentication to create the authentication ticket for you once you authenticate them:
if (VerifyUser(name, password) ) // this is not a framework method
FormsAuthentication.RedirectFromLoginPage(
userName, false); // no persistent cookie
If you want to read the authentication ticket data (from anywhere else).
// output just writes to a StringBuilder 'sb'
output(sb, "Identity.AuthenticationType", Page.User.Identity.AuthenticationType);
FormsIdentity fi = Page.User.Identity as FormsIdentity;
if (fi == null)
{
output(sb, "Identity Type", Page.User.Identity.ToString());
return;
}
output(sb, "FormsIdentity.Ticket.IssueDate", fi.Ticket.IssueDate);
output(sb, "FormsIdentity.Ticket.Expiration", fi.Ticket.Expiration);
output(sb, "FormsIdentity.Ticket.Name", fi.Ticket.Name);
output(sb, "FormsIdentity.Ticket.CookiePath", fi.Ticket.CookiePath);
output(sb, "FormsIdentity.Ticket.UserData", fi.Ticket.UserData);
output(sb, "FormsIdentity.Ticket.Version", fi.Ticket.Version);
output(sb, "FormsIdentity.Ticket.IsPersistent", fi.Ticket.IsPersistent);
The point is, once authenticated, asp.net will only redirect the user to the login page if the authentication ticket has expired and the user is on a protected page. Asp.net doesn't keep asking you to authenticate the user unnecessarily.

Resources