AD Users Works but AD roles or groups don't - c#

I installed and enabled Windows authentication in IIS and in the web.config file of my project and added the [Authorize(Users = "MYDOMAIN\MyAccount") attribute to the controller, just above the Index method so that I could begin testing to be sure no one but those specified could access an IT intranet app I was working on. This worked fine after adding the following to the Web.config:
<system.web>
<compilation debug="true" targetFramework="4.7.1" />
<httpRuntime targetFramework="4.6.1" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
<authentication mode="Windows" />
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
</system.web>
If I either remove the Users = part of the attribute and change it to Roles = "DOMAIN\\Group", or if I just add that after a comma, it stops working altogether:
[Authorize(Roles = "DOMAIN\\GROUP")]
or
[Authorize(Roles = "DOMAIN\\GROUP", Users = "DOMAIN\Username")]
I'm a member of the AD group I'm specifying yet neither of these work. It only works for the Users alone and at no other time. I'll be prompted for a password otherwise.
I even got it to display the current user I'm logged into Windows as and that's still working fine if I remove the attribute. Yet if I add the attribute back (with the Roles section included) I get a prompt to login despite being logged in as the user specified in the tag.
Here's part of the controller:
public class HomeController : Controller
{
[Authorize(Users = #"MYDOMAIN\MyAccount", Roles = #"MYDOMAIN\All Information Technology")]
public ActionResult Index()
{
return View();
}
Here's my RouteConfig.cs
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Why is this not working? What am I missing?

You are trying to authorize Group instead of Role. Those two things are not one and the same. Unless user will be part of the Role that is authorized to access resource you will always get unauthorized result.
If you want to authorize Group you should inherit and extend AuthorizeAttribute or develop your own authorization attribute implementing IAuthorizationFilter.

Turns out that for whatever reason, the laptop I was testing on, despite being logged into the domain as an account that was a member of the group in the annotation, was being picked up as my separate domain admin account. So when I added Domain Admins to the authorize list of roles it started working. I've got a whole new problem now, why my app picks up a different account than the one I'm logged in as, but apparently I was doing everything right. See question as a reference.

Related

Restrict access to the Logs folder

I have an ASP.NET MVC Application, which has a Logs folder, where the log files are stored. Normally, I would access it as localhost/Logs/Log.common.txt and see the logs. However, now I want to restrict it.
Now I have Logs controller, which has an Authorize attribute set to the Admin only:
namespace MyApp.Controllers
{
[Authorize(Roles = "Admin")]
public class LogsController : BaseController
{
public ActionResult Index()
{
LogFile logFile = GetLogFileByName("log.Common.txt");
return View(logFile);
}
}
}
So now, if I try to go to localhost/Logs, then I get an unauthorized access error, however, if I go directly to localhost/Logs/Log.common.txt I still can see the file. Is there any way to disable this?
For IIS7+ add following web.config file into /Logs
<configuration>
<system.webServer>
<security>
<authorization>
<remove users="*" roles="" verbs="" />
<add accessType="Allow" users="" roles="Admin" />
</authorization>
</security>
</system.webServer>
</configuration>
Earlier versions have slightly different syntax.
Alternatively, move /logs into /app_data

How to authorize users and AD groups for my application

Using Visual Studio 2015 Community, EF 6, ASP.NET MVC 5, Oracle, and using a database-first approach.
I'm trying to setup my application so that an AD and a list of users are the only ones who can access it. The list of users will not be in this AD group. This is for an internal application. In my web.config file I have the following
<authentication mode="Windows" />
<authorization>
<deny users="?" />
</authorization>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider">
<providers>
<clear />
<add name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" applicationName="/" />
</providers>
</roleManager>
Above each of my controllers I have the following:
[Authorize(Roles = #"domain\AD_Group, domain\user1,domain\user2,domain\user3")]
public class HomeController : Controller
I've tried different ways of handling this with:
[Authorize(Roles = #"domain\AD_Group" Users = #"domain\user1,domain\user2,domain\user3")]
And
[Authorize(Roles = #"domain\AD_Group")]
[Authorize(Users = #"domain\user1,domain\user2,domain\user3")]
But nothing seems to work. Either everyone loses access or only the AD has access. What am I doing wrong? Should I handle this in the web.config file rather than my current method? What would that look like? Thanks.

User.Identity.Name is blank

I have done a bunch of research about this, but can't find a solution to this problem.
my web.config :
<system.web>
<compilation debug="true" targetFramework="4.5.1"/>
<httpRuntime targetFramework="4.5.2"/>
<authentication mode="Windows"/>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
and for some reason
string User = User.Identity.Name;
is always blank.
IIS Windows authentication is the only option that is enabled.
i have tried the
[Authorize]
same result.
I checked the IIS config file to make sure
<windowsAuthentication enabled="true">
is set to true.
Are you working within an authorized context? In other words, unless you actually say you want a particular controller or action authorized, nothing is filled even if the user has previously logged in. For example:
public ActionResult Foo()
{
var user = User.Identity.Name; // null
}
But
[Authorize]
public ActionResult Foo()
{
var user = User.Identity.Name; // WIN
}
If you need the action to still allow anonymous access, just add [AllowAnonymous] as well:
[Authorize]
[AllowAnonymous]
public ActionResult Foo()
{
...

Integrating SimpleMembershipProvider in ASP.NET MVC Application

I'm having a hard time implementing (or integrating) ASP.NET SimpleMembershipProvider. I already have the database tables from a previous version of the application and I don't want to create new user tables, roles, etc... I want to use the existing tables (already mapped with entity framework) so the users in the database can log in to the future application. Here's what I did:
Web.config
<authentication mode="Forms">
<forms loginUrl="~/Auth" timeout="2880" />
</authentication>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<roleManager enabled="true" />
Global.asax
WebSecurity.InitializeDatabaseConnection("MyConnectionString", "tblCreds", "IdCred", "Login", false);
// I put false in the end because I don't want it to create new tables
Controller:
[HttpPost]
public ActionResult Index(UserCreds creds)
{
if (ModelState.IsValid)
{
UserBLL bll = new UserBLL();
BaseUser authUser = bll.Authenticate(creds.Login, creds.Password);
if (authUser != null)
{
WebSecurity.Login(creds.Login, creds.Password);
return RedirectToAction("Index", "Home");
}
}
ViewBag.ErrorMessage = "Error";
return View();
}
And I'm getting this exception:
System.Data.SqlClient.SqlException: Invalid object name 'webpages_Membership'
Thanks you for your help :)
You are seeing that exception as SimpleMembershipProvider internally uses these table names. Unfortunately they are not overridable (until last i used it).
The design goal with SMP was to provide an out of the box working model of membership with its own table schema. You can configure user table name and add more column but not everything.
See this question for more information.

Simplest home page with ASP.NET and AnjularJS

I want to build a SPA with AngularJS and ASP.NET Web API.
In regards to the frontend webpage I would like to limit the implication of asp.net as much as possible and move all the logic into Angular, the only thing the Web API will supply is a REST service.
I have created an index.html page with some angular that loads a basic list from the server.
But my index.html is accessed using ex. http://localhost:1234/app/index.html , what I would like now is to see my index.html from http://localhost:1234/ and also get a custom error page if I access some random link from this host.
Do I require ASP.NET to do this ? I would like to limit the use of ASP.NET as much as possible, only the basic required stuff.
And I am complete new to this.
Web.config :
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.webServer>
<handlers>
<clear />
<add
name="StaticFile"
path="*" verb="*"
modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule"
resourceType="Either"
requireAccess="Read" />
</handlers>
<staticContent>
<mimeMap fileExtension=".*" mimeType="application/octet-stream" />
</staticContent>
<defaultDocument enabled="true">
<files>
<clear/>
<add value="index.html"/>
</files>
</defaultDocument>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
Also added routing:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Page error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /
Well angular only does routing on client side, for your url needs you will still need to do some config on server side.
this should do the trick:
add this to web.config:
<system.webServer>
<defaultDocument>
<files>
<clear/>
<add value="(location of index.html)"/>
</files>
</defaultDocument>
As for errors (404 is among them), answer can be found here. That is only for when someone tries to get an url that does not exist, before angular has been loaded.
But once angular is loaded up, you do everything withing config, where you configure $routeProvider:
$routeProvider.when('/someUrl', {templateUrl: 'url/templatefile.html', controller: 'templateController'})
.when('/my404route', {templateUrl: 'url/my404file.html', controller: 'my404Controller'})
//when returns $routeprovider so you can chain "whens"
//finnaly add "otherwise"
.otherwise({redirectTo: '/my404route'});
//or just route to root with '/' if you won't handle unknown routes
By default visual studio deploy the site in a subfolder. To change it right click on your web project file / properties. Then in the Web tab specify the project url to be http://localhost:1234.

Categories