MVC Windows Authentication with AD - I still have to log in - asp.net-mvc

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?

Related

MVC application to restrict one ad group

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

Sharing authentication cookie between DNN Site and ASP.NET Site

I have a DNN site on example.com and an MVC site on subdomain.example.com. I've set up MembershipProvider and a RoleProvider in according to this article: SharePoint-Forms-Based-Authentication-Using-DotNet. Now I want to share auth cookie between two sites. I've set up domain keys in both web.config files like domain=".example.com". Fiddler says the same cookie is used when requesting to any of the sites. And there's a following effect: When I log in to one of the sites, I'm being logged off from another. What could I missed?
Below is a part of the web.config of the MVC site:
<machineKey
validationKey="DEE8F9D31F46D663FA0BCF9A6A9701B0796777C5"
decryptionKey="E75FBCF55F6BB0B2A352036B965725FD739B2EB21B790659"
decryption="3DES"
validation="SHA1" />
<authentication mode="Forms">
<forms
name=".DOTNETNUKE"
protection="All"
timeout="60"
cookieless="UseCookies"
loginUrl="~/Account/Login"
domain=".example.com"
path="/" />
</authentication>
<httpCookies httpOnlyCookies="true" requireSSL="false" domain=".example.com" />
<!-- Configure the Sql Membership Provider -->
<membership defaultProvider="SqlMembershipProvider" userIsOnlineTimeWindow="15">
<providers>
<clear />
<add
name="SqlMembershipProvider"
type="System.Web.Security.SqlMembershipProvider"
connectionStringName="DnnSqlServer"
enablePasswordRetrieval="false"
enablePasswordReset="true"
requiresQuestionAndAnswer="false"
minRequiredPasswordLength="7"
minRequiredNonalphanumericCharacters="0"
requiresUniqueEmail="false"
passwordFormat="Hashed"
applicationName="DotNetNuke" />
</providers>
</membership>
<!-- Configure the Sql Role Provider -->
<roleManager enabled="true" defaultProvider="SqlRoleProvider">
<providers>
<clear/>
<add
name="SqlRoleProvider"
connectionStringName="DnnSqlServer"
applicationName="DotNetNuke"
type="System.Web.Security.SqlRoleProvider,System.Web,
Version=2.0.0.0,Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" />
</providers>
</roleManager>
When you see this behavior it is typically from the encryption MachineKey values being different between the different applications. When the other application attempts to read the cookie, it cannot decrypt it and then deletes it, allowing you to login.
I would validate those items in the web.config. (They are not too far down from the node.

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.

Restrict access to ELMAH using custom RoleProvider

in my mvc-project i have set up ELMAH for the exception-handling. ELMAH comes with a frontend which can be accessed by "/elmah.axd".
In the web.config this is configured like this:
<location path="elmah.axd">
<system.web>
<httpHandlers>
<add verb="POST,GET,HEAD"
path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah" />
</httpHandlers>
<authorization>
<allow roles="ADMIN" /> <!-- instead i want to use 'permission' from my custom RoleProvider -->
<deny users="*"/>
</authorization>
</system.web>
<system.webServer>
<handlers>
<add name="ELMAH"
verb="POST,GET,HEAD"
path="elmah.axd"
type="Elmah.ErrorLogPageFactory, Elmah"
preCondition="integratedMode" />
</handlers>
</system.webServer>
</location>
If i would use the standard RoleProvider i would use the authorization as specified in the example above. But as i have a custom RoleProvider i can't / dont know how to do this.
For my Views i have implemented a custom Authentication-Attribute which is very similar to the [Authorize] Attribute (but takes Permissions instead...). Now i want to specify the accessibility for "elmah.axd" (which is no physical file) using my custom RoleProvider.
Does anyone have a clue how i could archieve my goal?
here seems to be a viable approach...

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