RoleManager crashes application asp.net MVC WebApi - c#

my RoleManager keeps failing to connect to the database
my application's roles work fine in my ASP.net MVC webApi application without it, but i can't get the roles of a user without adding RoleManager to the WebConfig
this is a part of the webconfig containing the RoleManager definition
<system.web>
<roleManager enabled="true">
<providers>
<add name="newprovider"
type="System.Web.Security.SqlMembershipProvider"
minRequiredNonalphanumericCharacters="0"
connectionStringName="DefaultConnection"/>
</providers>
</roleManager>
<customErrors defaultRedirect="Error.aspx" mode="On">
<error statusCode="401" redirect="~" />
<error statusCode="403" redirect="Forbidden.aspx" />
</customErrors>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
<httpModules>
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</system.web>
and this is the code I have in my RolesController
[Authorize]
public class RolesController : ApiController
{
// GET: api/Roles
public IEnumerable<string> Get()
{
string[] roleNames = Roles.GetRolesForUser();
return roleNames;
}
}
when i have the RoleManager part in the WebConfig my application doesn't even show the index page, it shows an error:
Runtime Error
Description: An exception occurred while processing your request. Additionally, another exception occurred while executing the custom error page for the first exception. The request has been terminated.
EDIT: now shows error on Line 20: type="System.Web.Security.SqlMembershipProvider"

Related

HOW TO FIX: You do not have permission to view this directory or page?

I have a new legacy code in .NET MVC app.
The first time a run it, prompt the windows authentication alert to log me in. I already disabled it in the web.config.
Then a see authentication code obviously, but i already comment it to jump.
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
//if (!Request.IsAuthenticated) return;
//var userPrincipal = new CompanyPrincipal((WindowsIdentity) HttpContext.Current.User.Identity);
//var userPrincipal = new CompanyPrincipal(WindowsIdentity.GetCurrent());
//if (userPrincipal.IsAuthenticated)
//{
//HttpContext.Current.User = userPrincipal;
WindowsPrincipal fakeUser = new WindowsPrincipal(WindowsIdentity.GetCurrent());
HttpContext.Current.User = fakeUser;
//}
//else
//{
// Response.StatusCode = 401;
// Response.StatusDescription = "Unauthorized";
// Response.SuppressContent = true;
// HttpContext.Current.ApplicationInstance.CompleteRequest();
//}
}
After this something my app displays the error message HTTP Error 401.0 - Unauthorized
HTTP Error 401.0 - Unauthorized - image here
And this is part of my web config
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<remove name="UrlRoutingModule-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
and this part
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<globalization culture="es-MX" uiCulture="es-MX" />
<!--<authentication mode="Windows" />-->
<authentication mode="None"/>
<authorization>
<allow users="*" />
<!--<deny users="*" />-->
</authorization>
</system.web>
What am i missing?? I already give permissons to application folders but i think there is something more there.
Any suggestion?? I have some bindings and end points in the web.config.
Regards!!
Since you are using a windows principal maybe you should change the authentication mode to "Windows".
In my case There is a filter enabled in App_Start => FilterConfig.cs => "filters.Add(new AuthorizeAttribute());"
I just removed above line and now my application is working fine.
Thanks!

Roles not working in ActiveDirectoryMembershipProvider

I have a web-site which uses forms auth and ActiveDirectoryMembershipProvider. I have an Action in controller like this:
[Authorize(Roles = "jira-developers")]
[HttpGet]
public ActionResult MonitorForm()
{
var list = Dal.GetActualData();
return View(list);
}
I'm totally sure that my user is in group with Name="jira-developers", but auth fails. If i remove Roles parameter, the auth will work fine.
What am i doing wrong? I'll be gratefull for any help!
As nobody gave me an answer i'll answer this question myself. ActiveDirectoryMembershipProvider can only handle auth and to enable roles management i had to specify rolesManager. I implemented my own RoleProvider (because i need some specific functionality) and now my Web.Config looks like this:
<system.web>
<authentication mode="Forms">
<forms name=".ADAuthCookie" loginUrl="~/Account/Login" timeout="45" slidingExpiration="false" protection="All" />
</authentication>
<membership defaultProvider="ADMembershipProvider">
<providers>
<clear />
<add name="ADMembershipProvider"
type="System.Web.Security.ActiveDirectoryMembershipProvider"
connectionStringName="ADConnectionString"
attributeMapUsername="sAMAccountName" />
</providers>
</membership>
<roleManager enabled="true" defaultProvider="AdRoleProvider">
<providers>
<clear/>
<add name="AdRoleProvider" type="InternalAutomation.Providers.AdRoleProvider"/>
</providers>
</roleManager>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
Do you have the role defined in your Roles table? (Depending on the version you're using the table could be named slightly different than my screen shot below)
You should have an entry with a 'RoleName' of "jira-developers".
The user hitting the action should also have an entry in the '...UsersInRoles' table.

where do i put overrideMode="Deny" in mt config

I have got this error below
HTTP Error 500.19 - Internal Server Error
The requested page cannot be accessed because the related configuration data for the page is invalid.
Detailed Error Information
Module Authentication
Notification AuthenticateRequest
Handler ExtensionlessUrl
Handler-Integrated-4.0
Error Code 0x80070021
Config Error This configuration section cannot be used at this path.
This happens when the section is locked at a parent level. Locking is either by
default (overrideModeDefault="Deny"), or set explicitly by a location tag with
overrideMode="Deny" or the legacy allowOverride="false".
this is my config file
<configuration>
<connectionStrings>
<add name="DBConnection" connectionString="data source=12.12.16.117;Initial Catalog=web_prof_global; User ID=1111;Password=1111;persist security info=True;packet size=4096" providerName="System.Data.SqlClient" />
<add name="DBConnectionSf" connectionString="data source=12.12.16.117;Initial Catalog=webCommon; User ID=1111;Password=1111;persist security info=True;packet size=4096" providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="false" targetFramework="4.0" />
</system.web>
<system.webServer>
<security>
<authentication>
<basicAuthentication enabled="true" />
</authentication>
</security>
<modules runAllManagedModulesForAllRequests="true" />
<defaultDocument>
<files>
<add value="s-f.aspx" />
</files>
</defaultDocument>
</system.webServer>
</configuration>
can you please help

altering the type field in sqlmembership provider

Let us consider the following web.config file
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">
<connectionStrings>
</connectionStrings>
<system.web>
<pages theme="PetShop" styleSheetTheme="PetShop" controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID">
<controls>
<add tagPrefix="blt" namespace="BLToolkit.Web.UI" assembly="BLToolkit.4" />
</controls>
</pages>
<!--
Set compilation debug="true" to insert debugging
symbols into the compiled page. Because this
affects performance, set this value to true only
during development.
-->
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="System.Data.Linq, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" />
</assemblies>
</compilation>
<!--
The <authentication> section enables configuration
of the security authentication mode used by
ASP.NET to identify an incoming user.
-->
<authentication mode="Forms">
<forms name="PetShopAuth" loginUrl="SignIn.aspx" protection="None" timeout="60" />
</authentication>
<!--
The <customErrors> section enables configuration
of what to do if/when an unhandled error occurs
during the execution of a request. Specifically,
it enables developers to configure html error pages
to be displayed in place of a error stack trace.
-->
<customErrors defaultRedirect="Error.aspx" mode="RemoteOnly" />
<sessionState mode="Off" />
<anonymousIdentification enabled="true" />
<profile automaticSaveEnabled="false" defaultProvider="ShoppingCartProvider">
<providers>
<add name="ShoppingCartProvider" connectionStringName="ProfileDB" type="PetShop.BusinessLogic.ProfileProvider" applicationName=".NET Pet Shop 4.0" />
<add name="WishListProvider" connectionStringName="ProfileDB" type="PetShop.BusinessLogic.ProfileProvider" applicationName=".NET Pet Shop 4.0" />
<add name="AccountInfoProvider" connectionStringName="ProfileDB" type="PetShop.BusinessLogic.ProfileProvider" applicationName=".NET Pet Shop 4.0" />
</providers>
<properties>
<add name="ShoppingCart" type="PetShop.BusinessLogic.Cart" allowAnonymous="true" provider="ShoppingCartProvider" />
<add name="WishList" type="PetShop.BusinessLogic.Cart" allowAnonymous="true" provider="WishListProvider" />
<add name="AccountInfo" type="PetShop.ObjectModel.Address" allowAnonymous="false" provider="AccountInfoProvider" />
</properties>
</profile>
<!-- Membership Provider for SqlServer -->
<membership defaultProvider="SQLMembershipProvider">
<providers>
<add name="SQLMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MembershipDB" applicationName=".NET Pet Shop 4.0" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" passwordFormat="Hashed" />
</providers>
</membership>
<caching>
<sqlCacheDependency enabled="true" pollTime="10000">
<databases>
<add name="MSPetShop4" connectionStringName="SQLConnString1" pollTime="10000" />
</databases>
</sqlCacheDependency>
</caching>
</system.web>
<location path="UserProfile.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
<location path="CheckOut.aspx">
<system.web>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</location>
</configuration>
by reading the above config file i need to change the attribute value of type field in membership providers nodes.
type="System.Web.Security.SqlMembershipProvider"
to new value
type="sample.SqlMembershipProvider"
through c#.net lambda expressions
waiting for your responses
I done the solution as
var xDoc = XDocument.Load(inputPathToConfigFile);
var ns = xDoc.Descendants().First(x => x.Name.LocalName == "configuration").Name.Namespace;
var prop = xDoc.Descendants(ns + "membership")
.First(p => p.Attribute("defaultProvider").Value == "SQLMembershipProvider");
if(prop.HasAttributes)
{
var prop1 = prop.Descendants(ns + "add").First(p => p.Attribute("type").Value == "System.Web.Security.SqlMembershipProvider");
prop1.Attribute("type").Value = "sample.membershipprovider";
xDoc.Save(inputPathToConfigFile);
}
Just for your references...

Microsoft Media Platform + Forms Authentification

Forms Authentication does not work. Auth cookies are not sent to server when SMF attempts to get access to *.ism/Manifest files on a server that requires specific user roles.
What i do:
1. Create new Silverlight Smooth Streaming template with supporting RIA WCF.
2. Configure web.config :
<connectionStrings>
<add name="ApplicationServices" connectionString="Data Source=[SERVER];Initial Catalog=[CATALOG];User ID=[USER];Pwd=[PASSWORD];" providerName="System.Data.SqlClient" />
<system.web>
<authentication mode="Forms">
<forms loginUrl="~/Account/LogOn" timeout="2880" />
</authentication>
<membership>
<providers>
<clear />
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<profile>
<providers>
<clear />
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="Gender" />
<add name="Birthday" />
<add name="AvatarPath" />
</properties>
</profile>
<roleManager enabled="true">
<providers>
<clear />
<add connectionStringName="ApplicationServices" applicationName="/" name="AspNetSqlRoleProvider" type="System.Web.Security.SqlRoleProvider" />
<add applicationName="/" name="AspNetWindowsTokenRoleProvider" type="System.Web.Security.WindowsTokenRoleProvider" />
</providers>
</roleManager>
Add Authentification Service and correct User class (add 3 props).
On client side add this to app.xaml.cs:
public App()
{
//Default things...
InitializeWebContext();
}
private void InitializeWebContext()
{
WebContext webContext = new WebContext();
var fa = new FormsAuthentication();
var ac = new AuthenticationDomainService1();
fa.DomainContext = ac;
fa.Login(new LoginParameters("user", "password"), (y) =>
{
if (!y.HasError)
{
this.RootVisual = new MainPage();
}
}, null);
webContext.Authentication = fa;
ApplicationLifetimeObjects.Add(webContext);
Resources.Add("WebContext", WebContext.Current);
}
Access is restricted by web.config file in target directory:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<authorization>
<allow roles="Role_name" />
<deny users="*" />
</authorization>
</system.web>
</configuration>
User exists in this role.
When I use the default video that's specified in Xaml (Big Bunny) - everything is fine. But when I change mediasource to a path to s restricted zone on my server I get an access error.
On the client side, I get user credentials succesfully.
Fiddler shows next thing:
When I try access to another resctricted methods ([RequiresAuthentication]) on RIA WCF, client send Auth cookies, but when SMFPlayer try access to media source, that cookie wasn`t sent.
What have I missed?
I found some workaround:
If you transfer the stream files into a subdirectory, and restrict access to it (instead of a directory with "ism" files). Manifest will be issued to anonymous users, but the data streams is only for registered (when player try touch data stream it sucessfully attach auth cookies).

Categories

Resources