Skip to content

Commit

Permalink
protect the Api
Browse files Browse the repository at this point in the history
  • Loading branch information
bnek committed Oct 29, 2020
1 parent 7eab6bc commit b77263c
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

Expand All @@ -24,6 +25,7 @@ public WeatherForecastController(ILogger<WeatherForecastController> logger)
}

[HttpGet]
[Authorize]
public IEnumerable<WeatherForecast> Get()
{
var rng = new Random();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="3.1.8" />
<PackageReference Include="Microsoft.AspNetCore.SpaServices.Extensions" Version="3.1.7" />
</ItemGroup>

Expand Down
19 changes: 19 additions & 0 deletions web/msal-2-auth-code-flow-spa-aspnet-core-31/Msal2/Startup.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
Expand All @@ -20,6 +24,18 @@ 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(options =>
{
options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(jwtOptions =>
{
var instance = Configuration["AzureAd:Instance"];
var domain = Configuration["AzureAd:Domain"];
jwtOptions.Authority = $"{instance}/{domain}/v2.0/";
jwtOptions.Audience = Configuration["AzureAd:ClientId"];
});

services.AddControllersWithViews();

Expand Down Expand Up @@ -50,6 +66,9 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

app.UseRouting();

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

app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
{
"Logging": {
"LogLevel": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*"
}
},
"AzureAd": {
"TenantId": "<Your Tenant Id>",
"ClientId": "<Client ID of your app registration>",
"Domain": "<YourAzureAdTenant>.onmicrosoft.com",
"Instance": "https://login.microsoftonline.com/"
},
"AllowedHosts": "*"
}

0 comments on commit b77263c

Please sign in to comment.