Pages

Showing posts with label Visual Studio. Show all posts
Showing posts with label Visual Studio. Show all posts

Tuesday, January 8, 2013

Claims Based Authentication - Setting up Visual Studio 2012 on Localhost to use ADFS

So currently I'm  learning Windows Identity Foundation to do Claims Based Authentication. I'm working an a few posts on the subject and i'll be posting them soon. For now this one focuses on the my need to configure my Visual Studio environment to use my domain ADFS server as a STS. Now I know i can setup a local STS project for testing but I wanted to use our domain ADFS so that everything as close as possible to production configuration as I could for testing.

Turns out this isn’t hard to do but a few configuration steps that are easy to miss. Since I didn't find any guides or posts on how to do this I figured I’d share mine.

Overview

The end result will be a ADFS relaying service provider that will expect inbound connection from https://localhost and a Visual studio configuration set to use IIS, rather than IIS express, hosting the VS Project. What's really interesting is that since i configured this to use https://localhost any developer can use the the same relaying party for their testing rather than creating a Replaying Party Entry in ADFS for every developer machine. Also because the links will only work from the localhost you don’t need to worry about them deploying projects using that Replying Party entry because it won’t work.

Solution

There are two sides of this setup. First I’ll cover the settings I configured on the ADFS with a relaying relaying party and this those of the client machine running Visual studio.

ADFS Configuration

From the ADFS server navigate to the Relying Party Trusts and add a new Relaying Party Trust. We need to supply a FederationMetadata.xml file. I modified this one for our use. Create a text file and copy the contents to it and save it as “Localhost_FederationMetadata.xml”

Localhost_FederationMetadata.xml

<?xml version="1.0" encoding="utf-8"?>
<EntityDescriptor ID="_3d1176b1-236d-4675-8970-674b061daf17" 
                entityID="https://localhost/"
                xmlns="urn:oasis:names:tc:SAML:2.0:metadata">
    <RoleDescriptor xsi:type="fed:ApplicationServiceType" 
                xmlns:fed="http://docs.oasis-open.org/wsfed/federation/200706"
                protocolSupportEnumeration="http://docs.oasis-open.org/wsfed/federation/200706"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
        <fed:TargetScopes><wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
            <wsa:Address>https://localhost/</wsa:Address></wsa:EndpointReference>
        </fed:TargetScopes>
        <fed:PassiveRequestorEndpoint>
            <wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
                <wsa:Address>https://localhost/</wsa:Address>
            </wsa:EndpointReference>
        </fed:PassiveRequestorEndpoint>
    </RoleDescriptor>
</EntityDescriptor>

With the file created Choose “Import data about the relying party from a file”.

clip_image002


Monday, April 25, 2011

ASP.NET Forms Based Authentication with Active Directory

If you've ever used Visual Studio's 2010 the default template for an ASP.NET Web Site is a really nice. It allows you to give users accounts based on SQL accounts it creates. I however wanted to use Active  Directory instead of SQL and do the user authentication there instead of setting it on the entire IIS site. This also allows you to have a much prettier login page rather than the normal web browser's "basic access authentication" prompt.

I figured that changing the ASP 4.0 WebSite to use Active Directory would be be a GUI wizard to do it but found a large amount of confusion on the subject when I was researching how. After Figuring it out for myself I figured I'd write a guide on how.

Setup your machine
Serveral of the problems I observed were people had problems with their website and Visual Studio install before they even started with change the website to use AD. Start by creating a WebSite from the "ASP.NET Web Site" using .Net Framework 4. Don't make a single change and build and run the project. Does the site come up. Can you register a user account and then login to that user account. If not don't proceed any further till you can.

The cause for this for many people was that the website went to use the SQLEXPRESS instance only to find that it wasn't installed or running. As a result you'll get the following error from IIS.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

Changing the Template to use Active Directory
Nearly everything nessory is done in the web sites root web.config file. Below is a copy of the complete file.

  • Add connectionStrings "ADService" to domain your going to use. example "LDAP://nku.edu" (note i tried to alter this to use )
  • Notice that we remove the AspNetSqlMembershipProvider and added AspNetActiveDirectoryMembershipProvider. 
  • Making sure to set AspNetActiveDirectoryMembershipProvider as the default membership provider.
  • Setting attributeMapUsername to sAMAccountName 


<?xml version="1.0"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
 <connectionStrings>
  <add name="ADService" connectionString="LDAP://Domainname.com"/> 
  <add name="ApplicationServices" 
         connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true" 
         providerName="System.Data.SqlClient"/>
 </connectionStrings>
 <system.web>
  <compilation debug="true" targetFramework="4.0">
   <assemblies>
    <add assembly="stdole, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/>
      </assemblies>
    </compilation>
  <authentication mode="Forms">
   <forms loginUrl="~/Account/Login.aspx" timeout="2880"/>
  </authentication>
  <membership defaultProvider="AspNetActiveDirectoryMembershipProvider">
   <providers>
    <clear/>
    <!-- <add name="AspNetSqlMembershipProvider" 
             type="System.Web.Security.SqlMembershipProvider" 
             connectionStringName="ApplicationServices" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="/"/> -->
    <add name="AspNetActiveDirectoryMembershipProvider"
             type="System.Web.Security.ActiveDirectoryMembershipProvider,  System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" 
             connectionStringName="ADService" 
             attributeMapUsername="sAMAccountName"/>
   </providers>
  </membership>
  <profile>
   <providers>
    <clear/>
    <add name="AspNetSqlProfileProvider" 
             type="System.Web.Profile.SqlProfileProvider"
             connectionStringName="ApplicationServices"
             applicationName="/"/>
   </providers>
  </profile>
  <roleManager enabled="false">
   <providers>
    <clear/>
    <add name="AspNetSqlRoleProvider" 
             type="System.Web.Security.SqlRoleProvider" 
             connectionStringName="ApplicationServices"
             applicationName="/"/>
    <add name="AspNetWindowsTokenRoleProvider"
             type="System.Web.Security.WindowsTokenRoleProvider"
             applicationName="/"/>
   </providers>
  </roleManager>
 </system.web>
 <system.webServer>
  <modules runAllManagedModulesForAllRequests="true"/>
 </system.webServer>
</configuration>



We also want to create content where the user has to be authenticated to view. Create a new folder to the project. , i called mine "Content". Then add a new item to the folder, selecting "web config". Alter the new web.config to match below.

<configuration>
    <system.web>
      <authorization>
        <!-- deny = ? means deny unauthenticated users -->
        <deny users="?"/>
      </authorization>
    </system.web>
</configuration>

This means that any content inside this folder requires the users first be authenticated before they can access. Any link to this content will first prompt an unauthenticated user to login and then be redirected to the linked content.


Cleanup
There were a several pages and links we can remove as the aren't used since we are using AD to authenticate via forms based authentication. You could comment them out if you ever want to switch back to SQL based users.
  • Remove the "Register User" hyperLink from Login.aspx and delete the Register.aspx file.
  • Change the Site.Master using   we change the tabs users can see depending on if they are logged in or not.
Source
I've included a Visual Studio 2010 Project using Framework 4 that may be useful to view how it works and the changes I made.

Download  - Web Site Using AD Forms Based Authentication

Pictures showing the user Login


Anonymous User Viewing the Site

User accessing Login Page or Content that requires Login
Authenticated User Viewing Site

Links
http://stackoverflow.com/questions/895002/asp-net-active-directory-membership-provider-and-sql-profile-provider/5779884#5779884
http://www.howtodothings.com/computers/a792-aspnet-forms-authentication-with-roles.html
http://msdn.microsoft.com/en-us/library/ff648341.aspx#paght000012_step1