FormsAuthentication.SetAuthCookie in Generic Handler ashx - forms-authentication

I have an Generic Handler where I would like to auto-login based on some querystrings.
But then I set FormsAuthentication.SetAuthCookie(user.Name, false), but HttpContext.Current.User.Identity.IsAuthenticated return false, and I can't redirect because of the limits set in web.config.
So how do I set FormsAuthentications in an .ashx-file?

To perform a login using the FormsAuthentication module, you may want to just use the RedirectFromLoginPage static method, which, under the covers:
prepares the authentication token;
encrypts it;
adds it to the cookie collection of the response;
performs the redirect to the required page (or the default one, as per your web.config).
Here is a short prototype for your handler:
public void ProcessRequest(HttpContext context)
{
// TODO: Determine the user identity
var username = context.Request.QueryString["username"];
FormsAuthentication.RedirectFromLoginPage(username, true);
}
If you are not comfortable by the way this method performs its job, you may do each activity in a manual way:
prepare a FormsAuthenticationTicket with the user name;
encrypt it by way of the Encrypt method;
add it to the response Cookies;
issue a redirect.

Have you tried adding it as a location path in the web.config?
<configuration>
<location path="foo.ashx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location >
<system.web>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
</location>
</configuration>

Related

Web config allow users not working

I have the below in my web config file on a forms authenticated web site, but it does not allow a user to navigate to that page unless they login.
<configuration>
<connectionStrings>
<remove name="******"/>
<add name="*******" *******"/>
<add name="*****" *******"/>
</connectionStrings>
<location path="About.aspx">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
ASP.net web forms 4 site. NOTE *** hide original data
Your Question it not clear .But again Enable From Authentication by adding this line
<system.web>
<!--Session state Time Out-->
<sessionState timeout="60" />
<!--My authontication module-->
<authentication mode="Forms">
<forms name="PROJECTNAME.ASPXAUTH" loginUrl="~/Login.aspx" protection="All" path="/" timeout="60"/>
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
and It will secure the web application.If you want to access any particular folder then create a folder and add Web.config file.and in web.cofig file
<?xml version="1.0"?>
<configuration>
<system.web>
<authorization>
<!--Defualt access grant sa=11,admin=12-->
<allow roles="admin"/>
<!--Order and case are important below-->
<deny users="*"/>
</authorization>
</system.web>
</configuration>
prevent access of users of role other than admin
and create role by
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
1, // Ticket version
Convert.ToString(user.UserID), // Username associated with ticket
DateTime.Now, // Date/time issued
DateTime.Now.AddMinutes(60), // Date/time to expire
false, // "true" for a persistent user cookie
Convert.ToString(user.RoleID), // User-data, in this case the roles
FormsAuthentication.FormsCookiePath);// Path cookie valid for
// Encrypt the cookie using the machine key for secure transport
string hash = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(
FormsAuthentication.FormsCookieName, // Name of auth cookie
hash); // Hashed ticket
// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = ticket.Expiration;
// Add the cookie to the list for outgoing response
Response.Cookies.Add(cookie);

Redirect for some pages and deny access for others?

I'm using forms authentication.
In the root web.config there's ...
<authentication mode="Forms">
<forms loginUrl="~/Auth/Login.aspx" timeout="2880" defaultUrl="~/Search.aspx" />
</authentication>
... so if an unauthenticated user is denied access, by a entry like the following in the web.config of a subfolder ...
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
... then the not-logged-in user is redirected to the Login.aspx page.
First question
If an unauthenticated users requests some (but not all) pages, or requests files from one sub-folder (but not another), I want to deny access by returning HTTP 403 instead of redirecting them (HTTP 302) to the login page.
How can I do that? Currently unauthenticated users are invariably redirected to the Login page, instead of being simply denied access.
Second question
I'm also using 'role-based' privileges, for example I have a role named Supervisors.
Access to certain folders is intended only for supervisors so those folders have a web config like
<system.web>
<authorization>
<allow roles="Supervisor"/>
<deny users="*"/>
</authorization>
</system.web>
If an authenticated (logged-in) user without the Supervisor role attempts access, they too are redirected to the Login page (although they're already logged-in).
Can I change that, somehow (e.g. to return HTTP 403, or to redirect to some other failure page)?
You will have to do this manually by creating a Procedure which will run on Page_Init
Public Shared Sub CheckAccess()
If My.User.IsAuthenticated And (Condition Here) Then
Response.Redirect("AccessDenied.aspx")
End If
End Sub
Protected Sub Page_Init (sender As Object, e As EventArgs) Handles Me.PageInit
CheckAccess()
End Sub

How to check if user is logged in

I have created a Login page where users must provide username and password to have access to some specific resources, where they can upload images, or just edit some description about themselves.
My web.config file looks like this:
<authentication mode="Forms">
<forms loginUrl="Secure/Login.aspx" defaultUrl="index.aspx" name=".ASPXFORMSAUTH" timeout="30"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="Secure">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
So when the user has typed in the username and pw, he is redirected to the index.aspx page.
Depending wether the user is logged in or not, the index.aspx should show or hide some stuff.
This is how I check if he is logged in:
bool isLoggedIn = HttpContext.Current.User.Identity.IsAuthenticated;
if (isLoggedIn)
{
placeHolder2.Visible = true;
...
}
Now the problem is that the: HttpContext.Current.User.Identity.IsAuthenticated; ALWAYS returns true, so unauthorised people will be seeing the stuff that should be hidden.
I am not sure about the: HttpContext.Current.User.Identity.IsAuthenticated;
I just googled "How to check if user is logged in", and suggestions were the:
HttpContext.Current.User.Identity.IsAuthenticated;
I want only the people that are logged in to view the private stuff. How do I go about this? How do I make the: HttpContext.Current.User.Identity.IsAuthenticated only return true when the user is logged in?
Thanks
if (Request.IsAuthenticated) {.....}
edit based on some comments
Authenticated via "Forms", check here
HttpContext.Current.User.Identity.IsAuthenticated // will be "Forms" if using forms based auth
// "Negotiate" is using windows integrated
// etc
If using .net 4.5 and you wanted "SET" user claims.
The ClaimsPrincipal is recommended reading
bool isLoggedIn = System.Web.HttpContext.Current.User.Identity.IsAuthenticated
My coding is
bool val1 = (System.Web.HttpContext.Current.User != null) &&
(System.Web.HttpContext.Current.User.Identity.IsAuthenticated) &&
(System.Web.HttpContext.Current.User.Identity.AuthenticationType.ToString() == "Forms");
for identifying the users with domain login and logged in form

How does ASP.NET's Authentication module work?

I can not make it clear about how the asp.net's authentication work,I set the following configuration according to the help document and google:
<configuration>
<!--
Login.aspx and the random_code_img.aspx does not need authentication
But excluding the above files,all the page are protected.
-->
<location path="Login.aspx">
</location>
<location path="random_code_img.aspx">
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
</location>
<system.web>
<authorization>
<deny users="?"/>
</authorization>
..........
</system.web>
</configuration>
Now in the login.aspx.cs:
Within the method loginButton_click:
if (Membership.ValidateUser(username, password))
{
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
username,
DateTime.Now,
DateTime.Now.AddMinutes(30),
isPersistent,
"",
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
// Create the cookie.
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
// Redirect back to the protected URL.
Session["havelogined"] = "1";
HttpContext.Current.Response.Write("<script>location.replace('Default.aspx')</script>");
}
else{
//do something
}
However in the login.aspx,after I enter the name and password,then click the login button,I was redirected to Default.aspx in the address bar of the browser,but I can not see the content of the Default.aspx,I just see:
Access is denied.
Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.
Error message 401.2................
So I wonder how does the asp.net's authentication know if I am logined or not? Can I repace these notice with some readable information?
Also,
<system.web>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
What does the "users" here mean?
I do not think they are the registered users in my database.
HTTP 401.2 status code corresponds to "No Authentication method configured". I'll need more info to confirm. If I had to guess I'd say you are missing the <forms> tag under the <authentication> tag.
If you haven't already found this article, you might try this link which talks about how to fully setup forms authentication - http://msdn.microsoft.com/en-us/library/xdt4thhy.aspx
the
<allow users="*"/>
means allow all users. In essence it is instructing ASP.NET to allow all users (authenticated or unauthenticated) access to random_code_img.aspx
BTW:
<deny users="?"/>
means don't allow unauthenticated users.
Hope this helps.
Inside your loginButton_click method, after you validate your user, you can simply use
FormsAuthentication.RedirectFromLoginPage
See here for more information and example . http://msdn.microsoft.com/en-us/library/ka5ffkce.aspx

WCF, ASP.NET Compatibility Mode and custom authentication using membership providers

I need help in following:)
To begin with I work on the large application, that has a WinForms client and server. Server in our case is the set of WCF services. There is one service that is responsible for authentication of users. The logic of authentication is custom and complex and authentication service uses different membership providers.
We want to protect the access to server services for non-authenticated users. The users must firstly authenticate and than use other services (users in this case are the other systems, services, WinForms client, etc.). On this basis, we decided to use the ASP.NET Url/File Authorization feature.
So, I set on the ASP.NET compatibility mode, allowed cookie in all binding configurations, added AspNetCompatibilityRequirements attribute to our services and added the followingconfigurations to config:
<authentication mode="Forms">
<forms cookieless="UseCookies">
<credentials passwordFormat="Clear" />
</forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
...
<location path="AuthenticationService.svc">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
In the authenticate method of our authentication service I add the following code:
public AuthenticationResult AuthenticateUser(string username, string password)
{
AuthenticationResult result = new AuthenticationResult();
result = Authenticate(username, password);
if (result.IsAuthenticated)
FormsAuthentication.SetAuthCookie(username, true);
return result;
}
Next, I wrote the following code:
var authClient = new AuthenticationServiceClient();
var result = authClient.AuthenticateUser("user", "password");
var otherClient = new OtherServiceClient();
var temp = otherClient.DoSomething();
But after authentication I can't access to OtherServiceClient...
So, how can I share the call context between the WCF services calls? Could anybody provide some useful articles about this question?
Thanks in advance!
Best regards.
You need to:
1) Enable sessions in WCF
2) Authenticate using WCF
3) Keep reusing your proxies instead of creating new ones.
This is useful:
http://msdn.microsoft.com/en-us/library/ms733040.aspx

Resources