Last active
November 24, 2020 15:20
-
-
Save beachside-project/1f5cff9a87ae66021b371957e10059ac to your computer and use it in GitHub Desktop.
Azure AD - AppRoles AuthZ sample - Startup.cs
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 Microsoft.AspNetCore.Authentication.JwtBearer; | |
using Microsoft.AspNetCore.Builder; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.Extensions.Configuration; | |
using Microsoft.Extensions.DependencyInjection; | |
using Microsoft.Extensions.Hosting; | |
using Microsoft.IdentityModel.Tokens; | |
using System.Net; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace AzureAdAppRolesWebSample | |
{ | |
public class Startup | |
{ | |
private readonly IWebHostEnvironment _env; // HACK: 追加 | |
public Startup(IConfiguration configuration, IWebHostEnvironment env) // HACK: 2つめの引数 env を追加 | |
{ | |
Configuration = configuration; | |
_env = env; // HACK: 追加 | |
} | |
public IConfiguration Configuration { get; } | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
AddAzureAdJwtAuth(services);// HACK: 追加 | |
services.AddControllers(); | |
} | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
if (env.IsDevelopment()) | |
{ | |
app.UseDeveloperExceptionPage(); | |
} | |
app.UseHttpsRedirection(); | |
app.UseRouting(); | |
app.UseAuthentication(); // HACK: 追加 | |
app.UseAuthorization(); | |
app.UseEndpoints(endpoints => | |
{ | |
endpoints.MapControllers(); | |
}); | |
} | |
// HACK: メソッドを追加 | |
public void AddAzureAdJwtAuth(IServiceCollection services) | |
{ | |
services.AddAuthentication(options => { options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; }) | |
.AddJwtBearer(jwtOptions => | |
{ | |
jwtOptions.Authority = Configuration.GetValue<string>("AzureAd:Authority"); | |
jwtOptions.Audience = Configuration.GetValue<string>("AzureAd:ClientId"); | |
if (_env.IsDevelopment()) | |
{ | |
// テキトーにトークンの validation の条件変更を書く(有効期限の検証無視はよくないヨ) | |
jwtOptions.TokenValidationParameters = new TokenValidationParameters() | |
{ | |
ValidateLifetime = false, | |
}; | |
// エラーイベントもかける(デバッグ専用って用途) | |
jwtOptions.Events = new JwtBearerEvents | |
{ | |
OnAuthenticationFailed = AuthenticationFailed | |
}; | |
} | |
}); | |
} | |
// HACK: メソッドを追加 | |
private static async Task AuthenticationFailed(AuthenticationFailedContext arg) | |
{ | |
var message = $"AuthenticationFailed: {arg.Exception.Message}"; | |
arg.Response.ContentLength = message.Length; | |
arg.Response.StatusCode = (int)HttpStatusCode.Unauthorized; | |
await arg.Response.Body.WriteAsync(Encoding.UTF8.GetBytes(message), 0, message.Length); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment