Skip to content

Commit

Permalink
Implement Refresh Token
Browse files Browse the repository at this point in the history
  • Loading branch information
lcorozco10 committed Jan 28, 2016
1 parent 7441651 commit 1cab02a
Show file tree
Hide file tree
Showing 6 changed files with 113 additions and 34 deletions.
1 change: 1 addition & 0 deletions Api.Rest.Secure/Api.Rest.Secure.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@
<Compile Include="AuthRepository.cs" />
<Compile Include="Controller\AccountController.cs" />
<Compile Include="Controller\OrdersController.cs" />
<Compile Include="Controller\RefreshTokensController.cs" />
<Compile Include="Migrations\201601262034249_InitialCreate.cs" />
<Compile Include="Migrations\201601262034249_InitialCreate.Designer.cs">
<DependentUpon>201601262034249_InitialCreate.cs</DependentUpon>
Expand Down
41 changes: 12 additions & 29 deletions Api.Rest.Secure/AuthRepository.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,25 +40,10 @@ public async Task<IdentityUser> FindUser(string userName, string password)

return user;
}

public void Dispose()
{
_ctx.Dispose();
_userManager.Dispose();

}


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

return client;
}


public async Task<bool> AddRefreshToken(RefreshToken token)
{

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

if (existingToken != null)
Expand All @@ -75,13 +60,10 @@ 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;
}
if (refreshToken == null) return false;

return false;
_ctx.RefreshTokens.Remove(refreshToken);
return await _ctx.SaveChangesAsync() > 0;
}

public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken)
Expand All @@ -90,16 +72,17 @@ public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken)
return await _ctx.SaveChangesAsync() > 0;
}

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

return refreshToken;
}
public async Task<RefreshToken> FindRefreshToken(string refreshTokenId) => await _ctx.RefreshTokens.FindAsync(refreshTokenId);

public List<RefreshToken> GetAllRefreshTokens() =>_ctx.RefreshTokens.ToList();

public List<RefreshToken> GetAllRefreshTokens()
public void Dispose()
{
return _ctx.RefreshTokens.ToList();
_ctx.Dispose();
_userManager.Dispose();

}

}
Expand Down
53 changes: 53 additions & 0 deletions Api.Rest.Secure/Controller/RefreshTokensController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;

namespace Api.Rest.Secure.Controller
{
[RoutePrefix("api/RefreshTokens")]
public class RefreshTokensController : ApiController
{

private readonly AuthRepository _repo;

public RefreshTokensController()
{
_repo = new AuthRepository();
}

[Authorize(Users = "Admin")]
[Route("")]
public IHttpActionResult Get()
{
return Ok(_repo.GetAllRefreshTokens());
}

//[Authorize(Users = "Admin")]
[AllowAnonymous]
[Route("")]
public async Task<IHttpActionResult> Delete(string tokenId)
{
var result = await _repo.RemoveRefreshToken(tokenId);
if (result)
{
return Ok();
}
return BadRequest("Token Id does not exist");

}

protected override void Dispose(bool disposing)
{
if (disposing)
{
_repo.Dispose();
}

base.Dispose(disposing);
}
}
}
24 changes: 24 additions & 0 deletions Api.Rest.Secure/Providers/SimpleAuthorizationServerProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,29 @@ public override Task TokenEndpoint(OAuthTokenEndpointContext context)

return Task.FromResult<object>(null);
}


public override Task GrantRefreshToken(OAuthGrantRefreshTokenContext context)
{
var originalClient = context.Ticket.Properties.Dictionary["as:client_id"];
var currentClient = context.ClientId;

if (originalClient != currentClient)
{
context.SetError("invalid_clientId", "Refresh token is issued to a different clientId.");
return Task.FromResult<object>(null);
}

// Change auth ticket for refresh token requests
var newIdentity = new ClaimsIdentity(context.Ticket.Identity);
newIdentity.AddClaim(new Claim("newClaim", "newValue"));

var newTicket = new AuthenticationTicket(newIdentity, context.Ticket.Properties);
context.Validated(newTicket);

return Task.FromResult<object>(null);
}

}

public class Helper
Expand All @@ -132,4 +155,5 @@ public static string GetHash(string input)
return Convert.ToBase64String(byteHash);
}
}

}
21 changes: 19 additions & 2 deletions Api.Rest.Secure/Providers/SimpleRefreshTokenProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,9 +59,26 @@ public void Receive(AuthenticationTokenReceiveContext context)
throw new NotImplementedException();
}

public Task ReceiveAsync(AuthenticationTokenReceiveContext context)
public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
{
throw new NotImplementedException();
var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

string hashedTokenId = Helper.GetHash(context.Token);

using (AuthRepository _repo = new AuthRepository())
{
var refreshToken = await _repo.FindRefreshToken(hashedTokenId);

if (refreshToken != null)
{
//Get protectedTicket from refreshToken class
context.DeserializeTicket(refreshToken.ProtectedTicket);
var result = await _repo.RemoveRefreshToken(hashedTokenId);
}
}
}


}
}
7 changes: 4 additions & 3 deletions Api.Rest.Secure/StartUp.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using Owin;
using System;
using System.Web.Http;
using Microsoft.Owin.Security;

[assembly: OwinStartup(typeof(Api.Rest.Secure.Startup))]
namespace Api.Rest.Secure
Expand All @@ -26,18 +27,18 @@ public void Configuration(IAppBuilder app)

public void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
OAuthAuthorizationServerOptions oAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10),
Provider = new SimpleAuthorizationServerProvider(),
RefreshTokenProvider = new SimpleRefreshTokenProvider()

};

// Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthAuthorizationServer(oAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

}
Expand Down

0 comments on commit 1cab02a

Please sign in to comment.