Custom Role Provider Not Being Used - c#

Alright so I made a custom role provider for my website and no matter what I do I can't get the code in the overridden functions to get hit.
This is the Custom Role Provider
namespace XXX.Security
{
using System;
using System.Linq;
using XXX.Areas.AccountManagement;
using System.Web.Security;
public class AppRoleProvider : RoleProvider
{
public override string ApplicationName
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public override void AddUsersToRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override void CreateRole(string roleName)
{
throw new NotImplementedException();
}
public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
{
throw new NotImplementedException();
}
public override string[] FindUsersInRole(string roleName, string usernameToMatch)
{
throw new NotImplementedException();
}
public override string[] GetAllRoles()
{
AccountManagementDbContext accountManagement = new AccountManagementDbContext("App Role Provider - GetAllRoles()");
string[] roles = accountManagement.getRoles();
return roles;
}
public override string[] GetRolesForUser(string username)
{
AccountManagementDbContext accountManagement = new AccountManagementDbContext("App Role Provider - GetRolesForUser()");
string[] userRoles = accountManagement.getRolesForUser(username);
return userRoles;
}
public override string[] GetUsersInRole(string roleName)
{
throw new NotImplementedException();
}
public override bool IsUserInRole(string username, string roleName)
{
AccountManagementDbContext accountManagement = new AccountManagementDbContext("App Role Provider - GetAllRoles()");
string[] userRoles = accountManagement.getRolesForUser(username);
return userRoles.Contains(roleName);
}
public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
{
throw new NotImplementedException();
}
public override bool RoleExists(string roleName)
{
throw new NotImplementedException();
}
}
}
Here is my web.config file
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<connectionStrings>
<add name="xxx"
providerName="System.Data.SqlClient"
connectionString="Data Source=xxx;
Initial Catalog=xxx;
Integrated Security=false;
User ID=xxx;
Password=xxx;"/>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="EnableSimpleMembership" value="false" />
</appSettings>
<system.web>
<authentication mode="Windows" />
<roleManager defaultProvider="AppRoleProvider" enabled="true">
<providers>
<clear/>
<add name="AppRoleProvider" type="xxx.Security.AppRoleProvider"/>
</providers>
</roleManager>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<remove name="TelemetryCorrelationHttpModule" />
<add name="TelemetryCorrelationHttpModule" type="Microsoft.AspNet.TelemetryCorrelation.TelemetryCorrelationHttpModule, Microsoft.AspNet.TelemetryCorrelation" preCondition="integratedMode,managedHandler" />
<remove name="ApplicationInsightsWebTracking" />
<add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" />
</modules>
<validation validateIntegratedModeConfiguration="false" />
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlCeConnectionFactory, EntityFramework">
<parameters>
<parameter value="System.Data.SqlServerCe.4.0" />
</parameters>
</defaultConnectionFactory>
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SqlServerCe.4.0" type="System.Data.Entity.SqlServerCompact.SqlCeProviderServices, EntityFramework.SqlServerCompact" />
</providers>
</entityFramework>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.8.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SqlServerCe.4.0" />
<add name="Microsoft SQL Server Compact Data Provider 4.0" invariant="System.Data.SqlServerCe.4.0" description=".NET Framework Data Provider for Microsoft SQL Server Compact" type="System.Data.SqlServerCe.SqlCeProviderFactory, System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</DbProviderFactories>
</system.data>
</configuration>
This is a custom Authorization Attribute I am using
namespace XXX.Models
{
using System.Web;
using System.Web.Mvc;
public class AccessDeniedAuthorizationAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
var user = HttpContext.Current.User.Identity.Name;
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.Result = new RedirectResult("/AccessDenied");
}
}
}
}
Finally this is my controller
namespace XXX.Areas.Admin.Controllers
{
using Models;
using System.Web.Mvc;
public class AdminController : Controller
{
[AccessDeniedAuthorization(Roles = "Administrator")]
public ActionResult AdminHome()
{
var user = HttpContext.User.Identity.Name;
return View();
}
}
}
So here are some things I've tried to get this to work...
Tried using the default Authorize attribute on my controller action.
Tried specifying the other attributes in my web.config for the provider like so...
<system.web>
<authentication mode="Windows" />
<roleManager defaultProvider="AppRoleProvider" enabled="true">
<providers>
<clear/>
<add name="AppRoleProvider" type="XXX.Security.AppRoleProvider, XXX" connectionStringName="XXX"/>
</providers>
</roleManager>
<compilation debug="true" targetFramework="4.6.1" />
<httpRuntime targetFramework="4.6.1" />
</system.web>
I've hit all my overridden functions in the Role provider from a controller to make sure they worked and they all worked normally and hit the breakpoints I had in it. When I put a break point in my custom Authorization attribute though it hits when the controller action in the Admin controller gets called. I even looked at the HttpContext.Current.User.ProviderName and it is the name of my custom Role Provider.
Another thing that is weird is that my User.Identity is never filled out when it should be populating with my windows login information, so I would imagine this has to be some sort of problem with the windows authentication not working.
I have the windows authentication turned on in my project properties too. I also left anonymous authentication enabled as I need to use both types of authentication.
Also going to throw this out there. My custom Role provider is in my web project, but the acccountmanagementdbcontext it references is in a separate project, though I can't see that causing any issues.
** Update **
I found something while googling about changing the applicatonhost.config file for IIS express.
<windowsAuthentication enabled="true">
<providers>
<add value="Negotiate" />
<add value="NTLM" />
</providers>
</windowsAuthentication>
I did this, but still doesn't work.
** Update 2 **
It seems that for some reason the user has to enter their windows credentials at least one time for the windows authentication to be able to authenticate them. I tried it with my windows credentials, while running locally, and after I entered my credentials the code in my custom role provider was then hit.
I was under the impression that if windows authentication was turned on and a request was sent to a controller/action that required authentication that it would just pull the windows user's credentials automatically and then pass them to the role provider.
My boss says that if you're on the same network as the IIS server that it will automatically get the windows user's credentials, but I have my doubts, as I tried hosting this on my pc in IIS with a dns address in my host file and it still didn't auto populate my windows credentials into the HttpContext.User.Identity.

You have to be using Internet Explorer for the Windows authentication to happen automatically on start of the site. The HttpContext.User.Identity.Name property will be populated with the current Windows username if you access the site with IE. I was using Firefox at the time. Which is also why I thought it was incorrect that that property was not populated when I hit that controller action. In any browser other than IE you have to turn on Windows authentication and then enter your Windows credentials in the popup login box when trying to access an area of you site that you have restricted. I had that login popup disabled, so in my site when I tried to access a controller action that I had set as restricted it never passed the windows validation, because the Identity.Name would not be populated without entering your windows credentials in that popup login.

Related

ImageResizer not longer working when TinyCache plugin is enabled

I'm trying to get ImageResizer working with the TinyCache plugin. (i'll be on ImageResizer Essential Edition).
I am under Windows 10 / IIS 10.0 with Integrated mode
I have a .net webform 4.7.2 website with the following NuGet packages installed:
ImageResizer (v4.2.5)
ImageResizer.Plugin.TinyCache (v4.2.5)
ImageResizer.WebConfig (v4.2.5)
My web.config is the following:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
https://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<configSections>
<!--<section name="resizer" type="ImageResizer.ResizerSection" requirePermission="false" />-->
<section name="resizer" type="ImageResizer.ResizerSection,ImageResizer" requirePermission="false" />
</configSections>
<!--check URL ~/resizer.debug.ashx-->
<resizer>
<!--Unless you (a) use Integrated mode, or (b) map all requests to ASP.NET,
you'll need to add .ashx to your image URLs: image.jpg.ashx?width=200&height=20
Using IIS7 Integrated mode or the Visual Studio web server? You can skip this step.
You also don't need to do this if you are using the .jpg.ashx syntax.-->
<pipeline fakeExtensions=".ashx" defaultCommands="autorotate.default=true" />
<plugins>
<add name="TinyCache" />
<!--<add name="VirtualFolder" virtualPath="~/" physicalPath="..\Assets" vpp="false "/>-->
<!--<add name="VirtualFolder" virtualPath="~/" physicalPath="../Assets" vpp="false "/>-->
</plugins>
</resizer>
<system.web>
<customErrors defaultRedirect="YourErrorPage.aspx"
mode="RemoteOnly">
</customErrors>
<compilation debug="true" targetFramework="4.7.2" />
<httpRuntime targetFramework="4.7.2" />
<pages>
<namespaces>
<add namespace="System.Web.Optimization" />
</namespaces>
<controls>
<add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" />
</controls>
</pages>
<httpModules>
<!-- This is for IIS7/8 Classic Mode and Cassini-->
<add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
</httpModules>
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=2.0.1.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:default /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules>
<!--This is for IIS7+ Integrated mode-->
<add name="ImageResizingModule" type="ImageResizer.InterceptModule" />
</modules>
</system.webServer>
</configuration>
When I disable the TinyCache plugin (simply comment the <add name="TinyCache" /> line) it works when I try to call an image to resize (e.g. http:///Assets/TestImage.jpg?height=100 ; the image is resized ; here I have an TestImage.jpg picture in the Assets folder in the root directory of my website)
I however I get a warning on the diagnostic page http:///resizer.debug.ashx indicating I should enable cache:
(Warning): NoCache is only for development usage, and cannot scale to production use.
So I enable the TinyCache plugin in web.config.
Then I get a warning on the diagnostic page http:///resizer.debug.ashx which I am unable to get rid off : (Warning): To potentially see additional errors here, perform an image resize request.
If I then try to resize a picture (e.g. http:///Assets/TestImage.jpg?height=100 .... or event (e.g. http:///Assets/TestImage.jpg.ashx?height=100 which I should not need in my case with Win10 - IIS 10 Integrated mode) I get the following error :
Note : the english version of this error (I'm in French) would be
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.
Worth noted, the file /App_Data/tiny_cache.cache is never created ! (I have however granted all privileges on this folder to the user running the IIS Pool.... as well as all users on my DEV box !)
If you have any idea/solution, many thanks in advance !
I'm considering using https://imageprocessor.org/ instead of ImageResizer as didn't come with any pain :)
You need to install the protobuf-net nuget package. Because the dll is missing, a FileNotFound exception is thrown, which in turn is converted to a 404 error.

Add Azure Login to .Net 4.5 Webforms Application

We Currently have a Web Forms ASPX application I am trying to add Azure Authentication as a login option to. I don't currently want to rewrite the application as a MVC application.
I have added a Startup.cs file to the application as well as Microsoft.Owin.Security, Microsoft.Owin.Security.Cookies, Microsoft.Owin.Security.OpenIdConnect. Currently the application uses forms based authentication but I would like to add Azure as a login type and will keep track of what type of login they are using with a variable so the application will know how to login them out. I can't seem to get it to send me to the Microsoft common login page. Does anyone has any idea what I'm doing wrong to get this to work?
If I view the context from the button after it runs the response is a 401 but if I use the same client ID, and use the Microsoft Azure provided Sample it will log me in using the sample application so i know the Application is set up correctly on the Azure Portal.
In my Startup.cs I have:
using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;
using Microsoft.IdentityModel.Protocols.OpenIdConnect;
using Microsoft.IdentityModel.Tokens;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OpenIdConnect;
using Microsoft.Owin.Security.Notifications;
[assembly: OwinStartup(typeof(ClientDevicesManagement.Startup))]
namespace ClientDevicesManagement
{
public class Startup
{
// The Client ID (a.k.a. Application ID) is used by the application to uniquely identify itself to Azure AD
string clientId = System.Configuration.ConfigurationManager.AppSettings["ClientId"];
// RedirectUri is the URL where the user will be redirected to after they sign in
string redirectUrl = System.Configuration.ConfigurationManager.AppSettings["redirectUrl"];
// Tenant is the tenant ID (e.g. contoso.onmicrosoft.com, or 'common' for multi-tenant)
static string tenant = System.Configuration.ConfigurationManager.AppSettings["Tenant"];
// Authority is the URL for authority, composed by Azure Active Directory endpoint and the tenant name (e.g. https://login.microsoftonline.com/contoso.onmicrosoft.com)
string authority = String.Format(System.Globalization.CultureInfo.InvariantCulture, System.Configuration.ConfigurationManager.AppSettings["Authority"], tenant);
/// <summary>
/// Configure OWIN to use OpenIdConnect
/// </summary>
/// <param name="app"></param>
public void Configuration(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
// Sets the ClientId, authority, RedirectUri as obtained from web.config
ClientId = clientId,
Authority = authority,
RedirectUri = redirectUrl,
// PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
PostLogoutRedirectUri = redirectUrl,
//Scope is the requested scope: OpenIdConnectScopes.OpenIdProfileis equivalent to the string 'openid profile': in the consent screen, this will result in 'Sign you in and read your profile'
Scope = OpenIdConnectScope.OpenIdProfile,
// ResponseType is set to request the id_token - which contains basic information about the signed-in user
ResponseType = OpenIdConnectResponseType.IdToken,
// ValidateIssuer set to false to allow work accounts from any organization to sign in to your application
// To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name or Id (example: contoso.onmicrosoft.com)
// To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
TokenValidationParameters = new TokenValidationParameters()
{
ValidateIssuer = false
},
// OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
Notifications = new OpenIdConnectAuthenticationNotifications
{
AuthenticationFailed = OnAuthenticationFailed
}
}
);
}
/// <summary>
/// Handle failed authentication requests by redirecting the user to the home page with an error in the query string
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
private Task OnAuthenticationFailed(AuthenticationFailedNotification<OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> context)
{
context.HandleResponse();
context.Response.Redirect("/?errormessage=" + context.Exception.Message);
return Task.FromResult(0);
}
}
}
In my login.aspx I have added a asp button that runs this in the code behind:
protected void btn_azure_Click(object sender, EventArgs e)
{
Context.GetOwinContext().Authentication.Challenge(
new AuthenticationProperties { RedirectUri = "/" },
OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
web.config is as follows:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<REMOVED DB STINGS>
</connectionStrings>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="ClientId" value="REMOVED CLIENT ID" />
<add key="RedirectUrl" value="http://localhost:44463/" />
<add key="Tenant" value="common" />
<add key="Authority" value="https://login.microsoftonline.com/{0}" />
</appSettings>
<system.web>
<sessionState timeout="59"></sessionState>
<!--<trust level="full"/>-->
<compilation debug="true" targetFramework="4.5">
<assemblies>
<add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />
<add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
<!-- other configuration sections -->
<!--TEMPTEST-->
<siteMap defaultProvider="default">
<providers>
<clear />
<add name="admin" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/admin.sitemap" />
<add name="operation" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/operation.sitemap" />
<add name="tech" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/tech.sitemap" />
<add name="vendor" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/vendor.sitemap" />
<add name="default" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/default.sitemap" />
<add name="user" type="System.Web.XmlSiteMapProvider" siteMapFile="~/sitemaps/user.sitemap" />
</providers>
</siteMap>
<customErrors mode="Off" />
<authentication mode="Forms">
<forms loginUrl="login.aspx" name=".tgcpauth" defaultUrl="~/default.aspx" timeout="30" slidingExpiration="true" cookieless="UseCookies" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
<system.net>
<mailSettings>
<smtp deliveryMethod="Network">
<network host="aspmx.l.google.com" userName="REMOVED" password="REMOVED" port="25" />
</smtp>
</mailSettings>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
</system.net>
<location path="styles/login.css">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Refering to this guide, I'm willing to bet you're Azure AD is configured to use login URL of the sample app instead of your app and that is what's causing the 401. You can change the app registration though. Inside your application registration, click Manifest.
Make sure that homepage and replyURLs match the URL of your web project settings and save.
Also, feel free to update your tenant from common to <your azure tenant name>.onmicrosoft.com. You'll find this value the Settings > Properties > App ID URI

How to stop NHibernate from logging in Azure

I created an Azure web job project that uses Fluent NHibernate for its ORM. The program itself works fine and does what it's supposed to. However, after publishing the web job and running it live, every single SQL statement that NHibernate generates is output to the log, and I don't want this.
I thought that NHibernate by default does not output SQL statements, and I would have to enable it explicitly. However, it seems to be happening automatically, and I can't seem to turn it off. Is there some setting somewhere that I need to set to stop this logging?
This is my configuration, my app.config, and an example database query:
NHibernate configuration
public static ISessionFactory CreateSessionFactory()
{
string connString = ConnectionStringHelper.ConnectionString;
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(connString)
)
.Cache(c => c
.UseQueryCache())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Functions>())
.BuildSessionFactory();
}
App config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<connectionStrings>
<add name="AzureWebJobsDashboard" connectionString="DefaultEndpointsProtocol=https;AccountName=***;AccountKey=***" />
<add name="AzureWebJobsStorage" connectionString="DefaultEndpointsProtocol=https;AccountName=***;AccountKey=***" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.WindowsAzure.Storage" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Services.Client" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.7.0.0" newVersion="5.7.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.OData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.7.0.0" newVersion="5.7.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Data.Edm" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.7.0.0" newVersion="5.7.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Sample DB Query
using (ISessionFactory sessionFactory = CreateSessionFactory())
{
using (var session = sessionFactory.OpenSession())
{
var accountCrit = session.CreateCriteria<AccountRec>();
accountCrit.Add(Expression.Eq("AccountId", batch.AccountId));
var accounts = accountCrit.List<AccountRec>();
}
}
The above statement generates this in the Azure logs:
[09/06/2017 03:57:30 > 442002: INFO] NHibernate: SELECT this_.AccountId as AccountId9418_0_, this_.RingCentralId as RingCent2_9418_0_, this_.RingCentralExtension as RingCent3_9418_0_ FROM T_ACCOUNT this_ WHERE this_.AccountId = #p0;#p0 = '253' [Type: Int]
But I don't want it to generate that in the logs.
I'm guessing that somehow, Azure is enabling log4net and NHibernate is then able to broadcast its logging.
Try adding these blocks to your config and see what effect it has:
<configSections>
<section name="log4net"
type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<log4net debug="false">
<appender name="WindowsDebugOutput" type="log4net.Appender.DebugAppender, log4net">
<layout type="log4net.Layout.PatternLayout,log4net">
<param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n" />
</layout>
</appender>
<logger name="NHibernate.SQL" additivity="false">
<level value="OFF" />
<appender-ref ref="WindowsDebugOutput" />
</logger>
</log4net>
You might need to tweak the appender but the key is the OFF value in the logger.level. You might be able to set this at a higher, global level too. However, my knowledge of how to configure log4net is lacking.

Why is WebAPI Throwing a 'No MediaTypeFormatter' Error?

I have a strange issue happening with my WebAPI controller.
In my development environment (Win7, IIS 7.5) the method on the controller is called and the result is returned as expected.
In my integration environment (WIn Server 2003, IIS 6.0) I have deployed the code by copying it from my development box to the integration box. The method on the controller is called and returns the following error:
"No MediaTypeFormatter is available to read an object of type "EmailQueueResult"
from content with media type "text/html"."
What I don't understand is why I only get this error in my integration environment and not in my development environment.
public HttpResponseMessage Post([FromBody]EmailQueueMessage email)
{
EmailQueueResult result;
if (email != null)
{
try
{
var emailQueueIdList = QueueEmails(email);
QueueAttachments(email, emailQueueIdList);
foreach(var emailQueueId in emailQueueIdList)
{
UpdateEmailQueueDateQueued(emailQueueId, DateTime.Now);
}
result = new EmailQueueResult(0, "Email added to queue.", "", null);
}
catch (Exception e) {
result = new EmailQueueResult(2, "Error occurred.", e.Message, null);
}
}
else
{
result = new EmailQueueResult(1, "Email passed in was null.", "", null);
}
return ControllerContext.Request.CreateResponse(HttpStatusCode.OK, result, "application/json");
}
WebApiConfig.cs:
namespace App_Start
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
"ControllerWithBooleanParameter",
"api/{controller}/{showSentEmails}",
null,
new { boolConstraint = new IsBoolean() }
);
config.Routes.MapHttpRoute(
"ControllerWithIntegerParameter",
"api/{controller}/{id}",
null,
new { id = #"^\d+$" }
);
config.Routes.MapHttpRoute(
"Default",
"api/{controller}/{id}",
new { id = UrlParameter.Optional }
);
}
}
}
Web.config:
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="2.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="PreserveLoginUrl" value="true" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
</appSettings>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="true" />
</settings>
<mailSettings>
<smtp from="address#email.com">
<network host="smtp.server.com" port="25" />
</smtp>
</mailSettings>
</system.net>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="None" />
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
</namespaces>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true" />
<handlers>
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
<remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I have also tried having this method just return a straight EmailQueueResult, and that gave me the same results.
EDIT:
Here are some more tests that I tried along with their results:
When I send a POST request to the web service on my local machine using an external tool it works as expected.
When I execute code that calls the web service using my local copy of the code it works as expected.
When I send a POST request to the web service on the integration machine using an external tool it works as expected.
When I execute code that calls the web service using the integration machine I get the above error.
The line of code that sends the POST:
EmailQueueResult result = PostToWebService<EmailQueueMessage, EmailQueueResult>(EmailQueueBaseAddress, "application/json", EmailQueueUrlToCall, emailQueueMessage);
The PostToWebService method that actually makes the call:
protected returnType PostToWebService<dataType, returnType>(string baseAddress, string mediaType, string urlToCall, dataType data)
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(baseAddress);
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(mediaType));
MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
HttpContent content = new ObjectContent<dataType>(data, jsonFormatter);
HttpResponseMessage response = client.PostAsync(urlToCall, content).Result;
returnType result = response.Content.ReadAsAsync<returnType>().Result;
return result;
}
UPDATE: I installed the website and web service on a 2008 server. The only combination that fails seems to be when the web service on the 2003 box is called from the website on the 2003 box (2003 site -> 2003 service). The other three combinations (2008 site - > 2008 service, 2008 site -> 2003 service, 2003 site -> 2008 service) all seem to be working correctly.
Ok, it turns out this had NOTHING to do with the code, as some of you have expressed above. Basically, I had to change the local loopback address (127.0.0.1) in my hosts file on the 2003 box to the actual IP of the 2003 box and everything works as expexted now. Go figure.

To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider"

Currently whenever I try to register a user or login using the default membership services built into ASP.Net MVC4 on my host provider DiscountASP I receive the error
To call this method, the "Membership.Provider" property must be an instance of "ExtendedMembershipProvider".
This doesn't happen locally.
Here is my InitializeSimpleMembershipAttribute.cs:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public sealed class InitializeSimpleMembershipAttribute : ActionFilterAttribute
{
private static SimpleMembershipInitializer _initializer;
private static object _initializerLock = new object();
private static bool _isInitialized;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Ensure ASP.NET Simple Membership is initialized only once per app start
LazyInitializer.EnsureInitialized(ref _initializer, ref _isInitialized, ref _initializerLock);
}
private abstract class SimpleMembershipInitializer
{
protected SimpleMembershipInitializer()
{
Database.SetInitializer<UsersContext>(null);
try
{
using (var context = new UsersContext())
{
if (!context.Database.Exists())
{
// Create the SimpleMembership database without Entity Framework migration schema
((IObjectContextAdapter)context).ObjectContext.CreateDatabase();
}
}
WebSecurity.InitializeDatabaseConnection("DefaultConnection", "UserProfile", "UserId", "UserName", autoCreateTables: true);
}
catch (Exception ex)
{
throw new InvalidOperationException("The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588", ex);
}
}
}
}
Here is a full screenshot of the error:
Does anyone know how I can fix this or know an article that addresses it?
Try setting the following up in your web.config within the <system.web> node:
<roleManager enabled="true" defaultProvider="SimpleRoleProvider">
<providers>
<clear />
<add name="SimpleRoleProvider" type="WebMatrix.WebData.SimpleRoleProvider, WebMatrix.WebData" />
</providers>
</roleManager>
<membership defaultProvider="SimpleMembershipProvider">
<providers>
<clear />
<add name="SimpleMembershipProvider" type="WebMatrix.WebData.SimpleMembershipProvider, WebMatrix.WebData" />
</providers>
</membership>
<sessionState mode="InProc" customProvider="DefaultSessionProvider">
<providers>
<add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" />
</providers>
</sessionState>
Sounds like SimpleMembership isn't recognized when you go to use it.
Also, it may be worth including, the WebMatrix.webData library can be installed via NuGet:
PM> Install-Package Microsoft.AspNet.WebPages.WebData
Try to change the Login function under AccountController.cs
//
// POST: /Account/Login
[AllowAnonymous]
[HttpPost]
public ActionResult Login(LoginModel model, string returnUrl)
{
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
Did steps above but that didn't help. What helped was changing web.config:
<dependentAssembly>
<assemblyIdentity name="WebMatrix.Data" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebMatrix.WebData" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
I had the same error, but it was 100% references for me. I have had trouble getting WebMatrix.WebSecurity working several times...each time is because I did not create the project using the MVC 4 Internet template.
The key is that the references and config work by default in the template, so just recreate your project and it will be fine.
My fix is:
1. Back up my project to another folder.
2. Check out all files
3. Create a new MVC 4 Internet project, under the exact same name.
4. Copy + Paste (overwrite) the original project.
5. Add any missing references, changed routes, .config settings/DB connections.
I am just fix the same problem.
My problem start after update nuget packages.. My VS 2019 add new lines "membership" and "roleManager" in web.config so it is become duplicated (as previously has been exist).
I am commented the old values, then this "membership.provider" warning shown each time logoff and login.
Just use the old one because more suitable with your code.
Below is the generated code in web.config that I remove :
<membership defaultProvider="DefaultMembershipProvider">
<providers>
<add name="DefaultMembershipProvider" type="System.Web.Providers.DefaultMembershipProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/" />
</providers>
</membership>
<roleManager defaultProvider="DefaultRoleProvider">
<providers>
<add name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection" applicationName="/" />
</providers>
</roleManager>

Categories

Resources