Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
54 changes: 28 additions & 26 deletions src/GoogleIncrementalMvcSample/Controllers/HomeController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using Google.Apis.Auth.AspNetCore;
using Google.Apis.Auth.AspNetCore3;
using Google.Apis.Classroom.v1;
using Google.Apis.Classroom.v1.Data;
using Google.Apis.Services;
Expand All @@ -18,35 +18,34 @@ namespace GoogleIncrementalMvcSample.Controllers
{
public class HomeController : Controller
{
private readonly IGoogleAuthProvider _auth;

public HomeController(IGoogleAuthProvider auth)
public HomeController()
{
_auth = auth;
}

/// <summary>
/// Display the home page.
/// </summary>
public async Task<IActionResult> Index()
public async Task<IActionResult> Index([FromServices] IGoogleAuthProvider _auth)
{
var model = await LoadUserInfoAsync();
var model = await LoadUserInfoAsync(_auth);

return View(model);
}

/// <summary>
/// Display an error page.
/// </summary>
public IActionResult Error()
{
return View(new ErrorViewModel {RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier});
}
/// <summary>
/// Display an error page.
/// </summary>
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}

/// <summary>
/// User Sign In action.
/// </summary>
[Authorize]
/// <summary>
/// User Sign In action.
/// </summary>
[Authorize]
public IActionResult SignIn()
{
return RedirectToAction("Index");
Expand All @@ -62,16 +61,19 @@ public async Task<IActionResult> SignOut()
return RedirectToAction("Index");
}

/// <summary>
/// Display the list of the the user's Google Classroom classes. Scopes
/// requested: email, profile, and ClassroomService.Scope.ClassroomCoursesReadonly.
/// </summary>
[GoogleScopedAuthorize("https://www.googleapis.com/auth/classroom.courses.readonly")]
public async Task<IActionResult> ListCourses()
/// <summary>
/// Display the list of the the user's Google Classroom classes. Scopes
/// requested: email, profile, and ClassroomService.Scope.ClassroomCoursesReadonly.
/// </summary>
//[GoogleScopedAuthorize("https://www.googleapis.com/auth/classroom.courses.readonly")]

[Authorize]

public async Task<IActionResult> ListCourses([FromServices] IGoogleAuthProvider _auth)
{
var cred = await _auth.GetCredentialAsync();

var model = await LoadUserInfoAsync();
var model = await LoadUserInfoAsync(_auth);

try
{
Expand Down Expand Up @@ -120,7 +122,7 @@ public async Task<IActionResult> ListCourses()
}
}

private async Task<IndexModel> LoadUserInfoAsync()
private async Task<IndexModel> LoadUserInfoAsync(IGoogleAuthProvider auth)
{
var model = new IndexModel();

Expand All @@ -129,7 +131,7 @@ private async Task<IndexModel> LoadUserInfoAsync()
model.UserEmail = User.Claims.SingleOrDefault(c => c.Type == ClaimTypes.Email)?.Value;
model.UserName = User.Claims.SingleOrDefault(c => c.Type == "name")?.Value;

model.Scopes = await _auth.GetCurrentScopesAsync();
model.Scopes = await auth.GetCurrentScopesAsync();
}

return model;
Expand Down
11 changes: 5 additions & 6 deletions src/GoogleIncrementalMvcSample/GoogleIncrementalMvcSample.csproj
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<UserSecretsId>d151a932-920a-42b9-a2a7-1ba24bbc8a7e</UserSecretsId>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Google.Apis.Classroom.v1" Version="1.34.0.1236" />
<PackageReference Include="Microsoft.AspNetCore.All" />
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.1.1" PrivateAssets="All" />
<Compile Remove="Controllers\AccountController.cs" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\google-api-dotnet-client\Src\Support\Google.Apis.Auth.AspNetCore\Google.Apis.Auth.AspNetCore.csproj" />
<PackageReference Include="Google.Apis.Auth.AspNetCore3" Version="1.49.0" />
<PackageReference Include="Google.Apis.Classroom.v1" Version="1.49.0.2113" />

</ItemGroup>

</Project>
25 changes: 13 additions & 12 deletions src/GoogleIncrementalMvcSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
using Microsoft.ApplicationInsights.Extensibility.Implementation;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;

namespace GoogleIncrementalMvcSample
{
public class Program
{
public static void Main(string[] args)
{
TelemetryDebugWriter.IsTracingDisabled = true;
CreateWebHostBuilder(args).Build().Run();
}

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>();
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
66 changes: 44 additions & 22 deletions src/GoogleIncrementalMvcSample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Hosting;
using Google.Apis.Auth.AspNetCore3;

namespace GoogleIncrementalMvcSample
{
public class Startup
Expand All @@ -22,23 +26,35 @@ public Startup(IConfiguration configuration)
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => options.ExpireTimeSpan = TimeSpan.FromMinutes(2))
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});

services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
services.AddControllersWithViews();
services.AddRazorPages();

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication();
// This configures Google.Apis.Auth.AspNetCore3 for use in this app.
services
.AddAuthentication(o =>
{
// This forces challenge results to be handled by Google OpenID Handler, so there's no
// need to add an AccountController that emits challenges for Login.
o.DefaultChallengeScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// This forces forbid results to be handled by Google OpenID Handler, which checks if
// extra scopes are required and does automatic incremental auth.
o.DefaultForbidScheme = GoogleOpenIdConnectDefaults.AuthenticationScheme;
// Default scheme that will handle everything else.
// Once a user is authenticated, the OAuth2 token info is stored in cookies.
o.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogleOpenIdConnect(options =>
{
options.ClientId = Configuration["Authentication:Google:ClientId"];
options.ClientSecret = Configuration["Authentication:Google:ClientSecret"];
});

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
Expand All @@ -52,12 +68,18 @@ public void Configure(IApplicationBuilder app, IHostingEnvironment env)
app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
}
}
}