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 provider cleanup #6

Open
wants to merge 20 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
5e742d7
Enabling NuGet package restore
2ooom Oct 24, 2014
416216f
Enabling NuGet package restore
2ooom Oct 24, 2014
b2619d1
Enabling local database
2ooom Oct 24, 2014
9e69f00
Making clients updatable via Seed method in Entity migrations
2ooom Oct 24, 2014
dc6958c
Minor coding styles corrections
2ooom Oct 24, 2014
dd7e3da
Cleaning up SimpleAuthorizationServerProvider code styles + Additiona…
2ooom Oct 24, 2014
9cd59fe
context.ClientId is populated inderectly from clientId which makes re…
2ooom Oct 24, 2014
7719e33
Factoring out AuthenticationTicket issuing logic
2ooom Oct 27, 2014
b56f31f
Replacing Access Token persistence with AuthenticationTicketProvider …
2ooom Oct 27, 2014
dd13132
Moving client_id and username checks from AuthorizationServerProvider…
2ooom Oct 27, 2014
edd4e60
Introducing constants for Owin context keys
2ooom Oct 27, 2014
5ac4e90
Adding UserAgent column to refresh column to allow multi browser sess…
2ooom Oct 27, 2014
cb3284c
RefreshTokenProvider making calls syncronous. + minor usaing cleanup
2ooom Oct 27, 2014
6872da9
RefreshTokenProvider making calls syncronous. + minor usages cleanup
2ooom Oct 27, 2014
f439975
Factoring out AllowedOrigin logic to Owin.Cors middleware
2ooom Oct 28, 2014
9dcd4b7
Merge branch 'AuthProvider-cleanup' of https://github.com/2ooom/Angul…
2ooom Oct 28, 2014
abc2f6e
Fixing refresh token behaviour by storing clinetId in context
2ooom Oct 28, 2014
8810f7b
Fixing NullReferenceException in CorsPolicyProvider for non-Cors requ…
2ooom Oct 28, 2014
c39a3ea
Fifxing bug. Allowing Cors for non-token requests
2ooom Oct 28, 2014
6c80cff
Enabling simultaneous seesion from different umachines/useragents for…
2ooom Oct 28, 2014
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
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ publish/

# NuGet Packages Directory
## TODO: If you have NuGet Package Restore enabled, uncomment the next line
#packages/
packages/

# Windows Azure Build Output
csx
Expand Down
6 changes: 6 additions & 0 deletions .nuget/NuGet.Config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<solution>
<add key="disableSourceControlIntegration" value="true" />
</solution>
</configuration>
Binary file added .nuget/NuGet.exe
Binary file not shown.
144 changes: 144 additions & 0 deletions .nuget/NuGet.targets
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">$(MSBuildProjectDirectory)\..\</SolutionDir>

<!-- Enable the restore command to run before builds -->
<RestorePackages Condition=" '$(RestorePackages)' == '' ">false</RestorePackages>

<!-- Property that enables building a package from a project -->
<BuildPackage Condition=" '$(BuildPackage)' == '' ">false</BuildPackage>

<!-- Determines if package restore consent is required to restore packages -->
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>

<!-- Download NuGet.exe if it does not already exist -->
<DownloadNuGetExe Condition=" '$(DownloadNuGetExe)' == '' ">false</DownloadNuGetExe>
</PropertyGroup>

<ItemGroup Condition=" '$(PackageSources)' == '' ">
<!-- Package sources used to restore packages. By default, registered sources under %APPDATA%\NuGet\NuGet.Config will be used -->
<!-- The official NuGet package source (https://www.nuget.org/api/v2/) will be excluded if package sources are specified and it does not appear in the list -->
<!--
<PackageSource Include="https://www.nuget.org/api/v2/" />
<PackageSource Include="https://my-nuget-source/nuget/" />
-->
</ItemGroup>

<PropertyGroup Condition=" '$(OS)' == 'Windows_NT'">
<!-- Windows specific commands -->
<NuGetToolsPath>$([System.IO.Path]::Combine($(SolutionDir), ".nuget"))</NuGetToolsPath>
</PropertyGroup>

<PropertyGroup Condition=" '$(OS)' != 'Windows_NT'">
<!-- We need to launch nuget.exe with the mono command if we're not on windows -->
<NuGetToolsPath>$(SolutionDir).nuget</NuGetToolsPath>
</PropertyGroup>

<PropertyGroup>
<PackagesProjectConfig Condition=" '$(OS)' == 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName.Replace(' ', '_')).config</PackagesProjectConfig>
<PackagesProjectConfig Condition=" '$(OS)' != 'Windows_NT'">$(MSBuildProjectDirectory)\packages.$(MSBuildProjectName).config</PackagesProjectConfig>
</PropertyGroup>

<PropertyGroup>
<PackagesConfig Condition="Exists('$(MSBuildProjectDirectory)\packages.config')">$(MSBuildProjectDirectory)\packages.config</PackagesConfig>
<PackagesConfig Condition="Exists('$(PackagesProjectConfig)')">$(PackagesProjectConfig)</PackagesConfig>
</PropertyGroup>

<PropertyGroup>
<!-- NuGet command -->
<NuGetExePath Condition=" '$(NuGetExePath)' == '' ">$(NuGetToolsPath)\NuGet.exe</NuGetExePath>
<PackageSources Condition=" $(PackageSources) == '' ">@(PackageSource)</PackageSources>

<NuGetCommand Condition=" '$(OS)' == 'Windows_NT'">"$(NuGetExePath)"</NuGetCommand>
<NuGetCommand Condition=" '$(OS)' != 'Windows_NT' ">mono --runtime=v4.0.30319 "$(NuGetExePath)"</NuGetCommand>

<PackageOutputDir Condition="$(PackageOutputDir) == ''">$(TargetDir.Trim('\\'))</PackageOutputDir>

<RequireConsentSwitch Condition=" $(RequireRestoreConsent) == 'true' ">-RequireConsent</RequireConsentSwitch>
<NonInteractiveSwitch Condition=" '$(VisualStudioVersion)' != '' AND '$(OS)' == 'Windows_NT' ">-NonInteractive</NonInteractiveSwitch>

<PaddedSolutionDir Condition=" '$(OS)' == 'Windows_NT'">"$(SolutionDir) "</PaddedSolutionDir>
<PaddedSolutionDir Condition=" '$(OS)' != 'Windows_NT' ">"$(SolutionDir)"</PaddedSolutionDir>

<!-- Commands -->
<RestoreCommand>$(NuGetCommand) install "$(PackagesConfig)" -source "$(PackageSources)" $(NonInteractiveSwitch) $(RequireConsentSwitch) -solutionDir $(PaddedSolutionDir)</RestoreCommand>
<BuildCommand>$(NuGetCommand) pack "$(ProjectPath)" -Properties "Configuration=$(Configuration);Platform=$(Platform)" $(NonInteractiveSwitch) -OutputDirectory "$(PackageOutputDir)" -symbols</BuildCommand>

<!-- We need to ensure packages are restored prior to assembly resolve -->
<BuildDependsOn Condition="$(RestorePackages) == 'true'">
RestorePackages;
$(BuildDependsOn);
</BuildDependsOn>

<!-- Make the build depend on restore packages -->
<BuildDependsOn Condition="$(BuildPackage) == 'true'">
$(BuildDependsOn);
BuildPackage;
</BuildDependsOn>
</PropertyGroup>

<Target Name="CheckPrerequisites">
<!-- Raise an error if we're unable to locate nuget.exe -->
<Error Condition="'$(DownloadNuGetExe)' != 'true' AND !Exists('$(NuGetExePath)')" Text="Unable to locate '$(NuGetExePath)'" />
<!--
Take advantage of MsBuild's build dependency tracking to make sure that we only ever download nuget.exe once.
This effectively acts as a lock that makes sure that the download operation will only happen once and all
parallel builds will have to wait for it to complete.
-->
<MsBuild Targets="_DownloadNuGet" Projects="$(MSBuildThisFileFullPath)" Properties="Configuration=NOT_IMPORTANT;DownloadNuGetExe=$(DownloadNuGetExe)" />
</Target>

<Target Name="_DownloadNuGet">
<DownloadNuGet OutputFilename="$(NuGetExePath)" Condition=" '$(DownloadNuGetExe)' == 'true' AND !Exists('$(NuGetExePath)')" />
</Target>

<Target Name="RestorePackages" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(RestoreCommand)"
Condition="'$(OS)' != 'Windows_NT' And Exists('$(PackagesConfig)')" />

<Exec Command="$(RestoreCommand)"
LogStandardErrorAsError="true"
Condition="'$(OS)' == 'Windows_NT' And Exists('$(PackagesConfig)')" />
</Target>

<Target Name="BuildPackage" DependsOnTargets="CheckPrerequisites">
<Exec Command="$(BuildCommand)"
Condition=" '$(OS)' != 'Windows_NT' " />

<Exec Command="$(BuildCommand)"
LogStandardErrorAsError="true"
Condition=" '$(OS)' == 'Windows_NT' " />
</Target>

<UsingTask TaskName="DownloadNuGet" TaskFactory="CodeTaskFactory" AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v4.0.dll">
<ParameterGroup>
<OutputFilename ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Reference Include="System.Core" />
<Using Namespace="System" />
<Using Namespace="System.IO" />
<Using Namespace="System.Net" />
<Using Namespace="Microsoft.Build.Framework" />
<Using Namespace="Microsoft.Build.Utilities" />
<Code Type="Fragment" Language="cs">
<![CDATA[
try {
OutputFilename = Path.GetFullPath(OutputFilename);

Log.LogMessage("Downloading latest version of NuGet.exe...");
WebClient webClient = new WebClient();
webClient.DownloadFile("https://www.nuget.org/nuget.exe", OutputFilename);

return true;
}
catch (Exception ex) {
Log.LogErrorFromException(ex);
return false;
}
]]>
</Code>
</Task>
</UsingTask>
</Project>
33 changes: 33 additions & 0 deletions AngularJSAuthentication.API/AngularJSAuthentication.API.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
<IISExpressAnonymousAuthentication />
<IISExpressWindowsAuthentication />
<IISExpressUseClassicPipelineMode />
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\</SolutionDir>
<RestorePackages>true</RestorePackages>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
Expand Down Expand Up @@ -129,6 +131,7 @@
<Compile Include="App_Start\WebApiConfig.cs" />
<Compile Include="AuthContext.cs" />
<Compile Include="AuthRepository.cs" />
<Compile Include="Constants.cs" />
<Compile Include="Controllers\AccountController.cs" />
<Compile Include="Controllers\OrdersController.cs" />
<Compile Include="Controllers\RefreshTokensController.cs" />
Expand All @@ -139,13 +142,27 @@
<Compile Include="Migrations\201407121205456_AddClientsAndRefreshTokenTables.Designer.cs">
<DependentUpon>201407121205456_AddClientsAndRefreshTokenTables.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\201410270946093_Update_RefreshTokens_Schema.cs" />
<Compile Include="Migrations\201410270946093_Update_RefreshTokens_Schema.Designer.cs">
<DependentUpon>201410270946093_Update_RefreshTokens_Schema.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\201410271049298_Add_UserAgent_to_RefreshTokens.cs" />
<Compile Include="Migrations\201410271049298_Add_UserAgent_to_RefreshTokens.Designer.cs">
<DependentUpon>201410271049298_Add_UserAgent_to_RefreshTokens.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\201410281412441_Adding_UserAgentId_To_RefreshTokens.cs" />
<Compile Include="Migrations\201410281412441_Adding_UserAgentId_To_RefreshTokens.Designer.cs">
<DependentUpon>201410281412441_Adding_UserAgentId_To_RefreshTokens.cs</DependentUpon>
</Compile>
<Compile Include="Migrations\Configuration.cs" />
<Compile Include="Models\Enums.cs" />
<Compile Include="Models\ExternalLoginModels.cs" />
<Compile Include="Models\UserModel.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Providers\AuthenticationTicketProvider.cs" />
<Compile Include="Providers\FacebookAuthProvider.cs" />
<Compile Include="Providers\GoogleAuthProvider.cs" />
<Compile Include="Providers\IdentityCorsPolicyProvider.cs" />
<Compile Include="Providers\SimpleAuthorizationServerProvider.cs" />
<Compile Include="Providers\SimpleRefreshTokenProvider.cs" />
<Compile Include="Results\ChallengeResult.cs" />
Expand All @@ -168,6 +185,15 @@
<EmbeddedResource Include="Migrations\201407121205456_AddClientsAndRefreshTokenTables.resx">
<DependentUpon>201407121205456_AddClientsAndRefreshTokenTables.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Migrations\201410270946093_Update_RefreshTokens_Schema.resx">
<DependentUpon>201410270946093_Update_RefreshTokens_Schema.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Migrations\201410271049298_Add_UserAgent_to_RefreshTokens.resx">
<DependentUpon>201410271049298_Add_UserAgent_to_RefreshTokens.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Migrations\201410281412441_Adding_UserAgentId_To_RefreshTokens.resx">
<DependentUpon>201410281412441_Adding_UserAgentId_To_RefreshTokens.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<PropertyGroup>
<VisualStudioVersion Condition="'$(VisualStudioVersion)' == ''">10.0</VisualStudioVersion>
Expand All @@ -194,6 +220,13 @@
</FlavorProperties>
</VisualStudio>
</ProjectExtensions>
<Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Enable 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('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
</Target>
<!-- 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">
Expand Down
68 changes: 44 additions & 24 deletions AngularJSAuthentication.API/AuthRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,19 @@
using AngularJSAuthentication.API.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.Owin.Security;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;

namespace AngularJSAuthentication.API
{

public class AuthRepository : IDisposable
{
private AuthContext _ctx;
private readonly AuthContext _ctx;

private UserManager<IdentityUser> _userManager;
private readonly UserManager<IdentityUser> _userManager;

public AuthRepository()
{
Expand All @@ -27,7 +24,7 @@ public AuthRepository()

public async Task<IdentityResult> RegisterUser(UserModel userModel)
{
IdentityUser user = new IdentityUser
var user = new IdentityUser
{
UserName = userModel.UserName
};
Expand All @@ -39,58 +36,81 @@ public async Task<IdentityResult> RegisterUser(UserModel userModel)

public async Task<IdentityUser> FindUser(string userName, string password)
{
IdentityUser user = await _userManager.FindAsync(userName, password);
var user = await _userManager.FindAsync(userName, password);

return user;
}

public IdentityUser FindUserByName(string userName)
{
return _userManager.FindByName(userName);
}

public Client FindClient(string clientId)
{
var client = _ctx.Clients.Find(clientId);

return client;
}

public async Task<bool> AddRefreshToken(RefreshToken token)
public IQueryable<Client> GetAllClients(ApplicationTypes apptype, bool isActive = true)
{
var clients = _ctx.Clients.Where(t => t.ApplicationType == apptype && t.Active == isActive);

var existingToken = _ctx.RefreshTokens.Where(r => r.Subject == token.Subject && r.ClientId == token.ClientId).SingleOrDefault();
return clients;
}

if (existingToken != null)
{
var result = await RemoveRefreshToken(existingToken);
}

public bool AddRefreshToken(RefreshToken token)
{
_ctx.RefreshTokens.Add(token);

return await _ctx.SaveChangesAsync() > 0;
return _ctx.SaveChanges() > 0;
}

public async Task<bool> RemoveRefreshToken(string refreshTokenId)
{
var refreshToken = await _ctx.RefreshTokens.FindAsync(refreshTokenId);

if (refreshToken != null) {
_ctx.RefreshTokens.Remove(refreshToken);
return await _ctx.SaveChangesAsync() > 0;
return RemoveRefreshToken(refreshToken);
}

return false;
}

public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken)
public bool RemoveRefreshToken(params RefreshToken[] refreshTokens)
{
_ctx.RefreshTokens.Remove(refreshToken);
return await _ctx.SaveChangesAsync() > 0;
foreach (var refreshToken in refreshTokens)
{
_ctx.RefreshTokens.Remove(refreshToken);
}
return _ctx.SaveChanges() > 0;
}

public async Task<RefreshToken> FindRefreshToken(string refreshTokenId)
public RefreshToken FindRefreshToken(string refreshTokenId)
{
var refreshToken = await _ctx.RefreshTokens.FindAsync(refreshTokenId);
var refreshToken = _ctx.RefreshTokens.Find(refreshTokenId);

return refreshToken;
}

public IQueryable<RefreshToken> FindRefreshTokens(string clientId, string userName,
string userAgentId,
DateTime? maxExpiresUtc = null)
{
var query = _ctx.RefreshTokens.AsQueryable()
.Where(t => t.UserName == userName && t.ClientId == clientId);

if (userAgentId != null)
{
query = query.Where(t => t.UserAgentId == userAgentId);
}
if (maxExpiresUtc.HasValue)
{
query = query.Where(t => t.ExpiresUtc < maxExpiresUtc);
}

return query;
}

public List<RefreshToken> GetAllRefreshTokens()
{
return _ctx.RefreshTokens.ToList();
Expand Down
13 changes: 13 additions & 0 deletions AngularJSAuthentication.API/Constants.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
namespace AngularJSAuthentication.API
{
public static class Constants
{
public static class OAuth
{
public const string RefreshTokeLifeTime = "AngularJSAuthentication.API.OAuth.RefreshTokeLifetime";
public const string ClientId = "AngularJSAuthentication.API.OAuth.ClientId";
public const string UserAgentId = "AngularJSAuthentication.API.OAuth.UserAgentId";
public const string IsOriginAllowed = "AngularJSAuthentication.API.OAuth.IsOriginAllowed";
}
}
}
4 changes: 0 additions & 4 deletions AngularJSAuthentication.API/Entities/Client.cs
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
using AngularJSAuthentication.API.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;

namespace AngularJSAuthentication.API.Entities
{
Expand Down
Loading