Using multiple AWS CLI profiles to manage development environments

To avoid setting global AWS credentials/access to the AWS CLI you can use CLI Profiles like this:

Create a new profile:
aws configure –profile {profilename}

Then use it by adding the profile after a command like in the example below:
aws ecr get-login –no-include-email –region eu-central-1 –profile {profilename}


Thats it, this will allows you to use different access keys and policies for different purposes without different AWS security configurations overriding others.


This is especially true when you want to test your code against real world security settings in the cloud that can’t have higher level rights.


C# .NET Getting Windows Directory File Permissions programmatically



I while back I needed to do a security trim on files in a Windows file system based on returned search results by SharePoint search. Since in SharePoint 2010 search indexing does not know how to take into consideration file system rights for searches there was a need to do a security trimming based on what privileges you have in Active Directory and what you are given to the file itself.

Since there where alot of moving parts and hard to find out which classes and function where needed to actually do this specific task I finally found a source that gave a great sample how to do this:

Unfortunately the source above does not exist anymore for whatever reason. So for those who might need similar functionality through code here is the sample code from the link above and what you need class wise.

In the code below what you need is to call the following static function to check for if the user has certain privileges:

FileSystemRights rights = FileSystemEffectiveRights.GetRights(username, filelocation);

Then call the following function to test against the given file system privileges and what you want to user to have in the file system.
bool canReadExecute = rights.HasRights(FileSystemRights.ReadAndExecute);


Classes and enumeration needed for this functionality(there are many moving parts here and you might have to work with Active Directory and File System to test this code):

FileSystemRights Enumeration

FileSystemAccessRule Class

AccessControlType Enumeration

AuthorizationRuleCollection Class

SecurityIdentifier Class

FileSystemAccessRule Class

FileInfo Class

PrincipalContext Class

UserPrincipal Class

PrincipalSearcher Class

WindowsIdentity Class


Sample code – :

public static class FileSystemRightsEx
public static bool HasRights(this FileSystemRights rights, FileSystemRights testRights)
return (rights & testRights) == testRights;

public static class FileSystemEffectiveRights

public static FileSystemRights GetRights(string userName, string path)
if (string.IsNullOrEmpty(userName))
throw new ArgumentException(“UserName not defined!”);

//if (!Directory.Exists(path) && !File.Exists(path))
// throw new ArgumentException(string.Format(“path: {0}”, path));

return GetEffectiveRights(userName, path);

private static FileSystemRights GetEffectiveRights(string userName, string path)
FileSystemAccessRule[] accessRules = GetAccessRulesArray(userName, path);
FileSystemRights denyRights = 0;
FileSystemRights allowRights = 0;

for (int index = 0, total = accessRules.Length; index < total; index++)
FileSystemAccessRule rule = accessRules[index];

if (rule.AccessControlType == AccessControlType.Deny)
denyRights |= rule.FileSystemRights;
allowRights |= rule.FileSystemRights;

return (allowRights | denyRights) ^ denyRights;

private static FileSystemAccessRule[] GetAccessRulesArray(string userName, string path)
// get all access rules for the path – this works for a directory path as well as a file path
AuthorizationRuleCollection authorizationRules = (new FileInfo(path)).GetAccessControl().GetAccessRules(true, true, typeof(SecurityIdentifier));

// get the user’s sids
string[] sids = GetSecurityIdentifierArray(userName);

// get the access rules filtered by the user’s sids
return (from rule in authorizationRules.Cast<FileSystemAccessRule>()
where sids.Contains(rule.IdentityReference.Value)
select rule).ToArray();

private static string[] GetSecurityIdentifierArray(string userName)
// connect to the domain
PrincipalContext pc = new PrincipalContext(ContextType.Domain);

// search for the domain user
UserPrincipal user = new UserPrincipal(pc) { SamAccountName = userName };
PrincipalSearcher searcher = new PrincipalSearcher { QueryFilter = user };
user = searcher.FindOne() as UserPrincipal;

if (user == null)
throw new ApplicationException(string.Format(“Invalid User Name: {0}”, userName));

// use WindowsIdentity to get the user’s groups
WindowsIdentity windowsIdentity = new WindowsIdentity(user.UserPrincipalName);
string[] sids = new string[windowsIdentity.Groups.Count + 1];

sids[0] = windowsIdentity.User.Value;

for (int index = 1, total = windowsIdentity.Groups.Count; index < total; index++)
sids[index] = windowsIdentity.Groups[index].Value;

return sids;

Good To Know: ASP .NET MVC Reference Guide


This is my collection of sources of the most “relevant” information on ASP .NET MVC. Hope this helps you if you need information on MVC and web development with Microsoft Tools.

Design the application architecture – Application Layers, Azure, State Management, Caching, WebSocket, HTTPModules
ASP.NET MVC 4 Content Map
.NET On-Premises/Cloud Hybrid Application Using Service Bus Relay
A Beginner’s Guide to HTTP Cache Headers
ASP.NET MVC Views Overview
ASP.NET Routing
ASP.NET State Management Overview
Beginners guide to HTML5 Application Cache API
Caching in .NET Framework Applications
Controllers and Action Methods in ASP.NET MVC Applications
Differences Between ASMX and WCF Services
Distributed Cache
Donut Caching and Donut Hole Caching with Asp.Net MVC 4
Donut Caching with ASP.NET MVC 4
Entity Framework
Extending ASP.NET Processing with HTTP Modules
Getting Started with ASP.NET Web API 2
Global.asax File
HOW TO: Write a Simple Web Service by Using Visual C# .NET
HTML5 Web Storage
HTTP Handlers and HTTP Modules Overview
IHttpModule Interface
Improving Performance with Output Caching (C#)
INFO: ASP.NET Configuration Overview
Introducing “Razor” – a new view engine for ASP.NET
Introducing WebSocket HTML5
Introducing Windows Azure
Introducing Windows Azure AppFabric Applications
Introduction to HTTP Modules
Learn About ASP.NET Web API
patterns & practices: Data Access Guidance
Run Startup Tasks in Windows Azure
The WebSocket API
Two Ways of Passing HTML5 Web Storage Data to ASP.NET
Use AppCmd.exe to Configure IIS at Startup
Using an Asynchronous Controller in ASP.NET MVC
WCF Web HTTP Programming Model
Windows Azure Execution Models
Windows Azure Jump Start (03): Windows Azure Lifecycle, Part 1
Windows Azure Jump Start (04): Windows Azure Lifecycle, Part 2
Design the user experience – User Interface Design and Implementation
About Font Embedding
AjaxExtensions.BeginForm Method
ASP.NET MVC 4 Content Map
Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers.
CSS Media Types
CSS Reference
DisplayModeProvider Class
EditorExtensions.EditorFor Method
How To Test ModelState.IsValid In ASP.NET MVC
How to: Implement Remote Validation in ASP.NET MVC
How to: Validate Model Data Using DataAnnotations Attributes
HTML DOM innerHTML Property
Html.BeginForm() vs Ajax.BeginForm() in MVC3
HTML5 New Input Types
HtmlHelper Class
JavaScript prototype Property
JavaScript Tutorial
jQuery Documentation
jQuery Mobile
jQuery Mobile Framework
jQuery UI
JsonRequestBehavior Enumeration
JsonResult Class
Kendo UI Mobile
LinkExtensions.ActionLink Method
ModelStateDictionary.IsValid Property
Partial View in ASP.NET MVC 4
Rendering a Form in ASP.NET MVC Using HTML Helpers
Sencha Touch
Simplifying HTML generation in code using Razor templates
Styles.Render Method
System.Web.Mvc.Ajax Namespace
System.Web.Mvc.Html Namespace
Understanding JavaScript Prototypes.
Using the viewport meta tag to control layout on mobile browsers
ValidationExtensions.ValidationMessageFor Method
ValidationMessageFor HTML Helper in MVC3 Razor
Vendor-specific Properties
Views and UI Rendering in ASP.NET MVC Applications
Develop User Experience – Search Engine Optimization, Globalization and Localization, Routes, Application Behaviour, Network Optimization
13 ASP.NET MVC extensibility points you have to know
Action Filtering in ASP.NET MVC Applications
ActionResult Class
ActionResult.ExecuteResult Method
An Introduction to ASP.NET MVC Extensibility
ASP.NET Globalization and Localization
ASP.NET MVC – Basic overview of different view engines
ASP.NET MVC Custom Model Binder
ASP.NET MVC Model Binding and Data Annotation
ASP.NET MVC Routing Overview (C#)
ASP.NET Routing
Attribute Usage Guidelines
BindAttribute Class
Bundling and Minification
Configuring HTTP Compression in IIS 7
CultureInfo Class
Custom Controller Factory in ASP.NET MVC
FilterAttribute Class
HandleErrorAttribute Class
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization
HTML 5: The Markup Language (ARIA Edition)
Mage.exe (Manifest Generation and Editing Tool)
Microsoft Ajax Content Delivery Network
MVC 4 Part 4 – Bundles and Optimisation
MvcRouteHandler and MvcHandler in ASP.NET MVC Framework
ResourceManager Class
Search Engine Optimization Toolkit
Subscriber Locale Codes
The Features and Foibles of ASP.NET MVC Model Binding
Thread.CurrentUICulture Property
Using CDN for Windows Azure
Using Value Providers in ASP.NET 4.5
Walkthrough: Organizing an ASP.NET MVC Application using Areas
WebPart.AuthorizationFilter Property
What’s the Difference Between a Value Provider and Model Binder?
ViewResultBase Class
VirtualPathProviderViewEngine Class
Troubleshoot and debug web applications – Runtime issues, Exception handling, Testing, Debuging
AppDomain.FirstChanceException Event
Assert Class
Beginners Guide to Performance Profiling
Code Contracts
Code Contracts
Code Contracts for .NET
Collect Logging Data by Using Windows Azure Diagnostics
Configuring Performance Sessions for Profiling Tools
Configuring Windows Azure Diagnostics
Controller.OnException Method
Create and Use Performance Counters in a Windows Azure Application
customErrors Element (ASP.NET Settings Schema)
Debugging a Cloud Service in Visual Studio
Debugging Cloud Services
HandleErrorAttribute Class
How To Put Your Toe Into ASP.NET MVC Integration Testing
How to: Break When an Exception is Thrown
How to: Handle Application-Level Errors
How to: Receive First-Chance Exception Notifications
Integration Testing Your ASP.NET MVC Application
Invariants and Inheritance in Code Contracts
Isolating Code Under Test with Microsoft Fakes
Logging Error Details with ASP.NET Health Monitoring (C#)
MVC: Error Page implementation
Performance and Diagnostics Hub in Visual Studio 2013
Performance Profiler in Visual Studio 2012
Quick Start: Test Driven Development with Test Explorer
Record and run a web performance test
Remote Debugging a Window Azure Web Site with Visual Studio 2013
System.Diagnostics.Contracts Namespace
TraceListener Class
Tracing in ASP.NET MVC Razor Views
Understanding Web Tests
Unit Testing in ASP.NET MVC Applications
Use the Windows Azure Diagnostics Configuration File
Walkthrough: Using TDD with ASP.NET MVC
What is a First Chance Exception?
Windows Performance Monitor
Working with Web Tests
Design And Implement Security – Authentication, Authorization, Data Integrity, Hacks and Security, Communication
A Beginner’s Tutorial on Custom Forms Authentication in ASP.NET MVC Application
A Custom SqlRoleProvider for “Authenticated Users”
Anti-Cross Site Scripting Library
Apple Secure Coding Guide
ASP.NET Impersonation
ASP.NET MVC Authentication – Global Authentication and Allow Anonymous
Asp.Net MVC With the ValidateAntiForgeryToken For Cross Site Request Forgeries
ASP.NET Web Application Security
Authenticating Users with Windows Authentication (C#)
AuthorizeAttribute Class
Basic Security Practices for Web Applications
Client Certificates vs. Server Certificates – What’s the Difference?
Configure ASP.NET Impersonation Authentication (IIS 7)
Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#)
CryptoStream Class
Custom Authentication and Authorization in ASP.NET MVC
Custom Authentication with MVC 3.0
Custom Membership Providers
Custom Membership Providers – Task Manager
Custom Role Providers
DpapiProtectedConfigurationProvider Class
FormsIdentity Class
How to Authenticate Web Users with Windows Azure Active Directory Access Control
How to configure Custom Membership and Role Provider using ASP.NET MVC4
How to Create an Intranet Site Using ASP.NET MVC
How to: Create a WindowsPrincipal Object
How to: Create GenericPrincipal and GenericIdentity Objects
How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA
How To: Use Membership in ASP.NET 2.0
HtmlHelper.AntiForgeryToken Method
HttpEncoder Class
Microsoft Web Protection Library
OAuthWebSecurity.Login Method
OAuthWebSecurity.VerifyAuthentication Method
patterns & practices Improving Web Services Security – Now Released
Programming WCF Security
Provider Model Design Pattern and Specification, Part 1
RequireHttpsAttribute Class
Role-Based Authorization (C#)
RSACryptoServiceProvider Class
RsaProtectedConfigurationProvider Class
SAML 2.0 tokens and WIF – bridging the divide
Securing Your ASP.NET Applications
Security Practices: ASP.NET Security Practices at a Glance
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties
SqlMembershipProvider Class
SqlRoleProvider Class
System.Security.Cryptography Namespace
System.Threading.Thread.CurrentPrincipal vs. System.Web.HttpContext.Current.User or why FormsAuthentication can be subtle
Thread.CurrentPrincipal Property
Understanding and Using Simple Membership Provider in ASP.NET MVC 4.0
Understanding the Forms Authentication Ticket and Cookie
Understanding Windows Identity Foundation (WIF) 4.5
Using IIS Authentication with ASP.NET Impersonation
Using OAuth Providers with MVC 4
Walkthrough: Using Forms Authentication in ASP.NET MVC
WCF Security Fundamentals
WCF Using Windows Authentication and SqlRoleProvider over basicHttp
WebSecurity Class
Windows Communication Foundation Security
WindowsIdentity Class
WS-Trust 1.3 OASIS Standard

A great Security guide for veteran and new developers alike


Got this word of this great PDF from Apple on security issues to know and to take into consideration for your applications:

It looks rock solid with issues that are relevant to any application both web and offline apps.

SharePoint Forms Based Authentication against Active Directory with password change


In this post I am going to guide you through the steps necessary to setup a FBA against AD with the possibility to change your password. I will not write a step by step instructions how to do it BUT based on what I had to fight and solve I will post the best possible ways to do these steps to my knowledge:

1. The first step to do is to to configure your existing web application(or create a new one) to support claims authentication and to follow the steps to configure the AD support for the forms authentication.

Configure forms-based authentication for a claims-based web application in SharePoint 2013:

Migrate from classic-mode to claims-based authentication in SharePoint 2013:

Also for SQL Server Authentication if needed:

2. The second step is to create a custom sign in page to apply custom logic to the authentication phase like changing the password of a user:

A few examples how to do it:

3. The third step is to create the custom code to change the user password:

What you need to do:

An Active Directory user with delegated privileges to the OU or CN where the authenticated users reside. This user must have the privileges to reset and change passwords.

Make use of Secure Store Service in SP2010 to store the AD account and other information securely. Notice: When accessing the Secure Store Service from the sign in page the user that will be accessing the SSS is anonymous user. So what you need to do is to use SPSecurity.RunWithElevatedPrivileges delegate.

Implement the custom .NET code to change the password with impersonation so get access to the AD(notice that the user which runs the code is anonymous)

NOTICE: I had problems using another set of .NET class and function to perform the change password trough code. Problems with authorization against AD:

4. Bonus: How to get rid of the Mixed authentication selection page for internal users of the web application.

When you access a SharePoint application that has both Forms and Windows Authentication enabled for the application SharePoint will ask the users to select which authentication to use. This is not necessarily what you want internal users to see. Most probably the functionality required is so that the internal users logs in normally as if it is an intranet website.

The following code below is meant to be used for internal users who are not accessing the site through the forms sign in page. What you need to is to create a custom httpmodule and in the handler code below identify under which page you are and based on that to directly redirect the user to the front page of the website without asking users to choose which authentication method to use. Sample code(not the best but does the trick 🙂 ):

static void context_PreRequestHandlerExecute(object sender, EventArgs e)


            HttpApplication httpApp = sender as HttpApplication;

            HttpContext context = httpApp.Context;

            string httpUrl = context.Request.Url.ToString().ToLower();

            var page = HttpContext.Current.CurrentHandler as Page;

            string previousPageUrl = context.Cache[CacheKey_LoginStatus] as String;

            String intranetURL = System.Configuration.ConfigurationManager.AppSettings[“authentication page in sharepoint app setting value, this is sharepoint specific sample(modify for your environment): http://localhost:46752/_windows/default.aspx?ReturnUrl=/_layouts/Authenticate.aspx?Source=/_windows/default.aspx&amp;Source=/_windows/default.aspx “%5D ?? null;

            Uri httpUrlURI = new Uri(httpUrl);

            String localhostCalculated = httpUrlURI.AbsoluteUri.Replace(httpUrlURI.PathAndQuery, String.Empty);



                if (context.Request != null && String.IsNullOrEmpty(intranetURL) == false)


                    if (httpUrl.Contains(“/_layouts/closeconnection.aspx?loginasanotheruser=true”))


                        context.Response.Cookies.Add(new HttpCookie(CacheKey_LoginStatus, “true”));


                    if (httpUrl.Contains(“/_layouts/signout.aspx”))


                        context.Response.Cookies.Add(new HttpCookie(CacheKey_LoginStatus, “true”));


                    bool isSignOut = false;

                    Boolean.TryParse(context.Response.Cookies[CacheKey_LoginStatus].Value, out isSignOut);

                    if (isSignOut)



                        context.Response.Redirect(ConfigurationManager.AppSettings[“redirect page to somewhere else than the application app settings value this can be any page you want”]);


                    else if (httpUrl.Contains(localhostCalculated + “/_login/default.aspx”))






            catch (Exception Ex)



            if (page == null) return;

            page.PreInit += page_PreInit;


OR you could do something like the following link where you do a IP based functionality:

Possible problem areas – Good to know:

Office documents:

Authentication requests when you open Office documents:
How documents are opened from a Web site in Office 2003:

For Juniper VPNs:

[SSL VPN] Known Issues and limitations when accessing Microsoft SharePoint 2003 / 2007 / 2010 resources via the Web Rewrite Access mechanism:

[SSL VPN] Supported features and functionality of SharePoint 2010 when accessed via Secure Access SSL VPN’s Web/Rewrite access method: