Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auth changes #4218

Merged
merged 3 commits into from
Apr 13, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@

Function Update-AADApplicationWithCertificate
{
#SPN: PsAutoTestADAppUsingSPN
#AppType: Web app/Api

#AppId: b8a1058e-25e8-4b08-b40b-d8d871dda591
#ObjectId: 676e21d1-cd49-41d7-9eb3-b8fd76ba7e67

#HomePage: http://www.PsAutoTestADAppUsingSPN.com
#AppId Uri: http://PsAutoTestADAppUsingSPN

$localCert = Get-CertFromLocalStore

$rawCertData = $localCert.GetRawCertData()

$binaryAsciiCertData = [System.Convert]::ToBase64String($rawCertData)

$startDate = Get-Date
$endDate = [DateTime]::Parse($localCert.GetExpirationDateString())

#AD app does not exists, create one
#$psAutoADApp = New-AzureRmADApplication -DisplayName "PsAutoTestADAppUsingSPN" -HomePage "http://www.PsAutoTestADAppUsingSPN.com" -IdentifierUris "http://www.PsAutoTestADAppUsingSPN.com" -CertValue $binaryAsciiCertData -StartDate $startDate -EndDate $endDate
$psAutoADApp = New-AzureRmADApplication -DisplayName "PsAutoTestADAppUsingSPN" -HomePage "http://www.PsAutoTestADAppUsingSPN.com" -IdentifierUris "http://www.PsAutoTestADAppUsingSPN1.com" -CertValue $binaryAsciiCertData -StartDate $startDate -EndDate $endDate
Log-Info "Updated SPN with local cert"
}

Function Install-TestCertificateOnMachine([string] $localCertPath)
{
$certSubject = "CN=TestCertForAuthLib"
$certLocation = "cert:\CurrentUser\My"

$cert = Get-CertFromLocalStore

if($cert -eq $null)
{
Log-Info "Creating/Installing new certificate"

#
$cert = New-SelfSignedCertificate -CertStoreLocation $certLocation -Subject $certSubject -KeyExportPolicy Exportable -NotAfter (Get-Date).AddYears(1) -Type CodeSigningCert -KeySpec Signature
#$cert = New-SelfSignedCertificate -DnsName "PsAutoTestADAppUsingSPN" -CertStoreLocation $certLocation -KeyExportPolicy Exportable -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider"
#$cert = New-SelfSignedCertificate -Subject $certSubject -CertStoreLocation $certLocation


if($cert -eq $null)
{
$cert = Get-LocalCertifcate
}
}

$certPwdProtectedInBytes = $cert.Export([System.Security.Cryptography.X509Certificates.X509ContentType]::Pkcs12)
$pfxLocalFilePath = "SpnAuthTest.cer"
[System.IO.File]::WriteAllBytes($pfxLocalFilePath, $certPwdProtectedInBytes)

return $cert
}


Function Get-CertFromLocalStore([string] $certSubject = "CN=TestCertForAuthLib")
{
#TODO: Handle case whgere we get multiple test certificates with exactly the same subject
$cert = Get-ChildItem "cert:\CurrentUser\My" | Where-Object {$_.Subject -eq $certSubject}
if($cert -eq $null)
{
Log-Info "Trying to find certificate in LocalMachine"
$cert = Get-ChildItem 'Cert:\LocalMachine\My' | Where-Object {$_.Subject -eq $certSubject}
}

if($cert -eq $null)
{
Log-Info "Unable to find locally installed certificate with subject $certSubject"
}
else
{
Log-Info "Retrieved locally installed certificate with subject $certSubject"
}

return $cert
}

Function Delete-LocalCertificate([bool]$deleteLocalCertificate)
{
$cert = Get-CertFromLocalStore
if($cert -ne $null -and $deleteLocalCertificate -eq $true)
{
$certPath = $cert.PSPath
Log-Info "Deleting local certificate $certPath"
Remove-Item $cert.PSPath
}
}

Function Login-InteractivelyAndSelectTestSubscription()
{
Log-Info "Logging interactively....."
$global:gLoggedInCtx = Login-AzureRmAccount
Log-Info "Selecting '$global:gPsAutoTestSubscriptionId' subscription"
$global:gLoggedInCtx = Select-AzureRmSubscription -SubscriptionId $global:gPsAutoTestSubscriptionId

return $global:gLoggedInCtx
}

Function Log-Info([string] $info)
{
$info = [string]::Format("[INFO]: {0}", $info)
Write-Host $info -ForegroundColor Yellow
}

Function Log-Error([string] $errorInfo)
{
$errorInfo = [string]::Format("[INFO]: {0}", $errorInfo)
Write-Error -Message $errorInfo
}

#Delete-LocalCertificate $true
Install-TestCertificateOnMachine
#Update-AADApplicationWithCertificate
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="packages\xunit.runner.visualstudio.2.3.1\build\net20\xunit.runner.visualstudio.props" Condition="Exists('packages\xunit.runner.visualstudio.2.3.1\build\net20\xunit.runner.visualstudio.props')" />
<Import Project="packages\xunit.core.2.3.1\build\xunit.core.props" Condition="Exists('packages\xunit.core.2.3.1\build\xunit.core.props')" />
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{ACACDA67-5693-40B4-BA2B-6099A38C1562}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>Az.Auth.Net452.Test</RootNamespace>
<AssemblyName>Az.Auth.Net452.Test</AssemblyName>
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<TargetFrameworkProfile />
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory, Version=2.28.3.860, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.IdentityModel.Clients.ActiveDirectory.2.28.3\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll</HintPath>
</Reference>
<Reference Include="Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms, Version=2.28.3.860, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.IdentityModel.Clients.ActiveDirectory.2.28.3\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Rest.ClientRuntime, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>packages\Microsoft.Rest.ClientRuntime.2.3.11\lib\net452\Microsoft.Rest.ClientRuntime.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
<Reference Include="xunit.abstractions, Version=2.0.0.0, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>packages\xunit.abstractions.2.0.1\lib\net35\xunit.abstractions.dll</HintPath>
</Reference>
<Reference Include="xunit.assert, Version=2.3.1.3858, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>packages\xunit.assert.2.3.1\lib\netstandard1.1\xunit.assert.dll</HintPath>
</Reference>
<Reference Include="xunit.core, Version=2.3.1.3858, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>packages\xunit.extensibility.core.2.3.1\lib\netstandard1.1\xunit.core.dll</HintPath>
</Reference>
<Reference Include="xunit.execution.desktop, Version=2.3.1.3858, Culture=neutral, PublicKeyToken=8d05b1bb7a6fdb6c, processorArchitecture=MSIL">
<HintPath>packages\xunit.extensibility.execution.2.3.1\lib\net452\xunit.execution.desktop.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="CertAuthTests.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="TestBase.cs" />
<Compile Include="TestFxFiles\ConnectionString.cs" />
<Compile Include="TestFxFiles\ConnectionStringKeys.cs" />
<Compile Include="TestFxFiles\ExtMethod.cs" />
<Compile Include="TestFxFiles\TestEndpoints.cs" />
<Compile Include="UserLogin.cs" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Analyzer Include="packages\xunit.analyzers.0.7.0\analyzers\dotnet\cs\xunit.analyzers.dll" />
</ItemGroup>
<ItemGroup>
<Service Include="{82A7F48D-3B50-4B1E-B82E-3ADA8210C358}" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Az.Authentication\Microsoft.Rest.ClientRuntime.Azure.Authentication.csproj">
<Project>{037ffb80-b6dd-4de9-9065-c72415737cb5}</Project>
<Name>Microsoft.Rest.ClientRuntime.Azure.Authentication</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\xunit.core.2.3.1\build\xunit.core.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\xunit.core.2.3.1\build\xunit.core.props'))" />
<Error Condition="!Exists('packages\xunit.core.2.3.1\build\xunit.core.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\xunit.core.2.3.1\build\xunit.core.targets'))" />
<Error Condition="!Exists('packages\xunit.runner.visualstudio.2.3.1\build\net20\xunit.runner.visualstudio.props')" Text="$([System.String]::Format('$(ErrorText)', 'packages\xunit.runner.visualstudio.2.3.1\build\net20\xunit.runner.visualstudio.props'))" />
</Target>
<Import Project="packages\xunit.core.2.3.1\build\xunit.core.targets" Condition="Exists('packages\xunit.core.2.3.1\build\xunit.core.targets')" />
</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26430.4
MinimumVisualStudioVersion = 10.0.40219.1
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Rest.ClientRuntime.Azure.Authentication", "..\..\Az.Authentication\Microsoft.Rest.ClientRuntime.Azure.Authentication.csproj", "{037FFB80-B6DD-4DE9-9065-C72415737CB5}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tests", "Tests", "{8F33762A-0CEF-4675-9CE6-0CD164715D6B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Az.Auth.Net452.Test", "Az.Auth.Net452.Test.csproj", "{ACACDA67-5693-40B4-BA2B-6099A38C1562}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{037FFB80-B6DD-4DE9-9065-C72415737CB5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{037FFB80-B6DD-4DE9-9065-C72415737CB5}.Debug|Any CPU.Build.0 = Debug|Any CPU
{037FFB80-B6DD-4DE9-9065-C72415737CB5}.Release|Any CPU.ActiveCfg = Release|Any CPU
{037FFB80-B6DD-4DE9-9065-C72415737CB5}.Release|Any CPU.Build.0 = Release|Any CPU
{ACACDA67-5693-40B4-BA2B-6099A38C1562}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{ACACDA67-5693-40B4-BA2B-6099A38C1562}.Debug|Any CPU.Build.0 = Debug|Any CPU
{ACACDA67-5693-40B4-BA2B-6099A38C1562}.Release|Any CPU.ActiveCfg = Release|Any CPU
{ACACDA67-5693-40B4-BA2B-6099A38C1562}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{ACACDA67-5693-40B4-BA2B-6099A38C1562} = {8F33762A-0CEF-4675-9CE6-0CD164715D6B}
EndGlobalSection
EndGlobal
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
using Microsoft.Rest.Azure.Authentication;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using Xunit;

namespace Az.Auth.Net452.Test
{
public class CertAuthTests : TestBase
{
public CertAuthTests()
{

}


[Theory(Skip = "Interactive tests")]
[InlineData("AADTenant=dcfa120f-9293-4f06-b3d2-cf728bcabb10;" +
"ServicePrincipal=b8a1058e-25e8-4b08-b40b-d8d871dda591;" +
"SubscriptionId=2c224e7e-3ef5-431d-a57b-e71f4662e3a6;" +
"CertSubject=TestCertForAuthLib;" +
"Environment=Prod;"
)]
public void CertAuthWithSPN(string cnnStr)
{
LiteralCnnString = cnnStr;
ServiceClientCredentials svcClientCred = null;

X509Certificate2 localCert = null;
X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
try
{
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certCol = store.Certificates;
X509Certificate2Collection certsWithSubject = certCol.Find(X509FindType.FindBySubjectName, "TestCertForAuthLib", false);
localCert = certsWithSubject[0];
}
finally
{
store.Close();
}

ActiveDirectoryServiceSettings aadServiceSettings = new ActiveDirectoryServiceSettings()
{
AuthenticationEndpoint = new Uri(CloudEndPoints.AADAuthUri.ToString() + TenantId),
TokenAudience = CloudEndPoints.AADTokenAudienceUri
};

ClientAssertionCertificate certAssertion = new ClientAssertionCertificate(ClientId, localCert);

svcClientCred = ApplicationTokenProvider.LoginSilentWithCertificateAsync(TenantId, certAssertion, aadServiceSettings).GetAwaiter().GetResult();
Assert.NotNull(svcClientCred);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;

// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Az.Auth.Net452.Test")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Az.Auth.Net452.Test")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]

// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("6d479159-5a21-4559-b8d4-7480fc62d393")]

// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
Loading