Skip to content

Commit

Permalink
Update OAuth sample for 2.0.0-preview2-final
Browse files Browse the repository at this point in the history
  • Loading branch information
jerriep committed Aug 3, 2017
1 parent 20fcbe8 commit 3ac3de5
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 161 deletions.
46 changes: 8 additions & 38 deletions Samples/oauth2/AspNetCoreOAuth2Sample.csproj
Original file line number Diff line number Diff line change
@@ -1,48 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp1.1</TargetFramework>
<DebugType>portable</DebugType>
<PreserveCompilationContext>true</PreserveCompilationContext>
<AssemblyName>oauth2</AssemblyName>
<OutputType>Exe</OutputType>
<PackageId>oauth2</PackageId>
<RuntimeFrameworkVersion>1.0.4</RuntimeFrameworkVersion>
<PackageTargetFallback>$(PackageTargetFallback);dotnet5.6;dnxcore50;portable-net45+win8</PackageTargetFallback>
<TargetFramework>netcoreapp2.0</TargetFramework>
<AssetTargetFallback>$(AssetTargetFallback);portable-net45+win8+wp8+wpa81;</AssetTargetFallback>
</PropertyGroup>

<ItemGroup>
<None Update="wwwroot\**\*;Views\**\*">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
</None>
<PackageReference Include="BuildBundlerMinifier" Version="2.4.337" />
<PackageReference Include="Microsoft.AspNetCore.All" Version="2.0.0-preview2-final" />
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Diagnostics" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
<PackageReference Include="Microsoft.AspNetCore.Server.IISIntegration" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Server.Kestrel" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.EnvironmentVariables" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
<PackageReference Include="Microsoft.Extensions.Options.ConfigurationExtensions" Version="1.1.2" />
<PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.Cookies" Version="1.1.2" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.OAuth" Version="1.1.2" />
<DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.0-preview2-final" />
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="2.0.0-preview2-final" />
</ItemGroup>

<Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
<Exec Command="npm install" />
<Exec Command="bower install" />
<Exec Command="gulp clean" />
<Exec Command="gulp min" />
<Exec Command="dotnet bundle" />
</Target>

<ItemGroup>
<DotNetCliToolReference Include="Microsoft.DotNet.Watcher.Tools" Version="1.0.0" />
</ItemGroup>

</Project>
</Project>
13 changes: 0 additions & 13 deletions Samples/oauth2/Auth0Settings.cs

This file was deleted.

17 changes: 9 additions & 8 deletions Samples/oauth2/Controllers/AccountController.cs
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http.Authentication;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Options;

namespace AspNetCoreOAuth2Sample.Controllers
{
public class AccountController: Controller
{
private readonly IOptions<Auth0Settings> _auth0Settings;
private readonly IConfiguration _configuration;

public AccountController(IOptions<Auth0Settings> auth0Settings)
public AccountController(IConfiguration configuration)
{
_auth0Settings = auth0Settings;
_configuration = configuration;
}

public IActionResult Login(string returnUrl = "/")
public async Task Login(string returnUrl = "/")
{
return new ChallengeResult("Auth0", new AuthenticationProperties() { RedirectUri = returnUrl });
await HttpContext.ChallengeAsync("Auth0", new AuthenticationProperties() { RedirectUri = returnUrl });
}

[Authorize]
public async Task Logout()
{
// Sign the user out of the cookie authentication middleware (i.e. it will clear the local session cookie)
await HttpContext.Authentication.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

// Construct the post-logout URL (i.e. where we'll tell Auth0 to redirect after logging the user out)
var request = HttpContext.Request;
string postLogoutUri = request.Scheme + "://" + request.Host + request.PathBase + Url.Action("Index", "Home");

// Redirect to the Auth0 logout endpoint in order to log out of Auth0
string logoutUri = $"https://{_auth0Settings.Value.Domain}/v2/logout?client_id={_auth0Settings.Value.ClientId}&returnTo={Uri.EscapeDataString(postLogoutUri)}";
string logoutUri = $"https://{_configuration["Auth0:Domain"]}/v2/logout?client_id={_configuration["Auth0:ClientId"]}&returnTo={Uri.EscapeDataString(postLogoutUri)}";
HttpContext.Response.Redirect(logoutUri);
}

Expand Down
18 changes: 6 additions & 12 deletions Samples/oauth2/Program.cs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace AspNetCoreOAuth2Sample
Expand All @@ -11,14 +7,12 @@ public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseIISIntegration()
BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();

host.Run();
}
}
}
133 changes: 44 additions & 89 deletions Samples/oauth2/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,102 +1,60 @@
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System.Net.Http;
using System.Net.Http.Headers;
using Microsoft.Extensions.Options;
using Newtonsoft.Json.Linq;

namespace AspNetCoreOAuth2Sample
{
public class Startup
{
public Startup(IHostingEnvironment env)
public Startup(IConfiguration configuration)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
Configuration = configuration;
}

public IConfigurationRoot Configuration { get; }
public IConfiguration Configuration { get; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// Add authentication services
services.AddAuthentication(options => options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme);

// Add framework services.
services.AddMvc();

// Add functionality to inject IOptions<T>
services.AddOptions();

// Add the Auth0 Settings object so it can be injected
services.Configure<Auth0Settings>(Configuration.GetSection("Auth0"));
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<Auth0Settings> auth0Settings)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();

if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

// Add the cookie middleware
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
});

// Add the OAuth2 middleware
app.UseOAuthAuthentication(new OAuthOptions
{
// We need to specify an Authentication Scheme
AuthenticationScheme = "Auth0",

services.AddAuthentication(options => {
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookieAuthentication()
.AddOAuthAuthentication("Auth0", options => {
// Configure the Auth0 Client ID and Client Secret
ClientId = auth0Settings.Value.ClientId,
ClientSecret = auth0Settings.Value.ClientSecret,
options.ClientId = Configuration["Auth0:ClientId"];
options.ClientSecret = Configuration["Auth0:ClientSecret"];

// Set the callback path, so Auth0 will call back to http://localhost:5000/signin-auth0
// Also ensure that you have added the URL as an Allowed Callback URL in your Auth0 dashboard
CallbackPath = new PathString("/signin-auth0"),
options.CallbackPath = new PathString("/signin-auth0");

// Configure the Auth0 endpoints
AuthorizationEndpoint = $"https://{auth0Settings.Value.Domain}/authorize",
TokenEndpoint = $"https://{auth0Settings.Value.Domain}/oauth/token",
UserInformationEndpoint = $"https://{auth0Settings.Value.Domain}/userinfo",
options.AuthorizationEndpoint = $"https://{Configuration["Auth0:Domain"]}/authorize";
options.TokenEndpoint = $"https://{Configuration["Auth0:Domain"]}/oauth/token";
options.UserInformationEndpoint = $"https://{Configuration["Auth0:Domain"]}/userinfo";

// To save the tokens to the Authentication Properties we need to set this to true
// See code in OnTicketReceived event below to extract the tokens and save them as Claims
SaveTokens = true,
options.SaveTokens = true;

// Set scope to openid. See https://auth0.com/docs/scopes
Scope = { "openid" },
options.Scope.Clear();
options.Scope.Add("openid");
options.Scope.Add("profile");

Events = new OAuthEvents
options.Events = new OAuthEvents
{
// When creating a ticket we need to manually make the call to the User Info endpoint to retrieve the user's information,
// and subsequently extract the user's ID and email adddress and store them as claims
Expand All @@ -114,45 +72,42 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerF
var user = JObject.Parse(await response.Content.ReadAsStringAsync());

// Add the Name Identifier claim
var userId = user.Value<string>("user_id");
var userId = user.Value<string>("sub");
if (!string.IsNullOrEmpty(userId))
{
context.Identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, userId, ClaimValueTypes.String, context.Options.ClaimsIssuer));
}

// Add the Name claim
var email = user.Value<string>("email");
var email = user.Value<string>("name");
if (!string.IsNullOrEmpty(email))
{
context.Identity.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, email, ClaimValueTypes.String, context.Options.ClaimsIssuer));
}
},
OnTicketReceived = context =>
{
// Get the ClaimsIdentity
var identity = context.Principal.Identity as ClaimsIdentity;
if (identity != null)
{
// Save the tokens as Claims. If you do not want to do this then set SaveTokens above to false, and also comment out this code
if (context.Properties.Items.ContainsKey(".TokenNames"))
{
string[] tokenNames = context.Properties.Items[".TokenNames"].Split(';');

foreach(string tokenName in tokenNames)
{
string tokenValue = context.Properties.Items[$".Token.{tokenName}"];

if (!identity.HasClaim(c => c.Type == tokenName))
identity.AddClaim(new Claim(tokenName, tokenValue));
}
}
}

return Task.CompletedTask;
}
}
};
});

// Add framework services.
services.AddMvc();
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
}

app.UseStaticFiles();

app.UseAuthentication();

app.UseMvc(routes =>
{
routes.MapRoute(
Expand Down
24 changes: 24 additions & 0 deletions Samples/oauth2/bundleconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Configure bundling and minification for the project.
// More info at https://go.microsoft.com/fwlink/?LinkId=808241
[
{
"outputFileName": "wwwroot/css/site.min.css",
// An array of relative input file paths. Globbing patterns supported
"inputFiles": [
"wwwroot/css/site.css"
]
},
{
"outputFileName": "wwwroot/js/site.min.js",
"inputFiles": [
"wwwroot/js/site.js"
],
// Optionally specify minification options
"minify": {
"enabled": true,
"renameLocals": true
},
// Optinally generate .map file
"sourceMap": false
}
]
2 changes: 1 addition & 1 deletion Samples/oauth2/wwwroot/css/site.min.css

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 3ac3de5

Please sign in to comment.