Authorization Rules in Azure App Service is not working - json

I followed instructions on this blog post trying to enable anonymous access for the home page and redirect to Google if accessing /Admin page using this authorization.json.
{
"routes": [
{
"path_prefix": "/",
"policies": { "unauthenticated_action": "AllowAnonymous" }
},
{
"path_prefix": "/Admin",
"policies": { "unauthenticated_action": "RedirectToLoginPage" }
}
]
}
When I access the home page # http://mysite.azurewebsites.net/ it always navigates me to login page. And after I login then post redirection I am getting following errors inside log streaming.
2016-12-02T04:30:44 PID[11016] Verbose [Routes(Preview)] Attempting to load configuration from 'D:\home\site\wwwroot\authorization.json'.
2016-12-02T04:30:44 PID[11016] Critical System.Runtime.Serialization.SerializationException: There was an error deserializing the object of type Microsoft.Azure.AppService.Routes.RoutesConfig. Encountered unexpected character 'ï'. ---> System.Xml.XmlException: Encountered unexpected character 'ï'.
at System.Xml.XmlExceptionHelper.ThrowXmlException(XmlDictionaryReader reader, XmlException exception)
at System.Runtime.Serialization.Json.XmlJsonReader.ReadAttributes()
at System.Runtime.Serialization.Json.XmlJsonReader.ReadNonExistentElementName(StringHandleConstStringType elementName)
at System.Runtime.Serialization.Json.XmlJsonReader.Read()
at System.Xml.XmlBaseReader.IsStartElement()
at System.Xml.XmlBaseReader.IsStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri)
at System.Runtime.Serialization.XmlReaderDelegator.IsStartElement(XmlDictionaryString localname, XmlDictionaryString ns)
at System.Runtime.Serialization.XmlObjectSerializer.IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalIsStartObject(XmlReaderDelegator reader)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.InternalReadObject(XmlReaderDelegator xmlReader, Boolean verifyObjectName)
at System.Runtime.Serialization.XmlObjectSerializer.InternalReadObject(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
--- End of inner exception stack trace ---
at System.Runtime.Serialization.XmlObjectSerializer.ReadObjectHandleExceptions(XmlReaderDelegator reader, Boolean verifyObjectName, DataContractResolver dataContractResolver)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(XmlDictionaryReader reader)
at System.Runtime.Serialization.Json.DataContractJsonSerializer.ReadObject(Stream stream)
at Microsoft.Azure.AppService.Authentication.ModuleUtils.DecodeJson[T](Stream jsonStream)
at Microsoft.Azure.AppService.Routes.RoutesConfig.TryLoadFromFile(String configFilePath, Func`2 deserializer, RoutesConfig& config)
at Microsoft.Azure.AppService.Routes.RoutesConfig.TryLoadFromJsonFile(String configFilePath, RoutesConfig& config)
at Microsoft.Azure.AppService.Routes.RoutesModule.TryLoadRoutesConfig(HttpContextBase context)
at Microsoft.Azure.AppService.Routes.RoutesModule.<OnPostAuthenticateRequestAsync>d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.Azure.AppService.Authentication.HttpModuleDispatcher.<DispatchAsync>d__13.MoveNext()
2016-12-02T04:30:44 PID[11016] Information Sending response: 500.79 Internal Server Error
Additional details.
1. Re-started the site after publishing from visual studio as mentioned.
2. Those /Admin path I have inside AdminController.
3. The authorization.json is at the root of the site. If I navigate to PS D:\home\site\wwwroot> I am able to see the authorization.json file.
I don't know what I am getting wrong regarding the syntax of the file.

According to your description, I followed URL Authorization Rules and created the authorization.json in my Visual Studio. I could make it work as expected on my Azure Web App.
https://bruce-chen-001.azurewebsites.net/
https://bruce-chen-001.azurewebsites.net/admin/admin.html
I assumed that there be something wrong with your authorization.json file. I found a similar issue about Encountered unexpected character ‘ï’ error serializing JSON, you could refer to it.
Updated
Here is my authorization.json file:
Please make sure you have chosen Allow Anonymous requests (no action) under the “Action to take when request is not authenticated” in the Authentication/Authorization blade of your App Service on Azure Portal.

Related

How do I prevent Nest.js from logging an exception to the console?

Background
We use ApolloHandler to handle the exceptions in our Nest.js + GraphQL application.
Problem
Although ApolloHandler manages to create a structured GraphQL error response, every exception (plus it stack trace) also generates a console log and a logger entry [ExceptionHandler], polluting the application log with thousands of already managed input errors.
Question
How to set Nest.js to supress those ApolloHandler exceptions? Of course non ApolloHandler exceptions should remain logged.
Create your own custom logger to filter out those messages like:
export class AppLogger extends Logger {
error(message: string, trace: string, context?: string) {
if (message !== 'Validations failed!') {
super.error(message, trace, context)
}
}
}
And use it as
app.useLogger(new AppLogger())

Exception details in ABP framework

I wanna return the details of exception with ABP .NET Core, what I noticed is when I go to AbpAuditLogs table and App_Data\Logs logFile they contain the exception in details but when I use below method to return the exception it shows only general exception without any details (500 Internal Server Error)
try{
:
:
:
}
catch (Exception ex)
{
throw new System.ArgumentException(ex.InnerException.Message.ToString(), "original");
}
So, How could I return the specific Exception for the user for Example Email Validation Exception and so on?
Update:
I will explain more to make the question more clear :
The way that I handled the exception is attached with this question above .
The problem is when hitting a request on the service from swagger or Postman always see General Error with status Code 500 without any details and that force me to review the details of the exception from Log File or Log Table , I wanna see the details of the exception (e.g FileNotFoundException ) directly from Swagger or Postman without return back to Log File or AbpAuditLogs Table.
I think User Friendly Exception will work for you.
Because if an exception implements the IUserFriendlyException interface, then ABP does not change it's Message and Details properties and directly send it to the client.
throw new UserFriendlyException(
"Username should be unique!"
);
You can find more information here.
Actually, I found the answer in this question for #Mehdi Daustany .what I did is exactly what #Mehdi Daustany answered, I've added below code :
if (_env.EnvironmentName.ToLower() == "development")
Configuration.Modules.AbpWebCommon().SendAllExceptionsToClients = true;
under ***.Web.Core then the details of exception appeared in the Swagger
services.Configure<AbpExceptionHandlingOptions> (options =>
{
options.SendExceptionsDetailsToClients = true;
});
Above code will configure abp to return all the exception details. Just add it to the configuration.

Startup.cs error (ASP.Net Core configuration)

I am trying to set up an ASP.Net Core application to read in configuration settings from a json file. I am using VS2015 and .NetCore 1.0 (with .Net Core Tools preview 2). I am having problems getting a simple piece of boiler plate code to compile.
I am using the following code, which was published at
http://asp.net-hacker.rocks/2016/03/21/configure-aspnetcore.html
public Startup(IHostingEnvironment env)
{
// Set up configuration sources.
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddEnvironmentVariables();
if (env.IsDevelopment())
{
// This will push telemetry data through Application Insights
// pipeline faster, allowing you to view results immediately.
builder.AddApplicationInsightsSettings(developerMode: true);
}
Configuration = builder.Build();
}
However, the IDE/compiler complains that 'the name "Configuration" does not exist in the current context' (last line of code). The only suggestion from the IDE is to include Microsoft.Extensions.Configuration. However this is a namespace which does not contain an object or property named "Configuration".
In addition 'AddApplicationInsightsSettings' fails with does IConfigurationBuilder not contain a definition for AddApplicationInsightsSettings and no extension method AddApplicationInsightsSettings accepting a first argument of type IConfigurationBuilder could be found
Any suggestions please ?
Thanks
Simply add Configuration property to your Startup class, tutorial has missed this 'step':
public IConfigurationRoot Configuration { get; set; }
ConfigurationBuilder.Build() method just returns instance of IConfigurationRoot, that you should save, if need to get settings further in Startup class (in ConfigureServices method for example).
Regarding second error, looks like you didn't add the Application Insights dependency:
{
"dependencies": {
"Microsoft.ApplicationInsights.AspNetCore": "1.0.0"
}
}

Rethrowing an exception out of Scatter-Gather flow in Mule ESB

I have a very specific question, and i really searched the answer all over the place...
Here is a situation: i have a Scatter-Gather component with a custom aggregation strategy.
http://clip2net.com/s/j66jK8 - Image of a subflow
Semantic of this process is rather simple. Request comes with Basic Authentication Header, the upper road calls just empty java processor, which returns original payload, the lower road authenticates user over LDAP, and returns Boolean result of this authentication process. Custom aggregation class checks result and if authentication was OK, then returns original payload, which results from the road #1. If not OK, then throws exception. Nothing wrong here, it works.
There is a bit tricky thing. If a user passed wrong authentication data then exception occurs in ldap:bind module. According to documentation exception is propagated to the Scatter-Gather so i'm trying to catch it using this:
#Override
public MuleEvent aggregate(AggregationContext context) throws MuleException {
for (MuleEvent event: context.collectEventsWithExceptions()) {
event.getMessage().getExceptionPayload().getException().printStackTrace();
throw new RuntimeException(event.getMessage().getExceptionPayload().getException());
}
MuleEvent result = DefaultMuleEvent.copy(context.getEvents().get(0));
if (!(Boolean) context.getEvents().get(1).getMessage().getPayload()) {
throw new SecurityException();
}
return result;
}
BUT!
As a result i see exception which stacktrace does not have javax.naming.AuthenticationException which was rased by ldap:bind component, and was printed to log automaticaly (see below).
So, my question is: how can i reach and rethrow this javax.naming.AuthenticationException exception out of Custom Aggregation Class?
I'd appreciate all you ideas and help. Thank you in advance.
WARN 2014-10-15 20:51:18,552 [[minkult].ScatterGatherWorkManager.02] org.mule.module.ldap.api.jndi.LDAPJNDIConnection: Bind failed.
ERROR 2014-10-15 20:51:18,559 [[minkult].ScatterGatherWorkManager.02] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Work Descriptor. Root Exception was: javax.naming.AuthenticationException: [LDAP: error code 49 - INVALID_CREDENTIALS: Bind failed: Attempt to lookup non-existant entry: cn=sim,ou=people,dc=example,dc=com]; resolved object com.sun.jndi.ldap.LdapCtx#5de37d66. Type: class javax.naming.AuthenticationException
COUNT: 1
org.mule.api.transport.DispatchException: route number 1 failed to be executed. Failed to route event via endpoint: InterceptingChainLifecycleWrapper 'wrapper for processor chain 'null''
[
ScriptComponent{CheckAuth.component.553657235},
org.mule.module.ldap.processors.BindMessageProcessor#647af13d,
org.mule.module.ldap.processors.SearchMessageProcessor#2aac6fa7,
InvokerMessageProcessor [name=ldapUtils, object=com.at.mkrf.aggregate.LDAPUtils#5714c7da, methodName=findGroupByName, argExpressions=[#[payload], #[systemName]], argTypes=[Ljava.lang.Class;#5af349a6]
]. Message payload is of type: NullPayload
On a CompositeRoutingException, you can call:
exception.getExceptions().values()
to get an Array of Throwables thrown from within the scatter-gather. Then just re-throw the appropriate exception.

Windows Metadata Exporter Crashes when Compiling Windows Runtime Component

I'm attempting to create a Windows Runtime Component for use in a Windows 8 app.
This is essentially a helloworld level application and so has nothing complex. The only thing that I need to do to replicate the issue is to include a pair of methods such as the following:
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new List<string>().ToArray();
}
Whenever I compile the project, the Windows Metadata Exporter crashes.
I've dug into the errors generated in the output window by increasing the build verbosity and I've found that the error occurs after "Exporting 'obj\Debug\HelloWorld.Logic.winmdobj'."
By attempting to run winmdexp.exe from command line with the same parameters, it seems that it's having trouble finding metadata for the System.Xml files. (warning WME0004 : Could not find referenced metadata 'C:\Program Files(x86)\ReferenceAssemblies\Microoft\Framework.NETCore\v4.5.1\System.Xml.Serialization.dll'.)
The full stack trace of the error is:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.
at Microsoft.Tools.WinMDExp.AssemblyReferenceExtensionMethods.IsWindowsRuntimeMetadata(IAssemblyReference assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.IsWindowsRuntimeType(ITypeReference type, Boolean allowGenericParam)
at Microsoft.Tools.WinMDExp.ExportValidator.<>c__DisplayClasse.<GetAlternativeTypes>b__8(<>f__AnonymousType0`2 <>h__TransparentIdentifier5)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection)
at System.Collections.Generic.List`1.AddRange(IEnumerable`1 collection)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativeTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& isTask, Boolean allowGenericTypeParam)
at Microsoft.Tools.WinMDExp.ExportValidator.GetAlternativesTypesForGenericTypes(IGenericTypeInstanceReference parameterType, IMethodDefinition containingMethod, String& errorMsg)
at Microsoft.Tools.WinMDExp.ExportValidator.CheckAlternateTypes(ITypeReference parameterType, IMethodDefinition containingMethod, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportParameterType(IMethodDefinition containingMethod, ITypeReference parameterType, Boolean& reportedError)
at Microsoft.Tools.WinMDExp.ExportValidator.ValidateExportMethod(IMethodDefinition method)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IMethodDefinition method)
at Microsoft.Cci.MetadataTraverser.Traverse(IEnumerable`1 methods)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(ITypeDefinition typeDefinition)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(INamedTypeDefinition namedTypeDefinition)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Traverse(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataTraverser.Dispatcher.Visit(INamespaceTypeDefinition namespaceTypeDefinition)
at Microsoft.Cci.MetadataReader.ObjectModelImplementation.NamespaceType.Dispatch(IMetadataVisitor visitor)
at Microsoft.Tools.WinMDExp.ExportValidator.Validate(ITypeDefinition type)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IModule module)
at Microsoft.Cci.MetadataTraverser.TraverseChildren(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportValidator.TraverseChildren(IAssembly assembly)
at Microsoft.Cci.MetadataTraverser.Traverse(IAssembly assembly)
at Microsoft.Tools.WinMDExp.ExportVisitor.Export(IAssembly assembly)
at Microsoft.Tools.WinMDExp.Exporter.Export()
at Microsoft.Tools.WinMDExp.Program.Main(String[] args)
If anyone has any idea what's going on and how I can get my component compiling I'd be grateful.
James
P.S. I transferred the project to a colleague's PC and they had the same issue so I doubt if it's anything to do with my setup (Windows 8.1 x64, Visual Studio 2013 Ultimate).
I've managed to figure this out myself.
It seems as though there is a bug when using string[] (or other arrays) as the generic type for IAsyncOperation.
I have managed to work around this because actually I will want to return IDictionary objects and ILists, which work fine:
/* //Won't Work - crashes Windows Metadata Exporter
public IAsyncOperation<string[]> GetThings()
{
return GetThingsAsync().AsAsyncOperation();
}
private async Task<string[]> GetThingsAsync()
{
return new [] {"I am a string"};
}
*/
//This Works
public IAsyncOperation<IList<string>> GetThingsList()
{
return GetThingsListAsync().AsAsyncOperation();
}
private async Task<IList<string>> GetThingsListAsync()
{
return new[] { "I am a string" };
}
Hopefully this will be of use to anyone else who comes across this weird behaviour.