Application won't read username on IIS - c#

I have this application where I login by the PC user. I'm using this:
public static bool IsAuthenticated()
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
CurrentUser = Factory.Users.List(item => item.Username.ToLower() == cToLower()).FirstOrDefault();
}
return CurrentUser != null;
}
Note: .List(), is a method I created to list all database Users (in
this case).
Everything works fine. But when I publish my Website on my IIS, HttpContext.Current.User.Identity.Name is returning nothing, no user at all. What is wrong with it? Any suggestion?

You have to enable IIS Windows Authentication and Deny Annomyous acces. You can either configure your IIS or update your configuration file as follows,
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</configuration>

Related

IIS Authentication - calling the same server

I have a problem connecting from SITE A to SITE B on the same IIS Server.
SITE A acts as SPA (aspx) and consumes an API (web api) of SITE B, both on .net 4.6.1.
In my deployment env, they are both subdomains of the same domain living on the same V-Server.
If I'm on my dev environment it works with the following code:
protected async Task<HttpResponseMessage> Get(string urlParam = "")
{
string url = _url;
if (!string.IsNullOrWhiteSpace(urlParam))
{
url = $"{_url}?{urlParam}";
}
NetworkCredential credentials = null;
if (!string.IsNullOrEmpty(ServiceUser))
{
credentials = !string.IsNullOrEmpty(ServiceuserDomain)
? new NetworkCredential(ServiceUser, Servicepassword, ServiceuserDomain)
: new NetworkCredential(ServiceUser, Servicepassword);
}
using (var handler = new HttpClientHandler {Credentials = credentials})
{
using (var httpClient = new HttpClient(handler))
{
HttpResponseMessage responseMessage = null;
try
{
responseMessage = await httpClient.GetAsync(url);
}
...
I can also connect with that code to my deployed API (SITE B)
The web.config of SITE A has no "special" configurations. Anonymous Authentication is enabled and Windows Auth disabled.
The web.config of SITE B has the following "special" configuration:
<system.web>
<compilation debug="true" targetFramework="4.6.1" defaultLanguage="c#" />
<httpRuntime targetFramework="4.6.1" />
<customErrors mode="Off" />
<authentication mode="Windows"/>
<authorization>
<allow users="?"/>
</authorization>
</system.web>
<location path="swagger">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
</location>
<location path="api">
<system.web>
<authorization>
<deny users="?"/>
<allow users="*"/>
</authorization>
</system.web>
</location>
Which basically allows anonymous access to the site except for /api and /swagger.
If I test the API call to SITE B from POSTMAN using the new BETA Authentication NTLM it works aswell. The credential are definitly not wrong, but whenever I go throug the log files of SITE B I see:
2019-06-03 12:08:43 212.147.60.15 GET /api/form/ from=0&to=99/ 443 - IP HTTP/1.1 - - sub.domain.ch 401 0 0 2661 114 0
2019-06-03 12:08:43 212.147.60.15 GET /api/form/ from=0&to=99/ 443 - IP HTTP/1.1 - - sub.domain.ch 401 1 3221225581 6661 773 0
Also, both sub-domain on that server have the same IP address, but I don't think that's related.
Unfortunately in my case I cannot access the Windows Server. I just have a PLESK access to manage the domains / files.

How to configure IIS Express properly so that it would allow anonymous login

I'm converting my current MVC application which uses windows based authentication to forms based. I have made changes in web.config and global.asax file. Now when I run the application, it goes to login page and with the user's credentials validated, its gets navigated to other page. My issue is when I do a signout, my applicationhost.config file gets rewrited from
<windowsAuthentication enabled="false" />
to
<windowsAuthentication enabled="true" />
and then if I hit the home page of my application, it takes my windows credentials.
In my web config I do have
<authentication mode="Forms">
<forms loginUrl="~/Logon/Index"></forms>
</authentication>
<authorization>
<deny users="?" />
</authorization>
In global.asax I have
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string roles = string.Empty;
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles.Split(';'));
ISecurityUserIdentity objUser = null;
objUser = SecurityLibrary.Security.GetUser(username, Mgr.GetSecurityAttribute());
Context.User = objUser;
My issue is why my applicationhost.config file rewrites automatically when I do a signout and change my authentication mode.

Programmatically check if page requires authentication based on web.config settings

I would like to know if there is a way to check if a page requies authentication based on the web.config settings. Basically if there is a node like this
<location path="account">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
then I would like to check on any page if it requires authentication or not and to return true if it is under the account directory. Is this possible?
The solution is to create an anonymous identity (principal), and pass it into the CheckUrlAccessForPrincipal method. It will determine if the page is public, or requires authentication.
See code below:
var principal = new GenericPrincipal(new GenericIdentity(String.Empty, String.Empty), new string[]{});
bool requiredAuthentication = UrlAuthorizationModule.CheckUrlAccessForPrincipal(Page.AppRelativeVirtualPath, principal, Request.HttpMethod);
Are you checking the page that the user has requested? Its unlikely as the request will never get to the page. Check the url authorization workflow.
http://www.asp.net/web-forms/tutorials/security/membership/user-based-authorization-cs
I am a little confused as to what you are asking exactly, but to use your web.config to enforce authentication on a page-for-page basis, you need something like this:
<location path="Forms/Administration/Default.aspx">
<system.web>
<authorization>
<allow roles="Administrator, User, AdditionalUser" />
</authorization>
</system.web>
</location>
If you need to be more granular than that, you need to add the logic to your middle-tier and then check on page load or url request (if MVC).

simple web.config file question asp.net

i am using windows authentication with my asp.net application
different users will have different access to parts of the website.
i would like to do something like this in the config file:
<appSettings>
<role1>
<user>agordon</user><user>jsmith</user>
</role1>
<role2><user>dtodd</user><user>kveel</user></role2>
</appSettings>
is this possible to do?
when authenticating i would then get the username like this:
string username = HttpContext.Current.User.Identity.Name.ToString();
and check if that user exists in the specific role
Use the <authorization> element:
<configuration>
<system.web>
<authorization>
<allow users="*" />
<deny users="?"/>
</authorization>
</system.web>
</configuration>
You can then modify that for particular parts of your site:
<location path="Pages/Administration">
<system.web>
<authorization>
<deny roles="*"/>
<allow roles="Admin" />
</authorization>
</system.web>
</location>
You can do this, but it's really not the best way.
The problem here is that appSettings are not controlled by the Web.Config schema, so you'll need to programatically enumerate appSettings in a horrible fashion:
if (configurationSettings.HasKey("Role1")) { ... }
else if (configurationSettings.HasKey("Role2")) { ... }
else if (configurationSettings.HasKey("Role3")) { ... }
//continue ad.nauseum; it's not fun - trust me!
I know it's not what you're asking, but If you're using normal ASP.Net webforms then it's a little it of a slog; in each page/control you need to find out the current user and then determine if that user has access and then redirect or continue.
If you use ASP.Net MVC, it's a lot cleaner as you do this with attributes.
Authorize(Roles = "Managers")]
public ActionResult CompanySecrets()
{
return View();
}
What the code there is doing, is saying If the user doesn't have the Managers role, don't give them access.
To provide an opposite example, here's a similar method using Web form (msdn example):
http://support.microsoft.com/kb/311495

Problem with ASP.NET Authentication

I'm having problem with our login procedure.
Some customers complain that they can't login. I can see in our logs that their login is successful and that they are redirected from the login page to the member area. But there somehow the login isn't detected and they are bounced back to the login page.
I've asked customers to check if cookies are supported (http://www.html-kit.com/tools/cookietester/) but problem remains even if this test returns true.
This is how I've implemented the login procedure (simplyfied):
protected void Login(string email, string password)
{
FormsAuthentication.SignOut();
Guid clientId = /* Validate login by checking email and password, if fails display error otherwise get client id */
FormsAuthentication.SetAuthCookie(clientId.ToString(), true);
HttpContext.Current.Response.Redirect("~/Members.aspx");
}
On the member page I check for authentication by in Page_Load function:
public static void IsAuthenticated()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.Response.Redirect("~/Login.aspx", true);
}
}
Maybe I'm using FormsAuthentication completely wrong?
I've asked this before but still haven't been able to figure this out, I'd appreciate any help.
From my Web.Config:
<system.web>
<compilation debug="false">
<assemblies>
...
</assemblies>
</compilation>
<authentication mode="Forms"/>
<sessionState mode="InProc" cookieless="false" timeout="180"/>
<customErrors mode="On"/>
<httpHandlers>
...
</httpHandlers>
<httpModules>
...
</httpModules> </system.web>
public static void IsAuthenticated()
{
if (!HttpContext.Current.User.Identity.IsAuthenticated)
{
HttpContext.Current.Response.Redirect("~/Login.aspx", true);
}
}
is not necessary when you use forms authentication.
When you specify the forms authentication in the web.config (in which you also specify the login page)
<authentication mode="Forms">
<forms loginUrl="/Authorization/Login" timeout="60" />
</authentication>
and you deny all non-athenticated users access
<authorization>
<deny users="?" />
</authorization>
you don't have to check the authentication of a user yourself, the framework takes care of that.
I would place the FormsAuthentication.SignOut(); code behind a 'logout' link
Seperate the call of SignOut() and SetAuthCookie() in different methods. You may call FormsAuthentication.SignOut(); when the Login page loads first time - simply just do away from calling SignOut() on Login page. And Call
FormsAuthentication.SetAuthCookie(clientId.ToString(), true); after authentication is successful.
Normally you would use FormsAuthentication.Authenticate together with some membership provider, but this should work, and it actually does in my machine.
Are you removing the FormsAuthentication from your registered HTTP modules? Normally, this is in the machine wide web.config:
<configuration>
<system.web>
<httpModules>
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</httpModules>
</system.web>
</configuration>
If you put a <clear /> inside that same section of your own web.config, you're effectively removing that module.
My tested Web.config is pretty clean, it only has <authentication mode="Forms"/> configured.

Categories

Resources