目的
apsnetcore8 webapiでokta認証 を実装する
環境
- aspnetcore webapi 8
- Okta.AspNetCore 4.6.8
okta nugetパッケージインストール
.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<RootNamespace>xxxxxxx</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Okta.AspNetCore" Version="4.6.3" />
</ItemGroup>
</Project>
XMLProgram.csにokta認証設定
以下の行を追加
Program.cs
using System.Diagnostics;
using Okta.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
IHostEnvironment environment = builder.Environment;
Debug.WriteLine(environment.EnvironmentName);
Debug.WriteLine(Directory.GetCurrentDirectory());
//Auth
builder.Services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = OktaDefaults.ApiAuthenticationScheme;
opt.DefaultChallengeScheme = OktaDefaults.ApiAuthenticationScheme;
opt.DefaultSignInScheme = OktaDefaults.ApiAuthenticationScheme;
}).AddOktaWebApi(new OktaWebApiOptions()
{
OktaDomain = builder.Configuration["Okta:OktaDomain"],
AuthorizationServerId = builder.Configuration["Okta:AuthorizationServerId"]
});
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }
C#appsetting.jsonにokta認証サーバーの設定記載
appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"Okta": {
"OktaDomain": "[oktaサブドメイン(https://xxxxx.okta.com)]",
"AuthorizationServerId": "default"
}
}
JSON認証が必要なAPI・コントローラーに[Authorize]属性付与
コントローラー自体に付与してもいいし、API単位で付与することもできる
SampleController.cs
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("samples")]
public class SampleController : ControllerBase
{
[HttpPost]
[Authorize]
public async Task<ActionResult> Registry()
{
return Created();
}
}
C#開発時の設定
開発時には認証が邪魔な場合がある。開発時のみ認証処理がすべて通るような設定をする。
Program.cs(修正版)
using System.Diagnostics;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Okta.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
IHostEnvironment environment = builder.Environment;
Debug.WriteLine(environment.EnvironmentName);
Debug.WriteLine(Directory.GetCurrentDirectory());
//Auth
if (!environment.IsDevelopment())
{
builder.Services.AddAuthentication(opt =>
{
opt.DefaultAuthenticateScheme = OktaDefaults.ApiAuthenticationScheme;
opt.DefaultChallengeScheme = OktaDefaults.ApiAuthenticationScheme;
opt.DefaultSignInScheme = OktaDefaults.ApiAuthenticationScheme;
}).AddOktaWebApi(new OktaWebApiOptions()
{
OktaDomain = builder.Configuration["Okta:OktaDomain"],
AuthorizationServerId = builder.Configuration["Okta:AuthorizationServerId"]
});
}
else
{
builder.Services.AddAuthentication("AllowAll")
.AddScheme<AuthenticationSchemeOptions, AllowAnonymousAuthHandler>("AllowAll", Options => { });
builder.Services.AddAuthorization(opt =>
{
var allowAllPolicy = new AuthorizationPolicyBuilder("AllowAll")
.RequireAssertion(_ => true)
.Build();
opt.FallbackPolicy = allowAllPolicy;
opt.DefaultPolicy = allowAllPolicy;
});
}
var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
public partial class Program { }
C#AllowAnonymousAuthHandler
AllowAnonymousAuthHandler.cs
using System.Security.Claims;
using System.Text.Encodings.Web;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
public class AllowAnonymousAuthHandler : AuthenticationHandler<AuthenticationSchemeOptions>
{
public AllowAnonymousAuthHandler(IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder) : base(options, logger, encoder) { }
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
// 匿名ユーザーを常に通す
var identity = new ClaimsIdentity();
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
C#以上で apsnetcore8 webapiでokta認証 の実装が完了
参考サイト
他のokta記事はこちら