Created
December 4, 2019 08:13
-
-
Save bachoang/76f3b777cac79a8544f455aa10396a30 to your computer and use it in GitHub Desktop.
ASP.Net Core 2.2 Web API with AAD Authentication
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using Microsoft.AspNetCore.Authentication.JwtBearer; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Mvc; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
namespace CoreWebAPIAAD | |
{ | |
public class Startup | |
{ | |
// public string token = ""; | |
public Startup(IConfiguration configuration) | |
{ | |
Configuration = configuration; | |
} | |
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) | |
{ | |
services.AddAuthentication(sharedoptions => | |
{ | |
sharedoptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; | |
}) | |
.AddJwtBearer(options => | |
{ | |
// Example: "https://login.microsoftonline.com/contoso.onmicrosoft.com" | |
options.Authority = https://login.microsoftonline.com/<tenant name> or <Directory ID>; | |
// if you intend to validate only one audience for the access token, you can use options.Audience instead of | |
// using options.TokenValidationParameters which allow for more customization. | |
// options.Audience = "10e569bc5-4c43-419e-971b-7c37112adf691"; | |
options.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters | |
{ | |
ValidAudiences = new List<string> { "https://contoso.onmicrosoft.com/TodoListService", "10e569bc5-4c43-419e-971b-7c37112adf691" }, | |
// set the following issuers if you want to support both V1 and V2 issuers | |
ValidIssuers = new List<string> { "https://sts.windows.net/<Directory ID>/", "https://sts.windows.net/<Directory ID>/v2.0" } | |
}; | |
}); | |
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); | |
} | |
// 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 | |
{ | |
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. | |
app.UseHsts(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseAuthentication(); | |
app.UseMvc(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add JWT Bearer Authentication to protect web API with Azure AD