MVC application to restrict one ad group - asp.net-mvc

I want to restrict the application to be accessed by one particular AD Group only. So I have
implemented authorize attribute on the controllers and web.config as below. But the application is now not accessible to everyone
including the AD group. Could anyone please help.
[Authorize(Roles = #"Domain\ADGroup")]
public class HomeController : Controller
<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>
I have also tried the response given in the post Authorization using active directory role provider MVC4 as below but that doesn't seem to have resolved. I am still getting the 401 unauthorised error
[Authorize(Roles = "Domain\\ADGroup")]
public class HomeController : Controller

Related

Users don't load Sitefinity

I'm having an issue with SitefinityMembershipProvider in Sitefinity 9.1
When I login to the backend, navigate to Administration -> Users:Page keeps loading.
When I checked the error log it tells me that "Provider must implement the class 'System.Web.Security.MembershipProvider".
But my class inherits sitefinity membership provider i.e. MembershipDataProvider
which is of type Telerik.Sitefinity.Security.Data.
My web config have the following membership defined.
<membership defaultProvider="Default">
<providers>
<clear />
<add name="Default" type="Telerik.Sitefinity.Security.Data.SitefinityMembershipProvider, Telerik.Sitefinity" />
<add name="CredentialServiceProvider" type="SitefinityWebApp.Providers.CredentialServiceProvider" />
</providers>
You need to register the provider in the Security settings as explained here:
http://docs.sitefinity.com/custom-membership-provider-add-the-new-provider-to-the-sitefinity-providers-collection
Additionally, I had to remove the custom provider from the web.config
<providers>
<clear />
<add name="Default" type="Telerik.Sitefinity.Security.Data.SitefinityMembershipProvider, Telerik.Sitefinity" />
</providers>

MVC Windows Authentication with AD - I still have to log in

I have decorated my controller as follows
[Authorize(Roles = #"domain\System_Admin, domain\Survey_Admin, domain\Read_Only")]
public class ContractController : BaseController
{
I am in the process of converting a Forms Authenticated application to Windows Authentication. However I find that to access the methods in this controller, I have to login via a popup screen, defeating the purpose of using Windows Authentication.
In my web.config I have:
<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>
What more do I need to do so that the user is automatically logged in with the correct user roles?

ASP.Net MVC app logout not completely logging out

This app is running in an environment where some users are still using IE7 if that makes any difference. What we're seeing is occasionally after someone logs out and someone else logs in they still get residue from the previous person where it may show that persons profile. Any suggestions would be greatly appreciated.
I'm using the following as the logout method in my asp.net mvc app
public ActionResult LogOff()
{
System.Web.HttpContext.Current.Response.Cookies.Clear();
FormsService.SignOut();
Session["User"] = null;
Session.Clear();
Session.Abandon();
Session.RemoveAll();
return Redirect("/");
}
The app is using sessions saved into the database because it's running on two different web servers.
Here's some settings from the web.config
<sessionState sqlConnectionString="LiveDB" />
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="LiveDB" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="50" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="LiveDB" applicationName="/" />
</providers>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="LiveDB" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
If you use FormAuthentication to login like this -
FormsAuthentication.SetAuthCookie("username", false);
then Logout is supposed to be
FormsAuthentication.SignOut();
If you still have issue, you can force cookie to expire like this.
Membership and Session providers works separetly. Two members may use one session. That is not a rule, but it can be.
I'm not sure but I have a suggetion about your problem. Session has property IsNewSession. Microsofts says, that it "Gets a value indicating whether the session was created with the current request."
So, you may try to check if the Session of login user is new, because as he may share session with old user, and, may be, this is a reason, why one sees others profile.

using windows authentication with active directory groups as roles

I've read several questions on this topic,
such as here, here, here and here;
but none have provided a working solution in my case.
What I want to do:
Implement Windows authentication for a web app that is only used by our own employees. This way they should not need to log into the app, but already be authenticated by way of having logged into windows.
Also, I need to restrict certain areas of the app, based on Active Directory Security Groups that the user may be assigned to.
So I want to be able to decorate Controllers / Actions with
[Authorize(Roles="SomeRole")]
What I've tried:
I have
<authentication mode="Windows" />
in my web.config. And I have added several permutations of a <roleManager> as found in some of the posts linked to above. Currently I have this role manager
<roleManager defaultProvider="WindowsProvider"
enabled="true"
cacheRolesInCookie="false">
<providers>
<add
name="WindowsProvider"
type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
as found in this post.
As it is, if I decorate a controller with [Authorize], I can access it fine.
However:
I can see in my user settings on the network, that I am part of a AD security group called "IT". But if I decorate the same controller with [Authorize(Roles="IT")] I get the blank screen that is is served by the asp.net development server for a 401 not authorized. This is unexpected. I would think that I should be able to view the page as I am logged in to windows and am part of the group "IT".
Most everything I am finding on this topic make it sound very simple to accomplish what I'm trying to do, but I am clearly missing something here.
For dev I am using IISExpress
with development server properties of the MVC project set up so that
Anonymous Authentication is Disabled and Windows Authentication is Enabled.
The web config is deployed using our TFS build server to test and release servers for which authentication is also setup as above and works in those locations as well.
In my web.config I have.
<system.web>
....
<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>
....
</system.web>
I can use
[Authorize(Roles = #"DOMAIN\ADGroup")]
Public ActionResult Index()
{...}
or
public ActionResult Index()
{
var User = System.Web.HttpContext.Current.User;
if (User.IsInRole("DOMAIN\\ADGroup"))
{
return RedirectToAction("IRSAdmin");
}
return View();
}
After i remember to logoff and log back in so the permission i was given to the AD group were applied.

Exclude specific path from WIF authorization in a ASP.NET MVC 4 project

We have successfully configured windows identity foundation (WIF) in our ASP.NET 4.5 MVC 4 project with the help of the Identity and Access... extension for Visual Studio 2012. But are unable to exclude a specific path from authorization to allow anonymous access.
When we access our default route (i.e. /Home), the passive redirection will redirect us to the configured issuer Uri. This is currect. But now assume we want to exclude Path /Guest from STS Authentication so that everybody can access http://ourhost/Guest without beeing routed to the STS issuer. Only static documents are located there.
Snippets from Web.config:
<system.identityModel>
<identityConfiguration>
<audienceUris>
<add value="http://ourhost/" />
</audienceUris>
<issuerNameRegistry type="System.IdentityModel.Tokens.ConfigurationBasedIssuerNameRegistry, System.IdentityModel, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<trustedIssuers>
<add thumbprint="9B74****40D0" name="OurSTS" />
</trustedIssuers>
</issuerNameRegistry>
<certificateValidation certificateValidationMode="None" />
</identityConfiguration>
</system.identityModel>
<system.identityModel.services>
<federationConfiguration>
<cookieHandler requireSsl="false" />
<wsFederation passiveRedirectEnabled="true" issuer="http://oursts/Issue" realm="http://ourhost/" reply="http://ourhost/" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
Further we have...
<system.webServer>
<!-- ... -->
<modules runAllManagedModulesForAllRequests="true">
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
and finally:
<system.web>
<!-- ... -->
<authentication mode="None" />
</system.web>
We tried the following without success:
<location path="~/Guest"> <!-- also "/Guest" is not working -->
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
We also tried to put a small Web.config file into this folder, without success. No matter which Uri we locate to in the browser, we're always redirected.
What is the proper way to accomplish this?
EDIT
Removed the previous "accepted answered", set "accepted answer" to Eugenios answer as this is the more useful reply.
In an MVC app you typically define access through the [Authorize] attribute in controllers and actions.
Just remove from web.config:
<system.web>
<authorization>
<deny users="?" />
</authorization>
Note: this is usually added automatically by the "Add STS Reference" wizard in VS2010
It seems that the behaviour is exactly the same on VS2012 and the new tools. I just created a brand new MVC4 app. Ran the "Identity and Access..." tool with a local config STS (left all defaults).
It did add this fragment to the web.config:
<authorization>
<deny users="?" />
</authorization>
I removed it and added [Authorize] to the About controller action:
[Authorize]
public ActionResult About()
{
ViewBag.Message = "Your app description page.";
return View();
}
When I click on the "About" link, then I get redirected to the STS. Everything else works with anonymous access.
Note:
You have some control on this too in the wizard (see the "Configuration" page of the wizard).
I can not get [Authorize] to work - it is not doing the redirect to my STS, and I am sure it is something I am missing. I did discover how to solve for the original ask, though.
In global.asax:
protected void Application_Start()
{
... config stuff ...
FederatedAuthentication.WSFederationAuthenticationModule.AuthorizationFailed += WSFederationAuthenticationModule_AuthorizationFailed;
}
and then:
void WSFederationAuthenticationModule_AuthorizationFailed(object sender, AuthorizationFailedEventArgs e)
{
// Do path/file detection here
if (Request.Path.Contains("/Content/") || Request.Path.Contains("/Scripts/"))
{
e.RedirectToIdentityProvider = false;
}
}
I was in the same situation as Thomas. In my case, I was testing/using IISExpress locally.
Eugenio's answer almost got me working, with one added requirement. I had to set the "Anonymous Authentication" in my MVC Project Property to "Enabled."
This was either disabled by default or possibly set that way when using the VS 2012 "Identity and Access..." tooling.
So, to recap, there was no code or special attributes to write/maintain.
My csproj file contains:
<IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
My web.config contains:
<system.web>
<authentication mode="None" />
</system.web>
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<add name="WSFederationAuthenticationModule" type="System.IdentityModel.Services.WSFederationAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
<add name="SessionAuthenticationModule" type="System.IdentityModel.Services.SessionAuthenticationModule, System.IdentityModel.Services, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" preCondition="managedHandler" />
</modules>
</system.webServer>
<system.identityModel.services>
<federationConfiguration>
<wsFederation passiveRedirectEnabled="true" issuer="https://REMOVED.accesscontrol.windows.net/v2/wsfederation" realm="urn:REMOVED" requireHttps="false" />
</federationConfiguration>
</system.identityModel.services>
And, I add the standard [Authorize] attribute to controller actions that I want to be defended by WIF:
[Authorize]
public ActionResult About()
{
....
}
What finally pointed me into the right direction was an older blog post which explains how to protect a specific controller or area of the page. In combination with global filters I'm almost there.
It seems like the key is not to use the passiveRedirectEnabled="true" option but set it to false. Only then you have the full control over the authentication process, but would need to trigger the passive redirection yourself then, using the SignInRequestMessage class (which is not a big deal).
Better solutions with less code required are welcome.
EDIT
Removed "accepted answered" state for this, set "accepted answer" to Eugenios anwer as this is the more useful reply.
I solved this in the web.config, the firts line Allow all unauthorized users and the second line disabled redirection
<wsFederation passiveRedirectEnabled="false" issuer="xxx" realm="xxx"/>
<authentication mode="Windows" />
<authorization>
<allow users="*" />
</authorization>

Resources