C# .NET Getting Windows Directory File Permissions programmatically

Hi,

 

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:

http://www.conarc.com/blog/2010/03/25/programmatically-getting-effective-directoryfile-permissions/

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 – http://www.conarc.com/blog/2010/03/25/programmatically-getting-effective-directoryfile-permissions/ :

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;
}
else
{
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;
}
}

Advertisements

Good To Know: ASP .NET MVC Reference Guide

Hi,

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 http://www.asp.net/mvc/overview/getting-started/aspnet-mvc-content-map
.NET On-Premises/Cloud Hybrid Application Using Service Bus Relay http://www.windowsazure.com/en-us/documentation/articles/cloud-services-dotnet-hybrid-app-using-service-bus-relay/
A Beginner’s Guide to HTTP Cache Headers http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/
ASP.NET MVC Views Overview http://www.asp.net/mvc/tutorials/older-versions/views/asp-net-mvc-views-overview-cs
ASP.NET Routing http://msdn.microsoft.com/en-us/library/cc668201.aspx
ASP.NET State Management Overview http://msdn.microsoft.com/en-us/library/75x4ha6s.ASPX
Beginners guide to HTML5 Application Cache API http://www.html5rocks.com/en/tutorials/appcache/beginner/
Caching in .NET Framework Applications http://msdn.microsoft.com/en-us/library/dd997357%28v%3DVS.110%29.aspx
Controllers and Action Methods in ASP.NET MVC Applications http://msdn.microsoft.com/en-us/library/dd410269%28v=vs.100%29.aspx
Differences Between ASMX and WCF Services http://msdn.microsoft.com/en-us/library/ff648181.aspx
Distributed Cache http://csharp-guide.blogspot.fi/2013/06/distributed-cache.html
Donut Caching and Donut Hole Caching with Asp.Net MVC 4 http://www.dotnet-tricks.com/Tutorial/mvc/ODJa210113-Donut-Caching-and-Donut-Hole-Caching-with-Asp.Net-MVC-4.html
Donut Caching with ASP.NET MVC 4 http://www.dhuvelle.com/2012/10/donut-caching-with-aspnet-mvc-4.html
Entity Framework http://msdn.microsoft.com/en-us/data/ef.aspx
Extending ASP.NET Processing with HTTP Modules http://msdn.microsoft.com/en-us/library/zec9k340%28v=vs.85%29.aspx
Getting Started with ASP.NET Web API 2 http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
Global.asax File http://msdn.microsoft.com/en-us/library/1xaas8a2%28v=vs.71%29.aspx
HOW TO: Write a Simple Web Service by Using Visual C# .NET http://support.microsoft.com/kb/308359
HTML5 Web Storage http://www.w3schools.com/html/html5_webstorage.asp
HTTP Handlers and HTTP Modules Overview http://msdn.microsoft.com/en-us/library/bb398986%28v=vs.100%29.aspx
IHttpModule Interface http://msdn.microsoft.com/en-us/library/system.web.ihttpmodule%28v%3Dvs.71%29.aspx
Improving Performance with Output Caching (C#) http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/improving-performance-with-output-caching-cs
INFO: ASP.NET Configuration Overview http://support.microsoft.com/kb/307626
Introducing “Razor” – a new view engine for ASP.NET http://weblogs.asp.net/scottgu/archive/2010/07/02/introducing-razor.aspx
Introducing WebSocket HTML5 http://www.html5rocks.com/en/tutorials/websockets/basics/
Introducing Windows Azure http://www.windowsazure.com/en-us/documentation/articles/fundamentals-introduction-to-Windows-Azure/
Introducing Windows Azure AppFabric Applications http://blogs.msdn.com/b/appfabric/archive/2011/06/20/introducing-windows-azure-appfabric-applications.aspx
Introduction to HTTP Modules http://msdn.microsoft.com/en-us/library/ms178468%28v=vs.85%29.aspx
Learn About ASP.NET Web API http://www.asp.net/web-api
patterns & practices: Data Access Guidance http://dataguidance.codeplex.com/
Run Startup Tasks in Windows Azure http://msdn.microsoft.com/en-us/library/windowsazure/hh180155.aspx
The WebSocket API http://dev.w3.org/html5/websockets/
Two Ways of Passing HTML5 Web Storage Data to ASP.NET http://www.codeguru.com/csharp/.net/two-ways-of-passing-html5-web-storage-data-to-asp.net.htm
Use AppCmd.exe to Configure IIS at Startup http://msdn.microsoft.com/en-us/library/windowsazure/hh974418.aspx
Using an Asynchronous Controller in ASP.NET MVC http://msdn.microsoft.com/en-us/library/ee728598%28v=vs.100%29.aspx
WCF Web HTTP Programming Model http://msdn.microsoft.com/en-us/library/bb412169%28v=vs.110%29.aspx
Windows Azure Execution Models http://www.windowsazure.com/en-us/documentation/articles/fundamentals-application-models/
Windows Azure Jump Start (03): Windows Azure Lifecycle, Part 1 http://channel9.msdn.com/posts/Windows-Azure-Jump-Start-03-Windows-Azure-Lifecycle-Part-1
Windows Azure Jump Start (04): Windows Azure Lifecycle, Part 2 http://channel9.msdn.com/posts/Windows-Azure-Jump-Start-04-Windows-Azure-Lifecycle-Part-2
Design the user experience – User Interface Design and Implementation
About Font Embedding http://msdn.microsoft.com/en-us/library/ms533034%28v%3DVS.85%29.aspx
AjaxExtensions.BeginForm Method http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax.ajaxextensions.beginform%28v=vs.118%29.aspx
ASP.NET MVC – HTML Helpers http://www.w3schools.com/aspnet/mvc_htmlhelpers.asp
ASP.NET MVC 4 Content Map http://msdn.microsoft.com/en-us/library/gg416514%28v%3Dvs.108%29.aspx
Compatibility tables for support of HTML5, CSS3, SVG and more in desktop and mobile browsers. http://caniuse.com/
CSS Media Types http://www.w3schools.com/css/css_mediatypes.asp
CSS Reference http://www.w3schools.com/cssref/default.asp
DefaultDisplayModes.Instance http://chipburris.wordpress.com/tag/displaymodeprovider-instance/
DisplayModeProvider Class http://msdn.microsoft.com/en-us/library/system.web.webpages.displaymodeprovider%28v=vs.111%29.aspx
EditorExtensions.EditorFor Method http://msdn.microsoft.com/en-us/library/system.web.mvc.html.editorextensions.editorfor%28v=vs.118%29.aspx
How To Test ModelState.IsValid In ASP.NET MVC http://randomtype.ca/blog/how-to-test-modelstate-isvalid-in-asp-net-mvc/
How to: Implement Remote Validation in ASP.NET MVC http://msdn.microsoft.com/en-us/library/gg508808%28v=vs.98%29.aspx
How to: Validate Model Data Using DataAnnotations Attributes http://msdn.microsoft.com/en-us/library/ee256141%28v=vs.100%29.aspx
HTML DOM innerHTML Property http://www.w3schools.com/jsref/prop_html_innerhtml.asp
Html.BeginForm() vs Ajax.BeginForm() in MVC3 http://www.codeproject.com/Articles/429164/Html-BeginForm-vs-Ajax-BeginForm-in-MVC3
HTML5 http://msdn.microsoft.com/en-us/library/ie/hh673546%28v%3Dvs.85%29.aspx
HTML5 New Input Types http://www.w3schools.com/html/html5_form_input_types.asp
HtmlHelper Class http://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper%28v=vs.118%29.aspx
JavaScript prototype Property http://www.w3schools.com/jsref/jsref_prototype_math.asp
JavaScript Tutorial http://www.w3schools.com/js/
jQuery http://jquery.com/
jQuery Documentation http://api.jquery.com/
jQuery Mobile http://jquerymobile.com/
jQuery Mobile Framework http://jquerymobile.codeplex.com/
jQuery UI http://jqueryui.com/
JsonRequestBehavior Enumeration http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonrequestbehavior%28v=vs.118%29.aspx
JsonResult Class http://msdn.microsoft.com/en-us/library/system.web.mvc.jsonresult%28v=vs.118%29.aspx
Kendo UI Mobile http://www.telerik.com/kendo-ui-mobile
KnockoutJS http://knockoutjs.com/documentation/introduction.html
LinkExtensions.ActionLink Method http://msdn.microsoft.com/en-us/library/system.web.mvc.html.linkextensions.actionlink%28v=vs.118%29.aspx
ModelStateDictionary.IsValid Property http://msdn.microsoft.com/en-us/library/system.web.mvc.modelstatedictionary.isvalid%28v=vs.118%29.aspx
Partial View in ASP.NET MVC 4 http://www.codeproject.com/Tips/617361/Partial-View-in-ASP-NET-MVC-4
Rendering a Form in ASP.NET MVC Using HTML Helpers http://msdn.microsoft.com/en-us/library/dd410596%28v=vs.100%29.aspx
Sencha Touch http://www.sencha.com/products/touch/
Simplifying HTML generation in code using Razor templates http://www.codeproject.com/Articles/457307/Simplifying-HTML-generation-in-code-using-Razor-te
Styles.Render Method http://msdn.microsoft.com/en-us/library/system.web.optimization.styles.render%28v=vs.110%29.aspx
System.Web.Mvc.Ajax Namespace http://msdn.microsoft.com/en-us/library/system.web.mvc.ajax%28v=vs.118%29.aspx
System.Web.Mvc.Html Namespace http://msdn.microsoft.com/en-us/library/system.web.mvc.html%28v=vs.118%29.aspx
Understanding JavaScript Prototypes. http://javascriptweblog.wordpress.com/2010/06/07/understanding-javascript-prototypes/
Using the viewport meta tag to control layout on mobile browsers https://developer.mozilla.org/en-US/docs/Mozilla/Mobile/Viewport_meta_tag
ValidationExtensions.ValidationMessageFor Method http://msdn.microsoft.com/en-us/library/system.web.mvc.html.validationextensions.validationmessagefor%28v=vs.118%29.aspx
ValidationMessageFor HTML Helper in MVC3 Razor http://20fingers2brains.blogspot.com/2013/03/validationmessagefor-html-helper-in.html
Vendor-specific Properties http://reference.sitepoint.com/css/vendorspecific
Views and UI Rendering in ASP.NET MVC Applications http://msdn.microsoft.com/en-us/library/dd410123(v=vs.100).aspx
Develop User Experience – Search Engine Optimization, Globalization and Localization, Routes, Application Behaviour, Network Optimization
13 ASP.NET MVC extensibility points you have to know http://codeclimber.net.nz/archive/2009/04/08/13-asp.net-mvc-extensibility-points-you-have-to-know.aspx
Action Filtering in ASP.NET MVC Applications http://msdn.microsoft.com/en-us/library/dd410209%28v=vs.100%29.aspx
ActionResult Class http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult%28v=vs.118%29.aspx
ActionResult.ExecuteResult Method http://msdn.microsoft.com/en-us/library/system.web.mvc.actionresult.executeresult%28v=vs.118%29.aspx
An Introduction to ASP.NET MVC Extensibility https://www.simple-talk.com/dotnet/.net-framework/an-introduction-to-asp.net-mvc-extensibility/
ASP.NET Globalization and Localization http://msdn.microsoft.com/en-us/library/c6zyy3s9%28v=vs.100%29.aspx
ASP.NET MVC – Basic overview of different view engines http://www.codeproject.com/Articles/467850/ASP-NET-MVC-view-engines
ASP.NET MVC Custom Model Binder http://www.codeproject.com/Articles/605595/ASP-NET-MVC-Custom-Model-Binder
ASP.NET MVC Model Binding and Data Annotation http://www.codeproject.com/Articles/551576/ASP-NET-MVC-Model-Binding-and-Data-Annotation
ASP.NET MVC Routing Overview (C#) http://www.asp.net/mvc/tutorials/older-versions/controllers-and-routing/asp-net-mvc-routing-overview-cs
ASP.NET Routing http://msdn.microsoft.com/en-us/library/cc668201%28v%3Dvs.100%29.aspx
Attribute Usage Guidelines http://msdn.microsoft.com/en-us/library/vstudio/2ab31zeh%28v=vs.100%29.aspx
BindAttribute Class http://msdn.microsoft.com/en-us/library/system.web.mvc.bindattribute%28v=vs.118%29.aspx
Bundling and Minification http://www.asp.net/mvc/tutorials/mvc-4/bundling-and-minification
Configuring HTTP Compression in IIS 7 http://technet.microsoft.com/en-us/library/cc771003%28v=ws.10%29.aspx
CultureInfo Class http://msdn.microsoft.com/en-us/library/system.globalization.cultureinfo%28v=vs.110%29.aspx
Custom Controller Factory in ASP.NET MVC http://www.dotnetcurry.com/showarticle.aspx?ID=878
FilterAttribute Class http://msdn.microsoft.com/en-us/library/system.web.mvc.filterattribute%28v=vs.118%29.aspx
Globalize.js https://github.com/jquery/globalize
HandleErrorAttribute Class http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute%28v%3Dvs.108%29.aspx
How to: Set the Culture and UI Culture for ASP.NET Web Page Globalization http://msdn.microsoft.com/en-us/library/bz9tc508.aspx
HTML 5: The Markup Language (ARIA Edition) http://dev.w3.org/html5/markup/aria/aria.html
Mage.exe (Manifest Generation and Editing Tool) http://msdn.microsoft.com/en-us/library/acz3y3te.aspx
Microsoft Ajax Content Delivery Network http://www.asp.net/ajaxlibrary/cdn.ashx
MVC 4 Part 4 – Bundles and Optimisation http://johnnewcombe.net/blog/post/4
MvcRouteHandler and MvcHandler in ASP.NET MVC Framework http://www.codeproject.com/Articles/595520/MvcRouteHandler-and-MvcHandler-in-ASP-NET-MVC-Fram
ResourceManager Class http://msdn.microsoft.com/en-us/library/system.resources.resourcemanager%28v=vs.110%29.aspx
Search Engine Optimization Toolkit http://www.iis.net/downloads/microsoft/search-engine-optimization-toolkit
Subscriber Locale Codes http://msdn.microsoft.com/en-us/library/aa226765%28v%3Dsql.80%29.aspx
The Features and Foibles of ASP.NET MVC Model Binding http://msdn.microsoft.com/en-us/magazine/hh781022.aspx
Thread.CurrentUICulture Property http://msdn.microsoft.com/en-us/library/system.threading.thread.currentuiculture%28v=vs.110%29.aspx
Using CDN for Windows Azure http://www.windowsazure.com/en-us/documentation/articles/cdn-how-to-use/
Using Value Providers in ASP.NET 4.5 http://www.codeguru.com/csharp/.net/using-value-providers-in-asp.net-4.5.htm
Walkthrough: Organizing an ASP.NET MVC Application using Areas http://msdn.microsoft.com/en-us/library/ee671793%28v=vs.100%29.aspx
WebPart.AuthorizationFilter Property http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.webparts.webpart.authorizationfilter%28v=vs.110%29.aspx
What’s the Difference Between a Value Provider and Model Binder? http://haacked.com/archive/2011/06/30/whatrsquos-the-difference-between-a-value-provider-and-model-binder.aspx/
ViewResultBase Class http://msdn.microsoft.com/en-us/library/system.web.mvc.viewresultbase%28v=vs.118%29.aspx
VirtualPathProviderViewEngine Class http://msdn.microsoft.com/en-us/library/system.web.mvc.virtualpathproviderviewengine%28v=vs.118%29.aspx
Troubleshoot and debug web applications – Runtime issues, Exception handling, Testing, Debuging
AppDomain.FirstChanceException Event http://msdn.microsoft.com/en-us/library/system.appdomain.firstchanceexception%28v=vs.110%29.aspx
Assert Class http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.assert.aspx
Beginners Guide to Performance Profiling http://msdn.microsoft.com/en-us/library/ms182372.aspx
Code Contracts http://msdn.microsoft.com/en-us/library/dd264808%28v=vs.110%29.aspx
Code Contracts http://research.microsoft.com/en-us/projects/contracts/
Code Contracts for .NET http://visualstudiogallery.msdn.microsoft.com/1ec7db13-3363-46c9-851f-1ce455f66970
Collect Logging Data by Using Windows Azure Diagnostics http://msdn.microsoft.com/en-us/library/windowsazure/gg433048.aspx
Configuring Performance Sessions for Profiling Tools http://msdn.microsoft.com/en-us/library/ms182370.aspx
Configuring Windows Azure Diagnostics http://msdn.microsoft.com/en-us/library/windowsazure/dn186185.aspx
Controller.OnException Method http://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onexception%28v=vs.118%29.aspx
Create and Use Performance Counters in a Windows Azure Application http://msdn.microsoft.com/en-us/library/windowsazure/hh411542.aspx
customErrors Element (ASP.NET Settings Schema) http://msdn.microsoft.com/en-us/library/h0hfz6fc%28v=vs.85%29.aspx
Debugging a Cloud Service in Visual Studio http://msdn.microsoft.com/en-us/library/windowsazure/ff683670.aspx
Debugging Cloud Services http://msdn.microsoft.com/en-us/library/windowsazure/ee405479.aspx
HandleErrorAttribute Class http://msdn.microsoft.com/en-us/library/system.web.mvc.handleerrorattribute%28v=vs.118%29.aspx
How To Put Your Toe Into ASP.NET MVC Integration Testing http://orientman.wordpress.com/2013/12/06/how-to-put-your-toe-into-asp-net-mvc-integration-testing/
How to: Break When an Exception is Thrown http://msdn.microsoft.com/en-us/library/d14azbfh.aspx
How to: Handle Application-Level Errors http://msdn.microsoft.com/en-us/library/24395wz3%28v=vs.100%29.aspx
How to: Receive First-Chance Exception Notifications http://msdn.microsoft.com/en-us/library/dd997368%28v=vs.110%29.aspx
Integration Testing Your ASP.NET MVC Application http://blog.stevensanderson.com/2009/06/11/integration-testing-your-aspnet-mvc-application/
Invariants and Inheritance in Code Contracts http://msdn.microsoft.com/en-us/magazine/hh205755.aspx
Isolating Code Under Test with Microsoft Fakes http://msdn.microsoft.com/en-us/library/hh549175.aspx
Logging Error Details with ASP.NET Health Monitoring (C#) http://www.asp.net/web-forms/tutorials/deployment/deploying-web-site-projects/logging-error-details-with-asp-net-health-monitoring-cs
MVC: Error Page implementation https://thatsimpleidea.wordpress.com/tag/exception/
Performance and Diagnostics Hub in Visual Studio 2013 http://blogs.msdn.com/b/visualstudioalm/archive/2013/07/12/performance-and-diagnostics-hub-in-visual-studio-2013.aspx
Performance Profiler in Visual Studio 2012 http://sylvester-lee.blogspot.fi/2013/03/performance-profiler-in-visual-studio.html
Quick Start: Test Driven Development with Test Explorer http://msdn.microsoft.com/en-us/library/hh212233.aspx
Record and run a web performance test http://msdn.microsoft.com/en-us/library/ms182539.aspx
Remote Debugging a Window Azure Web Site with Visual Studio 2013 http://blogs.msdn.com/b/webdev/archive/2013/11/05/remote-debugging-a-window-azure-web-site-with-visual-studio-2013.aspx
System.Diagnostics.Contracts Namespace http://msdn.microsoft.com/en-us/library/system.diagnostics.contracts%28v=vs.110%29.aspx
TraceListener Class http://msdn.microsoft.com/en-us/library/system.diagnostics.tracelistener%28v=vs.110%29.aspx
Tracing in ASP.NET MVC Razor Views http://blogs.msdn.com/b/webdev/archive/2013/07/16/tracing-in-asp-net-mvc-razor-views.aspx
Understanding Web Tests http://msdn.microsoft.com/en-us/library/ms182537%28v=vs.90%29.aspx
Unit Testing in ASP.NET MVC Applications http://msdn.microsoft.com/en-us/library/ff936235%28v%3Dvs.100%29.aspx
Use the Windows Azure Diagnostics Configuration File http://msdn.microsoft.com/en-us/library/windowsazure/hh411551.aspx
Walkthrough: Using TDD with ASP.NET MVC http://msdn.microsoft.com/en-us/library/ff847525%28v=vs.100%29.aspx
What is a First Chance Exception? http://blogs.msdn.com/b/davidklinems/archive/2005/07/12/438061.aspx
Windows Performance Monitor http://technet.microsoft.com/en-us/library/cc749249.aspx
Working with Web Tests http://msdn.microsoft.com/en-us/library/ms182536%28v=vs.90%29.aspx
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 http://www.codeproject.com/Articles/578374/AplusBeginner-27splusTutorialplusonplusCustomplusF
A Custom SqlRoleProvider for “Authenticated Users” http://blogs.msdn.com/b/jjameson/archive/2010/12/09/a-custom-sqlroleprovider-for-quot-authenticated-users-quot.aspx
Anti-Cross Site Scripting Library http://msdn.microsoft.com/en-us/security/aa973814.aspx
Apple Secure Coding Guide https://developer.apple.com/library/ios/documentation/Security/Conceptual/SecureCodingGuide/SecureCodingGuide.pdf
ASP.NET Impersonation http://msdn.microsoft.com/en-us/library/aa292118%28v=vs.71%29.aspx
ASP.NET MVC Authentication – Global Authentication and Allow Anonymous http://weblogs.asp.net/jgalloway/archive/2012/04/18/asp-net-mvc-authentication-global-authentication-and-allow-anonymous.aspx
Asp.Net MVC With the ValidateAntiForgeryToken For Cross Site Request Forgeries http://patrickdesjardins.com/blog/asp-net-mvc-with-the-validateantiforgerytoken-for-cross-site-request-forgeries
ASP.NET Web Application Security http://msdn.microsoft.com/en-us/library/330a99hc%28v=vs.100%29.ASPX
Authenticating Users with Windows Authentication (C#) http://www.asp.net/mvc/tutorials/older-versions/security/authenticating-users-with-windows-authentication-cs
AuthorizeAttribute Class http://msdn.microsoft.com/en-us/library/system.web.mvc.authorizeattribute%28v=vs.118%29.aspx
Basic Security Practices for Web Applications http://msdn.microsoft.com/en-us/library/zdh19h94%28v=vs.100%29.aspx
Client Certificates vs. Server Certificates – What’s the Difference? http://www.symantec.com/connect/blogs/client-certificates-vs-server-certificates-what-s-difference
Configure ASP.NET Impersonation Authentication (IIS 7) http://technet.microsoft.com/en-us/library/cc730708%28v=ws.10%29.aspx
Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#) http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
CryptoStream Class http://msdn.microsoft.com/en-us/library/system.security.cryptography.cryptostream%28v=vs.110%29.aspx
Custom Authentication and Authorization in ASP.NET MVC http://www.dotnet-tricks.com/Tutorial/mvc/G54G220114-Custom-Authentication-and-Authorization-in-ASP.NET-MVC.html
Custom Authentication with MVC 3.0 http://www.bradygaster.com/post/custom-authentication-with-mvc-3.0
Custom Membership Providers http://www.codeproject.com/Articles/165159/Custom-Membership-Providers
Custom Membership Providers – Task Manager http://www.codeproject.com/Articles/176863/Custom-Membership-Providers-Task-Manager
Custom Role Providers http://www.codeproject.com/Articles/607392/Custom-Role-Providers
DpapiProtectedConfigurationProvider Class http://msdn.microsoft.com/en-us/library/system.configuration.dpapiprotectedconfigurationprovider%28v=vs.110%29.aspx
FormsIdentity Class http://msdn.microsoft.com/en-us/library/system.web.security.formsidentity%28v=vs.110%29.aspx
How to Authenticate Web Users with Windows Azure Active Directory Access Control http://www.windowsazure.com/en-us/documentation/articles/active-directory-dotnet-how-to-use-access-control/
How to configure Custom Membership and Role Provider using ASP.NET MVC4 http://logcorner.wordpress.com/2013/08/29/how-to-configure-custom-membership-and-role-provider-using-asp-net-mvc4/
How to Create an Intranet Site Using ASP.NET MVC http://msdn.microsoft.com/en-us/library/gg703322%28v=vs.98%29.aspx
How to: Create a WindowsPrincipal Object http://msdn.microsoft.com/en-us/library/t6547wf1%28v=vs.110%29.aspx
How to: Create GenericPrincipal and GenericIdentity Objects http://msdn.microsoft.com/en-us/library/y9dd5fx0%28v=vs.110%29.aspx
How To: Encrypt Configuration Sections in ASP.NET 2.0 Using RSA http://msdn.microsoft.com/en-us/library/ff650304.aspx
How To: Use Membership in ASP.NET 2.0 http://msdn.microsoft.com/en-us/library/ff648345.aspx
HtmlHelper.AntiForgeryToken Method http://msdn.microsoft.com/en-us/library/dd470175%28v=vs.118%29.aspx
HttpEncoder Class http://msdn.microsoft.com/en-us/library/system.web.util.httpencoder%28v=vs.100%29.ASPX
Microsoft Web Protection Library http://wpl.codeplex.com/
OAuthWebSecurity.Login Method http://msdn.microsoft.com/en-us/library/microsoft.web.webpages.oauth.oauthwebsecurity.login%28v=vs.111%29.aspx
OAuthWebSecurity.VerifyAuthentication Method http://msdn.microsoft.com/en-us/library/microsoft.web.webpages.oauth.oauthwebsecurity.verifyauthentication%28v=vs.111%29.aspx
patterns & practices Improving Web Services Security – Now Released http://wcfsecurityguide.codeplex.com/
Programming WCF Security http://msdn.microsoft.com/en-us/library/ms731925%28v=vs.110%29.aspx
Provider Model Design Pattern and Specification, Part 1 http://msdn.microsoft.com/en-us/library/ms972319.aspx
RequireHttpsAttribute Class http://msdn.microsoft.com/en-us/library/system.web.mvc.requirehttpsattribute%28v=vs.118%29.aspx
Role-Based Authorization (C#) http://www.asp.net/web-forms/tutorials/security/roles/role-based-authorization-cs
RSACryptoServiceProvider Class http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsacryptoserviceprovider%28v=vs.110%29.aspx
RsaProtectedConfigurationProvider Class http://msdn.microsoft.com/en-us/library/system.configuration.rsaprotectedconfigurationprovider%28v=vs.110%29.aspx
SAML 2.0 tokens and WIF – bridging the divide http://blogs.msdn.com/b/bradleycotier/archive/2012/10/28/saml-2-0-tokens-and-wif-bridging-the-divide.aspx
Securing Your ASP.NET Applications http://msdn.microsoft.com/en-us/magazine/hh708755.aspx
Security Practices: ASP.NET Security Practices at a Glance http://msdn.microsoft.com/en-us/library/ff650037.aspx
Seed Users and Roles with MVC 4, SimpleMembershipProvider, SimpleRoleProvider, Entity Framework 5 CodeFirst, and Custom User Properties http://blog.longle.net/2012/09/25/seeding-users-and-roles-with-mvc4-simplemembershipprovider-simpleroleprovider-ef5-codefirst-and-custom-user-properties/
SqlMembershipProvider Class http://msdn.microsoft.com/en-us/library/system.web.security.sqlmembershipprovider%28v=vs.110%29.aspx
SqlRoleProvider Class http://msdn.microsoft.com/en-us/library/system.web.security.sqlroleprovider%28v=vs.110%29.aspx
System.Security.Cryptography Namespace http://msdn.microsoft.com/en-us/library/system.security.cryptography%28v=vs.110%29.aspx
System.Threading.Thread.CurrentPrincipal vs. System.Web.HttpContext.Current.User or why FormsAuthentication can be subtle http://www.hanselman.com/blog/SystemThreadingThreadCurrentPrincipalVsSystemWebHttpContextCurrentUserOrWhyFormsAuthenticationCanBeSubtle.aspx
Thread.CurrentPrincipal Property http://msdn.microsoft.com/en-us/library/system.threading.thread.currentprincipal%28v=vs.110%29.aspx
Understanding and Using Simple Membership Provider in ASP.NET MVC 4.0 http://www.codeproject.com/Articles/689801/Understanding-and-Using-Simple-Membership-Provider
Understanding the Forms Authentication Ticket and Cookie http://support.microsoft.com/kb/910443
Understanding Windows Identity Foundation (WIF) 4.5 http://www.codeproject.com/Articles/504399/Understanding-Windows-Identity-Foundation-WIF-4-5
Using IIS Authentication with ASP.NET Impersonation http://msdn.microsoft.com/en-us/library/134ec8tc%28v=vs.100%29.aspx
Using OAuth Providers with MVC 4 http://www.asp.net/mvc/tutorials/security/using-oauth-providers-with-mvc
Walkthrough: Using Forms Authentication in ASP.NET MVC http://msdn.microsoft.com/en-us/library/ff398049%28v=vs.100%29.aspx
WCF Security Fundamentals http://msdn.microsoft.com/en-us/library/ff650862.aspx
WCF Using Windows Authentication and SqlRoleProvider over basicHttp http://randypaulo.wordpress.com/2011/07/13/wcf-using-windows-authentication-and-sqlroleprovider-over-basichttp/
WebSecurity Class http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity%28v%3Dvs.111%29
Windows Communication Foundation Security http://msdn.microsoft.com/en-us/library/ms732362%28v=vs.110%29.aspx
WindowsIdentity Class http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity%28v=vs.110%29.aspx
WS-Trust 1.3 OASIS Standard http://docs.oasis-open.org/ws-sx/ws-trust/200512/ws-trust-1.3-os.html

A great Security guide for veteran and new developers alike

Hi,

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

https://developer.apple.com/library/ios/documentation/Security/Conceptual/SecureCodingGuide/SecureCodingGuide.pdf

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

Hi,

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:
http://technet.microsoft.com/en-us/library/ee806890.aspx

Migrate from classic-mode to claims-based authentication in SharePoint 2013:
http://technet.microsoft.com/en-us/library/gg251985.aspx

Also for SQL Server Authentication if needed:

http://blogs.technet.com/b/ptsblog/archive/2013/09/20/configuring-sharepoint-2013-forms-based-authentication-with-sqlmembershipprovider.aspx

http://msdn.microsoft.com/en-us/library/gg252020(v=office.14).aspx

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:

https://www.nothingbutsharepoint.com/sites/devwiki/articles/pages/sharepoint-custom-sign-in-and-sign-out-page-.aspx

http://blogs.technet.com/b/speschka/archive/2010/07/22/writing-a-custom-forms-login-page-for-sharepoint-2010-part-2.aspx

http://tomaszrabinski.pl/wordpress/2011/06/23/sharepoint-2010-custom-login-page/

http://blogs.msdn.com/b/kaevans/archive/2010/07/09/creating-a-custom-login-page-for-sharepoint-2010.aspx

http://www.mssharepointtips.com/tip.asp?id=1093&page=2

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.

http://www.petri.co.il/delegate-permission-reset-ad-user-account-passwords.htm

http://support.microsoft.com/kb/296999

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.

http://social.technet.microsoft.com/wiki/contents/articles/20110.sharepoint-retrieving-credentials-from-the-secure-store-application-using-c.aspx

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

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)

http://msdn.microsoft.com/en-us/library/w070t6ka%28v=vs.110%29.aspx

http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#1

http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentry(v=vs.110).aspx

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

http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.authenticableprincipal.setpassword(v=vs.110).aspx

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);

            try

            {

                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.Cookies.Remove(CacheKey_LoginStatus);

                        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”))

                    {

                        context.Response.Redirect(intranetURL);

                    }

                }

            }

            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:

http://spautomaticsignin.codeplex.com/

Possible problem areas – Good to know:

Office documents:

Authentication requests when you open Office documents:
http://support.microsoft.com/kb/2019105
How documents are opened from a Web site in Office 2003:
http://support.microsoft.com/kb/838028

For Juniper VPNs:

[SSL VPN] Known Issues and limitations when accessing Microsoft SharePoint 2003 / 2007 / 2010 resources via the Web Rewrite Access mechanism:
http://kb.juniper.net/InfoCenter/index?page=content&id=KB11501

[SSL VPN] Supported features and functionality of SharePoint 2010 when accessed via Secure Access SSL VPN’s Web/Rewrite access method:
http://kb.juniper.net/InfoCenter/index?page=content&id=KB20085