ASP.NET Core with AAD/AADB2C メモ

# ASP.NET CoreでAAD/AADB2C認証する場合のメモ


### Microsoft.Identity.Web.UI を使う

https://www.nuget.org/packages/Microsoft.Identity.Web.UI

### Startup

```
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
          .AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"));

services.AddMvc().AddMicrosoftIdentityUI();
```

#### Front door(reverse proxy)を前に置いてredirect_uriをfront doorのURLを指定したい場合

```
services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)          
            .AddMicrosoftIdentityWebApp(
                opt => {
                    Configuration.GetSection("AzureAdB2C").Bind(opt);
                    var onRedirectToIdentityProvider = opt.Events.OnRedirectToIdentityProvider;
                    opt.Events.OnRedirectToIdentityProvider = async context => {

                        await onRedirectToIdentityProvider(context);

                        if (opt.CallbackPath.HasValue && context.Request.Headers.ContainsKey("X-Forwarded-Host") && context.Request.Headers.ContainsKey("X-Forwarded-Proto"))
                        {
                            var schema = context.Request.Headers["X-Forwarded-Proto"];
                            var host = context.Request.Headers["X-Forwarded-Host"];
                            context.ProtocolMessage.RedirectUri = new UriBuilder($"{schema}://{host}").SetPath(opt.CallbackPath.Value).ToString();
                        }
                    };

                    var onRedirectToIdentityProviderForSignOut = opt.Events.OnRedirectToIdentityProviderForSignOut;
                    opt.Events.OnRedirectToIdentityProviderForSignOut = async context => {
                        await onRedirectToIdentityProviderForSignOut(context);

                        if (opt.SignedOutCallbackPath.HasValue && context.Request.Headers.ContainsKey("X-Forwarded-Host") && context.Request.Headers.ContainsKey("X-Forwarded-Proto"))
                        {
                            var schema = context.Request.Headers["X-Forwarded-Proto"];
                            var host = context.Request.Headers["X-Forwarded-Host"];
                            context.ProtocolMessage.PostLogoutRedirectUri = new UriBuilder($"{schema}://{host}").SetPath(opt.SignedOutCallbackPath.Value).ToString();
                        }
                    };

                    
                },
                null,
                OpenIdConnectDefaults.AuthenticationScheme,
                CookieAuthenticationDefaults.AuthenticationScheme,
                false);

```
* Front doorでWAF入れている場合、942440:SQL Comment Sequence Detected と 942450:SQL Hex Encoding Identified外さないとAADB2CとのOAuth連携時にブロック対象になる

### ライブラリで良いされているログイン・ログアウトなどの機能

https://github.com/AzureAD/microsoft-identity-web/blob/master/src/Microsoft.Identity.Web.UI/Areas/MicrosoftIdentity/Controllers/AccountController.cs

#### ログイン操作とかを行いたいケース(ログインとかパスワード変更後の戻り場所を制御したい)

```
　　　　　[AllowAnonymous]
        [HttpGet]
        public IActionResult Login([FromQuery] string returnUrl = "/")
        {
            if (!User.Identity.IsAuthenticated)
            {                
                return Challenge(new Microsoft.AspNetCore.Authentication.AuthenticationProperties() { RedirectUri = returnUrl });
            }
            return Redirect("/");
            
        }

 　　　　[AllowAnonymous]
        [HttpGet]
        public IActionResult ResetPassword([FromQuery] string returnUrl = "/")
        {
            return Challenge(new AuthenticationProperties(new Dictionary<string, string> { { Constants.Policy, _options.Value.ResetPasswordPolicyId } }) { RedirectUri = returnUrl });
        }


```
必要に応じてreturnUrlはローカルパスに限定するとかチェックを入れる。