Implement windows and forms authentication in asp.net mvc 4 - c#-4.0

I am working on asp.net mvc 4 application. Currently the application is forms authentication enabled. But now i want to implement windows authentication in same application. The scenario is- When application will run, it will by default check for window authentication and once that is authenticated, depending upon the role of user, I need to enable forms authentication.
Following is the setting in web.config-
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<authentication mode="Windows">
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
and following is the code in Login Controller-
[AllowAnonymous]
[HttpPost]
public JsonResult JsonLogin(User model, string returnUrl)
{
var user = HttpContext.User.Identity.Name;
if (ValidateUser(model))
{
FormsAuthentication.SetAuthCookie(model.LoginUserID, false);
return Json(new { success = true, redirect = returnUrl });
}
return Json(new { errors = GetErrorsFromModelState() });
}
but i am getting User.Identity.Name = ""; What am I missing? I want to run application on local system itself. Please tell me how to implement this scenario. Any help is appreciated! Thanks in advance!

Related

ServiceStack OrmLite with multiple APIs (private and public)

We have a .net Core 3.1 MVC web application running with ServiceStack Ormlite 5.12. Currently we have a 'public' Open API for users who wish to access data programmatically. We use the following in our AppHost:
public class AppHost : AppHostBase
{
public AppHost(IServiceProvider services, IWebHostEnvironment env)
: base("My API", typeof(MyAPIService).Assembly)
{
_appServices = services;
_env = env;
}
public override void Configure(Container container)
{
SetConfig(new HostConfig
{
...
HandlerFactoryPath = "/myapipath"
});
Plugins.Add(new OpenApiFeature
{
...
});
}
}
And in our Web.config:
<configuration>
<location path="myapipath">
<system.web>
<httpHandlers>
<add path="servicestack*" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" />
</httpHandlers>
</system.web>
<!-- Required for IIS7 -->
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add path="servicestack*" name="ServiceStack.Factory" type="ServiceStack.WebHost.Endpoints.ServiceStackHttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
</handlers>
</system.webServer>
</location>
</configuration>
We have MyApp.ServiceModel and MyApp.ServiceInterface projects that are accessed from the https://{baseurl}/myapipath endpoint. This all works well so far.
We wish to keep the existing OpenAPI unchanged so that users don't need to change anything when updating to a new version. But we also want to add another API for use with an angular application, either by adding a separate endpoint for a 2nd API, or by filtering out what is visible in swagger with our existing API. Is it possible to add a 2nd API plugin with a different path that is separate from the existing API?
There can be only one ServiceStack Open API Plugin registered which lists all publicly accessible APIs within an AppHost.
If you want to visually differentiate APIs you can Group related APIs with Tags:
[Tag("angular")]
public class MyRequest { ... }
Alternatively you can choose to Exclude Services from Metadata Pages with:
[ExcludeMetadata]
public class MyRequestDto { ... }

.NET Core MVC 5 Windows Authentication

I want to use Windows Authentication on my .NET Core MVC 5 web app. To allow specific domain users and an AD group.
I added a web.config in the root:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.web>
<authentication mode="Windows" />
<authorization>
<allow users="mydomain\username1, mydomain\username2" />
<deny users="?" />
</authorization>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
</configuration>
I added this to startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddAuthentication(IISDefaults.AuthenticationScheme);
}
I added this in my controller
[Authorize(Roles = #"mydomain\ADgroupName")]
[Authorize(Users = #"mydomain\username1")]
public class HomeController : Controller
In project properties I disabled Anonymous auth and enabled Windows auth.
I added a project reference to Microsoft.AspNetCore.Authentication.
When all that is said and done I get the error "Type or namespace 'Users' could not be found".
What am I missing here?
the error "Type or namespace 'Users' could not be found".
From the AuthorizeAttribute Class, we can see that the Authorize attribute only have the Roles and Policy property, without the Users property, so it will show the above error.
If you want to set authorization rights for specified users, you could create a policy for the users, then, in the Controller, set the Authorize attribute as below:
[Authorize(Policy = "policyforUser")]
public class HomeController : Controller
More detail information about create policy, see the following links:
Policy-based authorization in ASP.NET Core
ASP.NET Core Authorize AD Groups through web.config
ASP.NET Core - Authorization Using Windows Authentication
Using AD groups to authorise access to pages using IIS Windows Authentication

Authorization doesn't work with Windows Authentication in IIS

I tried to do something in IIS which I though is very simple, but I am unable to make it work.
I created a web page with simple html+js page and web api backend. (It means I have one single plain old html page with one single JavaScript file and it uses AJAX call back to the same server to get data from backend. The backend is written in C# with .NET Framework 4.7 and current version of ASP.NET. It is not MVC, it is not .NET Core, it is not ASP.NET Core.)
Now I want to allow this web page only for some users on local network and I expect this can be somehow configured in web.config file. The IIS is running on a computer in a domain, so I set up the web application in its web.config to use Windows authentication and provided the list of allowed users in authorization section (the user accounts are in the same domain as the web server). I though this would prevent other users to access the web, but apparently all authenticated users can display it. So it seems that Windows authentication works correctly, but there is no authorization check performed and all users are allowed. Can this be done easily in web.config in this kind of html+js+webapi scenario?
Currently, the related section in web.config looks like this:
<system.web>
<compilation targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<authentication mode="Windows" />
<authorization>
<deny users="?" />
<allow users="alloweduser1,alloweduser2" />
</authorization>
</system.web>
Try :
<system.web>
<compilation targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<authorization>
<allow users="domain\alloweduser1,domain\alloweduser2" />
<deny users="*" />
</authorization>
</system.web>

Enabling CORS for Web API in Azure Web Apps

I have deployed a Web API project to Azure Web app. And from a angularjs app I am trying a $http.get request to the API. but it gives a CORS(cross-origin) exception though I have enabled it in my Web API startup config
app.UseCors(CorsOptions.AllowAll);
I want to Enable CORS for Azure Web App, that would solve the problem I believe
EDIT
http://nearestbuyweb.azurewebsites.net/ this is the URL of the Web app. It is trying to access http://nearestbuyapi.azurewebsites.net/api/MenuBar where the exception occurs.
I think it is not possible with Azure Web App. MSDN Question
Please help!
Note: You use CORS settings to let other websites access your site's API. Not to access other site's APIs.
Based on your comments it sounds like you're getting the CORS error when you try to make external requests from your site. That's exactly the behavior CORS is supposed to block.
For the errors to go away you would have to apply the CORS config settings on the site who's API you're trying to access.
In your case you want to make sure you're applying the config changes on the http://nearestbuyapi.azurewebsites.net site. NOT on http://nearestbuyweb.azurewebsites.net/
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
</system.webServer>
I have CORS in Azure working using this:
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "PublicApi",
routeTemplate: "api/v1/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Web.config:
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers></system.webServer>
You need to remove the options handler in IIS using web.config.
http://eugeneagafonov.com/post/38312919044/iis-options-cors-aspnet-webapi-en
Sorry Guys,
The issue happens only at my corporate network. Having googled I found that corporate network can be disable CORS requests . Found this here link

I can retrieve all user names from active directory group on local server but on IIS showing exceptional error

I am new user for stachoverflow, I am developing one web application for intranet in which it authenticate user from active directory which works fine on IIS but I am getting problem to retrieve data(all user names) from group of active directory which works fine on local server.
on IIS it gives exceptiona error- System.DirectoryServices.DirectoryServicesCOMException: Logon failure: unknown user name or bad password.
in IIS windows authentication enabled and other are disabled
My code is:
Web.config file:
<authentication mode="Windows">
<forms loginUrl="~/TTracker/Login.aspx" timeout="600"></forms>
</authentication>
<authorization>
<deny users="?"/>
<allow users="*" />
</authorization>
<identity impersonate="true" />
Code for retrieving data:
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using (HostingEnvironment.Impersonate())
{
DropDownList1.Items.Add(new ListItem("-Select-", ""));
string grpname = "Group1";
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "domain");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, grpname);
if (grp != null)
{
foreach (Principal p in grp.GetMembers(false))
{
DropDownList1.Items.Add(p.SamAccountName + "-" + p.DisplayName);
}
grp.Dispose();
ctx.Dispose();
Console.ReadLine();
}
else
{
Console.WriteLine("We did not find that group.");
Console.ReadLine();
}
}
this is my code for retrieving data from active directory which works fine locally but not works on IIS.
It will be great help if any one solve this issue.
Thanks in advance.
It's related to Impersonation.
Please check the following,
We can impersonate an account to process with AD.
ASP.NET Impersonation
http://msdn.microsoft.com/en-us/library/aa292118(VS.71).aspx
And read this document.
Howto: (Almost) Everything In Active Directory via C#
http://www.codeproject.com/KB/system/everythingInAD.aspx

Resources