Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
softwarejc committed Mar 15, 2016
1 parent 14c8f5b commit a52ed81
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 32 deletions.
4 changes: 3 additions & 1 deletion 2-CookiesAuthentication/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,11 @@ public async Task<IActionResult> Login(LoginViewModel model, string returnUrl =
{
new Claim(ClaimTypes.Name, model.Name),
},

// Claims schema
CookieAuthenticationDefaults.AuthenticationScheme);

// Convert claims into a cookie using the cookie schema, if "AutomaticAuthenticate" is true
// that cookie will always be read and converted into a ClaimsIdentity in every request
await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));

return LocalRedirect(returnUrl ?? "/");
Expand Down
2 changes: 1 addition & 1 deletion 2-CookiesAuthentication/Views/Account/Index.cshtml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
{
<h3>Claims</h3>
<dl>
@foreach (var claim in ((System.Security.Claims.ClaimsPrincipal)User).Claims)
@foreach (var claim in User.Claims)
{
<dt>@claim.Type</dt>
<dd>@claim.Value</dd>
Expand Down
16 changes: 7 additions & 9 deletions 5-OpenIdConnect/Controllers/IdentityController.cs
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
using Microsoft.AspNet.Mvc;
using Microsoft.AspNet.Authorization;
using System.Linq;
using IdentityModel.Client;
using System;
using System.Threading.Tasks;
using System.Security.Claims;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using Newtonsoft.Json.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNet.Authorization;
using Microsoft.AspNet.Mvc;
using Newtonsoft.Json.Linq;

namespace _5_OpenIdConnect.Controllers
{
Expand All @@ -33,6 +29,8 @@ public async Task SignOut()
public async Task<IActionResult> CallApi()
{
// todo...
// configure UseIdentityServerBearerTokenAuthentication (or Microsoft middleware)
// that middleware validates the token

var token = User.FindFirst("access_token").Value;

Expand Down
48 changes: 27 additions & 21 deletions 5-OpenIdConnect/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Builder;
Expand Down Expand Up @@ -40,9 +41,10 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = "Cookies",
AutomaticAuthenticate = true, // OnAuthorizationCodeReceived will do the authentication
AutomaticChallenge = false,
AuthenticationScheme = "Cookies", // We can have more than one authentication "system", we need a name to distinguish them

AutomaticAuthenticate = true, // Way in - IF true, Convert cookie into identity object
AutomaticChallenge = false, // Way out - IF true, redirect to challenge URL
});

OpenIdConnectEvents events = null;
Expand All @@ -61,12 +63,11 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
options.Scope.Add("offline_access");
options.Scope.Add("role");
// Used to register later events
// Used to register events later
events = options.Events as OpenIdConnectEvents;
});

events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;
events.OnAuthenticationValidated = OnAuthenticationValidated;
if (events != null) events.OnAuthorizationCodeReceived = OnAuthorizationCodeReceived;

app.UseDeveloperExceptionPage();
app.UseMvc();
Expand All @@ -80,31 +81,36 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
private async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
{
// 1) Use the code to get the access and refresh token,
// As we are using the hybrid we will get code and access token but not refresh token,
// using the code we can get one if the client application is a server side app (like this example)
// As we are using the hybrid flow, we will get a "code" and "access_token" but not "refresh_token".
// Using the code we can get a "refresh_token" if the client application is a server side app (like this example)
// If the application is a SPA or a native phone app, it is not secure to use the ClientSecret to get an access token
var tokenClient = new TokenClient(Constants.TokenEndpoint, Constants.ClientId, Constants.ClientSecret);
var tokensResponse = tokenClient.RequestAuthorizationCodeAsync(context.Code, context.RedirectUri).Result;
List<Claim> oauthClaims = new List<Claim>();
oauthClaims.Add(new Claim("access_token", tokensResponse.AccessToken)); // JWT token, This will allow us to call the Resource (WebAPI)
oauthClaims.Add(new Claim("refresh_token", tokensResponse.RefreshToken));
oauthClaims.Add(new Claim("expires_at", DateTime.Now.AddSeconds(tokensResponse.ExpiresIn).ToLocalTime().ToString()));

var expiration = DateTime.Now.AddSeconds(tokensResponse.ExpiresIn)
.ToLocalTime()
.ToString(CultureInfo.InvariantCulture);

List<Claim> oauthClaims = new List<Claim>
{
new Claim("access_token", tokensResponse.AccessToken),
new Claim("refresh_token", tokensResponse.RefreshToken),
new Claim("expires_at", expiration)
};

// 2) Use the access token to retrieve user info claims
// The access token is a JWT token, it can be used to secure WebApi
var userInfoClient = new UserInfoClient(new Uri(Constants.UserInfoEndpoint), tokensResponse.AccessToken);
var userInfo = await userInfoClient.GetAsync();
List<Claim> userClaims = userInfo.Claims.Select(ui => new Claim(ui.Item1, ui.Item2)).ToList();

// 3) Add claims to authentication ticket
ClaimsIdentity identity = context.AuthenticationTicket.Principal.Identity as ClaimsIdentity;
identity.AddClaims(oauthClaims);
identity.AddClaims(userClaims);
}

private Task OnAuthenticationValidated(AuthenticationValidatedContext context)
{
Console.WriteLine("OnAuthenticationValidated");

return Task.FromResult(0);
if (identity != null)
{
identity.AddClaims(oauthClaims);
identity.AddClaims(userClaims);
}
}

// Entry point for the application.
Expand Down

0 comments on commit a52ed81

Please sign in to comment.