aws-sdk-net-extensions-cognito: Cognito StartWithRefreshTokenAuthAsync incorrectly checks SessionTokens.ExpirationTime, fails with "User is not authenticated."
Expected Behavior
Invoking StartWithRefreshTokenAuthAsync on an instance of CognitoUser that had previously authenticated, but now has an expired access token should result in a new access token with an expiration date in the future.
Current Behavior
StartWithRefreshTokenAuthAsync throws the following exception:
Amazon.CognitoIdentityProvider.Model.NotAuthorizedException: User is not authenticated.
at Amazon.Extensions.CognitoAuthentication.CognitoUser.EnsureUserAuthenticated()
at Amazon.Extensions.CognitoAuthentication.CognitoUser.CreateRefreshTokenAuthRequest(AuthFlowType authFlowType)
at Amazon.Extensions.CognitoAuthentication.CognitoUser.<StartWithRefreshTokenAuthAsync>d__82.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
... ommitted for brevity
Possible Solution
My workaround right now is to manually assign the user’s SessionTokens to a new instance created with the existing tokens, but with an expiration time set in the future by an arbitrary amount seems to let it work around the check to see if the tokens are expired.
user.SessionTokens = new CognitoUserSession(
user.SessionTokens.IdToken,
user.SessionTokens.AccessToken,
user.SessionTokens.RefreshToken,
user.SessionTokens.IssuedTime,
DateTime.Now.AddHours(1)
);
var response = await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
{
AuthFlowType = AuthFlowType.REFRESH_TOKEN
});
A real solution is probably just to remove the call to EnsureUserAuthenticated from the top of CreateRefreshTokenAuthRequest in CognitoUserAuthentication.cs.
private InitiateAuthRequest CreateRefreshTokenAuthRequest(AuthFlowType authFlowType)
{
// This line is the one that I suggest be removed
EnsureUserAuthenticated();
if (authFlowType != AuthFlowType.REFRESH_TOKEN && authFlowType != AuthFlowType.REFRESH_TOKEN_AUTH)
{
throw new ArgumentException("authFlowType must be either \"REFRESH_TOKEN\" or \"REFRESH_TOKEN_AUTH\"", "authFlowType");
}
Steps to Reproduce (for bugs)
Authenticate a cognito user via some variant of the following:
AmazonCognitoIdentityProviderClient provider = new AmazonCognitoIdentityProviderClient(new AnonymousAWSCredentials(), RegionEndpoint.USEast2);
CognitoUserPool userPool = new CognitoUserPool(Constants.UserPoolId, Constants.ClientId, provider);
user = new Amazon.Extensions.CognitoAuthentication.CognitoUser(username, Constants.ClientId, userPool, provider);
await user.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
{
Password = password
});
Wait an hour for the access token to expire.
Attempt to refresh the user:
await user.StartWithRefreshTokenAuthAsync(new InitiateRefreshTokenAuthRequest
{
AuthFlowType = AuthFlowType.REFRESH_TOKEN
});
Observe that it throws:
Amazon.CognitoIdentityProvider.Model.NotAuthorizedException: User is not authenticated.
Context
I need a cognito user that is as long-lived as it would be on any other client (ex. our web client handles refreshes just fine, allowing multi-hour sessions). If I log in to the desktop client created using this library, and then just leave that client running for an hour all API calls start failing with 401s. Refreshing the user when that happens throws the aforementioned exception, rather than resulting in a valid cognito user with a new access token.
It’s worth pointing out that even with a solution to this problem (or a workaround related to messing with expiration time on the tokens object), I still run into another issue related to the refresh action clearing the refresh token instead of leaving it alone or updating it. This bug has already been mentioned, just worth pointing out that fixing this bug and that bug together are required for a real refresh system: https://github.com/aws/aws-sdk-net/issues/778
Your Environment
- AWSSDK.Core version used: 3.3.19.0
- Service assembly and version used:
- Operating System and version: Windows 10 1709 (OS Build 19299.192)
- Visual Studio version: Community 2017 15.5.4
- Targeted .NET platform: Core 2.1
.NET Core Info
- .NET Core version used for development: 2.1.4
- .NET Core version installed in the environment where application runs: 2.1.4
- Output of
dotnet --info:
.NET Command Line Tools (2.1.4)
Product Information:
Version: 2.1.4
Commit SHA-1 hash: 5e8add2190
Runtime Environment:
OS Name: Windows
OS Version: 10.0.16299
OS Platform: Windows
RID: win10-x64
Base Path: C:\Program Files\dotnet\sdk\2.1.4\
Microsoft .NET Core Shared Framework Host
Version : 2.0.5
Build : 17373eb129b3b05aa18ece963f8795d65ef8ea54
- Contents of project.json/project.csproj: project.json:
{
"dependencies": {
"AWSSDK.CognitoIdentity": "3.3.2.17",
"AWSSDK.CognitoIdentityProvider": "3.3.8",
"AWSSDK.Extensions.CognitoAuthentication": "0.9.1",
"Microsoft.NETCore.UniversalWindowsPlatform": "5.2.2",
"Microsoft.Toolkit.Uwp.Notifications": "2.1.0",
"NETStandard.Library": "2.0.1",
"Newtonsoft.Json": "10.0.3",
"QueryString.NET": "1.0.0",
"System.Net.Http": "4.3.3",
"System.Threading": "4.3.0",
"System.Threading.Tasks": "4.3.0",
"System.Threading.Timer": "4.3.0",
"Xamarin.Forms": "2.5.0.121934"
},
"frameworks": {
"uap10.0.16299": {}
},
"runtimes": {
"win10-arm": {},
"win10-arm-aot": {},
"win10-x86": {},
"win10-x86-aot": {},
"win10-x64": {},
"win10-x64-aot": {}
}
}
SDPNativeClient.UWP.csproj:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
<ProjectGuid>{FD00B0CC-4454-440C-9F0E-00BFC3E99032}</ProjectGuid>
<OutputType>AppContainerExe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>SDPNativeClient.UWP</RootNamespace>
<AssemblyName>SDPNativeClient.UWP</AssemblyName>
<DefaultLanguage>en-US</DefaultLanguage>
<TargetPlatformIdentifier>UAP</TargetPlatformIdentifier>
<TargetPlatformVersion>10.0.16299.0</TargetPlatformVersion>
<TargetPlatformMinVersion>10.0.16299.0</TargetPlatformMinVersion>
<MinimumVisualStudioVersion>14</MinimumVisualStudioVersion>
<EnableDotNetNativeCompatibleProfile>true</EnableDotNetNativeCompatibleProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{A5A43C5B-DE2A-4C0C-9213-0A381AF9435A};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<PackageCertificateKeyFile>impulse.pfx</PackageCertificateKeyFile>
<RuntimeIdentifiers>win10-arm;win10-arm-aot;win10-x86;win10-x86-aot;win10-x64;win10-x64-aot</RuntimeIdentifiers>
<AppxAutoIncrementPackageRevision>True</AppxAutoIncrementPackageRevision>
<AppxBundle>Always</AppxBundle>
<AppxBundlePlatforms>x64</AppxBundlePlatforms>
<PackageCertificateThumbprint>5B78E478072A4493A14DEF9F91A15E82DE7E1127</PackageCertificateThumbprint>
<AppxSymbolPackageEnabled>False</AppxSymbolPackageEnabled>
<AppxPackageDir>C:\Users\IEUser\Desktop\installables\</AppxPackageDir>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|ARM'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\ARM\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|ARM'">
<OutputPath>bin\ARM\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>ARM</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>false</UseDotNetNativeToolchain>
<Optimize>false</Optimize>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>false</UseDotNetNativeToolchain>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<NoWarn>;2008</NoWarn>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<Optimize>true</Optimize>
<NoWarn>;2008</NoWarn>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<UseVSHostingProcess>false</UseVSHostingProcess>
<ErrorReport>prompt</ErrorReport>
<Prefer32Bit>true</Prefer32Bit>
<UseDotNetNativeToolchain>true</UseDotNetNativeToolchain>
</PropertyGroup>
<ItemGroup>
<Compile Include="API\IPCService.cs" />
<Compile Include="Platform\VPNService.cs" />
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
</Compile>
<Compile Include="MainPage.xaml.cs">
<DependentUpon>MainPage.xaml</DependentUpon>
</Compile>
<Compile Include="OpenAppService.cs" />
<Compile Include="Platform\PlatformEffectUWP.cs" />
<Compile Include="Platform\PlatformReplaceAppTitle.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Toaster.cs" />
</ItemGroup>
<ItemGroup>
<AppxManifest Include="Package.appxmanifest">
<SubType>Designer</SubType>
</AppxManifest>
<None Include="impulse.pfx">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Include="project.json" />
<None Include="SDPNativeClient.UWP_TemporaryKey.pfx" />
</ItemGroup>
<ItemGroup>
<Content Include="app_icon.png" />
<Content Include="Assets\Square44x44Logo.targetsize-16.png" />
<Content Include="Assets\Square44x44Logo.targetsize-24.png" />
<Content Include="Assets\Square44x44Logo.targetsize-256.png" />
<Content Include="Assets\Square44x44Logo.targetsize-32.png" />
<Content Include="Assets\Square44x44Logo.targetsize-48.png" />
<Content Include="Bundle.Mapping.txt" />
<Content Include="libfko.arm.dll" />
<Content Include="libfko.x86.dll" />
<Content Include="libfko.x64.dll" />
<Content Include="menu_1.png" />
<Content Include="Properties\Default.rd.xml" />
<Content Include="Assets\LockScreenLogo.scale-100.png" />
<Content Include="Assets\LockScreenLogo.scale-125.png" />
<Content Include="Assets\LockScreenLogo.scale-150.png" />
<Content Include="Assets\LockScreenLogo.scale-200.png" />
<Content Include="Assets\LockScreenLogo.scale-400.png" />
<Content Include="Assets\SplashScreen.scale-100.png" />
<Content Include="Assets\SplashScreen.scale-125.png" />
<Content Include="Assets\SplashScreen.scale-150.png" />
<Content Include="Assets\SplashScreen.scale-200.png" />
<Content Include="Assets\SplashScreen.scale-400.png" />
<Content Include="Assets\Square150x150Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.scale-100.png" />
<Content Include="Assets\Square44x44Logo.scale-125.png" />
<Content Include="Assets\Square44x44Logo.scale-150.png" />
<Content Include="Assets\Square44x44Logo.scale-200.png" />
<Content Include="Assets\Square44x44Logo.scale-400.png" />
<Content Include="Assets\Square44x44Logo.targetsize-16_altform-unplated.png" />
<Content Include="Assets\Square44x44Logo.targetsize-24_altform-unplated.png" />
<Content Include="Assets\Square44x44Logo.targetsize-32_altform-unplated.png" />
<Content Include="Assets\Square44x44Logo.targetsize-48_altform-unplated.png" />
<Content Include="Assets\Square44x44Logo.targetsize-256_altform-unplated.png" />
<Content Include="Assets\StoreLogo.png" />
<Content Include="Assets\Wide310x150Logo.scale-100.png" />
<Content Include="Assets\Wide310x150Logo.scale-125.png" />
<Content Include="Assets\Wide310x150Logo.scale-150.png" />
<Content Include="Assets\Wide310x150Logo.scale-200.png" />
<Content Include="Assets\Wide310x150Logo.scale-400.png" />
<Content Include="WindowsFullTrustProcess.exe">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</Content>
<Content Include="refresh.png" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Page Include="MainPage.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AWSSDK.CognitoIdentity">
<Version>3.3.2.17</Version>
</PackageReference>
<PackageReference Include="AWSSDK.CognitoIdentityProvider">
<Version>3.3.8</Version>
</PackageReference>
<PackageReference Include="AWSSDK.Extensions.CognitoAuthentication">
<Version>0.9.1</Version>
</PackageReference>
<PackageReference Include="BouncyCastle">
<Version>1.8.1</Version>
</PackageReference>
<PackageReference Include="Fwknop">
<Version>1.0.1</Version>
</PackageReference>
<PackageReference Include="Microsoft.NETCore.UniversalWindowsPlatform">
<Version>6.0.6</Version>
</PackageReference>
<PackageReference Include="Microsoft.Toolkit.Uwp.Notifications">
<Version>2.1.1</Version>
</PackageReference>
<PackageReference Include="NETStandard.Library">
<Version>2.0.1</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>11.0.1-beta3</Version>
</PackageReference>
<PackageReference Include="QueryString.NET">
<Version>1.0.0</Version>
</PackageReference>
<PackageReference Include="Serilog">
<Version>2.6.1-dev-00938</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.Console">
<Version>3.1.1</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.Debug">
<Version>1.0.1-dev-00015</Version>
</PackageReference>
<PackageReference Include="Serilog.Sinks.File">
<Version>4.0.1-dev-00790</Version>
</PackageReference>
<PackageReference Include="System.Net.Http">
<Version>4.3.3</Version>
</PackageReference>
<PackageReference Include="System.Security.Cryptography.OpenSsl">
<Version>4.4.0</Version>
</PackageReference>
<PackageReference Include="System.Threading">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="System.Threading.Tasks">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="System.Threading.Timer">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="Xamarin.Forms">
<Version>2.5.0.122203</Version>
</PackageReference>
</ItemGroup>
<ItemGroup>
<SDKReference Include="WindowsDesktop, Version=10.0.16299.0">
<Name>Windows Desktop Extensions for the UWP</Name>
</SDKReference>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<PropertyGroup Condition=" '$(VisualStudioVersion)' == '' or '$(VisualStudioVersion)' < '14.0' ">
<VisualStudioVersion>14.0</VisualStudioVersion>
</PropertyGroup>
<Import Project="..\SDPNativeClient\SDPNativeClient.projitems" Label="Shared" Condition="Exists('..\SDPNativeClient\SDPNativeClient.projitems')" />
<Import Project="..\..\WindowsAppServiceIPC\WindowsAppServiceIPC.projitems" Label="Shared" />
<Import Project="..\..\WindowsFullTrustProcessShared\WindowsFullTrustProcessShared.projitems" Label="Shared" />
<Import Project="$(MSBuildExtensionsPath)\Microsoft\WindowsXaml\v$(VisualStudioVersion)\Microsoft.Windows.UI.Xaml.CSharp.targets" />
<PropertyGroup>
<PreBuildEvent>"$(msbuildbinpath)\msbuild.exe" $(SolutionPath) /t:WindowsFullTrustProcess:Rebuild</PreBuildEvent>
</PropertyGroup>
<PropertyGroup>
<PostBuildEvent>
</PostBuildEvent>
</PropertyGroup>
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">
</Target>
<Target Name="AfterBuild">
</Target>
-->
</Project>
About this issue
- Original URL
- State: closed
- Created 9 years ago
- Reactions: 3
- Comments: 31 (2 by maintainers)
This is living proof the AWS team loves the .NET SDK more than any other languages! Probably will be fixed in 3 years
The ‘expirationTime’ we pass in is literally compared to the current time before it even attempts to authenticate.
EnsureUserAuthenticated();is still a valid call to make in this function, we just need to be passing the expirationTime of the RefreshToken rather than the one for the 1 hour token.@ assyadh
Awesome!!! I took like more than a year !!!
Finger crossed for 2021
This is still a “bug”. I think the issue is that most people initiate the login and get the expiry for the access token. Then they try and use the same set of session tokens to refresh. The code is checking the expiry date and failing. The issue is that between authenticating and refreshing there are two different time frames, but only one is stored in the session tokens. So you have to provide your own new expiry time on the refresh that is valid so the SDK expiry validation passes. This usually isn’t an issue since that is usually a month so knowing the exact time table for that is not needed. Also considering a new refresh token is given then that almost always works and doesn’t require a login with password again.
@philipogorman I think in your previous comment you’ve also figured out the design behind it however you’re still using the
DateTime.Now.AddHours(1)work around. This work around means you will always refresh the user’s token. At the point in which you authenticate the user, you should store a property with a name likeRefreshTokenExpirationTimeand set this anywhere between an hour to 30 days from that moment you authenticate them. ThisRefreshTokenExpirationTimewill dictate how long they have before their refresh token expires. I’ve always set mine to 25 days from the moment they are authenticated, which means if they keep logging in within 25 days they will always remained signed in – they will be authenticated again and their refresh token will have a new expiration time. However if they login again 26 days since their last sign in then they will need to sign in again.Using
DateTime.Now.AddHours(1)will work because cognito will always try to refresh their user’s token. It’s essentially a force refresh. However it will not work in this situation: If the user has signed in and then leaves and doesn’t come back to the app for over 30 days. (At this point the actual refresh token has expired, unless you have changed the expiration time of your refresh tokens) Your code ofDateTime.Now.AddHours(1)will try to force refreshing the token again which will fail due to an expired refresh token. Your app may or may not handle this gracefully but it certainly isn’t the behaviour you want.@NGL321 I’m not sure if my comments have made sense, people don’t seem to understand it. I don’t think theres anything wrong with the code here per se but argument name is very misleading and there should be proper instructions on how to use it.
Here is the code we use to refresh: `
`
Hi everyone,
I’ll have a look at this shortly and will narrow down the issue.
H
Yeah, After a few months of having this Issue I think I know why it hasn’t been fixed yet. It seems as though it was intended to work this way but the issue comes with a badly named parameter.
The reason DateTime.Now.AddHours(1) works is because that is doing the check against expiration time. I’m guessing we’ve all written something to check if the users 30 days are over before even getting to this function call so we will never make the call to refresh the token if their refresh token should be expired anyway.
public CognitoUserSession(string idToken, string accessToken, string refreshToken, DateTime issuedTime, DateTime expirationTime);We’re passing expirationTime as the token expiration time. However when refreshing the token, I think this should be passing in the Expiration Time of the RefreshToken.
I’ve changed this
into this
My RefreshTokenExpiresServer is set to be 25 days from when the user gets authenticated. This is what I think is the issue here is anyway. @jeffreythomasprice @sstevenkang @curtisshipley
This has fixed the issue for me.
@jeffreythomasprice I have the same issue, using DateTime.Now.AddHours(1)) seems to work-around the issue. But I also think this is a bug.
@jeffreythomasprice The trick was not really you adding expiration variable, it was the refresh token!
It was the user.SessionToken.RefreshToken you assigned to the session object that fixed your problem. The whole refresh token auth flow would not work if you don’t even provide the refresh token. Remember the
InitiateRefreshTokenAuthRequestobject only hasAuthFlowType, nothing else. I think it might be better to putRefreshTokeninto theInitiateRefreshTokenAuthRequestso we don’t need to create a dummy session object just to hold the refresh token.