title: Identity Server 4 with OAuth and ADFS
body: <p>I am having trouble with using OAuthAuthentication with IS4 and ASPNetCore. Took DamienBod's (thank you) sample Identity Server with AspNetIdentity attempted adding OAuth with windows server 2012 ADFS3. I could authenticate using the external ADFS but not getting correct results on the Identity Server side.
  <code>AccountController.ExternalLoginCallback</code> : <code>var info = await _signInManager.GetExternalLoginInfoAsync()</code> returns NULL and am back to login page.
  The following code might have some things that may not make sense as I was experimenting. Right now I almost reached the end of my capabilities as my knowledge in this area is not that great. Any help is very much appreciated
  My code files are as follows:</p>
  
  <p>Startup.cs:</p>
  
  <p>`</p>
  
  <pre><code>public Startup(IHostingEnvironment env)
  {
  var builder = new ConfigurationBuilder()
  .SetBasePath(env.ContentRootPath)
  .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
  .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
          if (env.IsDevelopment())
          {
              builder.AddUserSecrets();
          }
  
          _environment = env;
  
          builder.AddEnvironmentVariables();
          Configuration = builder.Build();
      }
  
      public IConfigurationRoot Configuration { get; }
  
      public void ConfigureServices(IServiceCollection services)
      {
          var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");
  
          services.AddMvc();
  
          services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
              options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));
  
          services.AddAuthentication();
  
          services.AddIdentity&lt;ApplicationUser, IdentityRole&gt;()
          .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;()
          .AddDefaultTokenProviders();
  
  
  
          services.AddTransient&lt;IProfileService, IdentityWithAdditionalClaimsProfileService&gt;();
  
          services.AddTransient&lt;IEmailSender, AuthMessageSender&gt;();
          services.AddTransient&lt;ISmsSender, AuthMessageSender&gt;();
  
      //    services.AddAuthentication();
          //var builder = services.AddIdentityServer(options =&gt;
          //{
          //    //options.
          //});
  
          services.AddDeveloperIdentityServer()
              .SetSigningCredential(cert)
              .AddInMemoryScopes(Config.GetScopes())
              .AddInMemoryClients(Config.GetClients())
              .AddInMemoryUsers(Config.GetUsers())
              .AddAspNetIdentity&lt;ApplicationUser&gt;()
              .AddProfileService&lt;IdentityWithAdditionalClaimsProfileService&gt;();
      }
  
      public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
      {
          var certificate = new X509Certificate2(@"D:\Downloads\AspNet5IdentityServerAngularImplicitFlow-master\AspNet5IdentityServerAngularImplicitFlow-master\src\IdentityServerWithIdentitySQLite\signingCertificate.CER");
  
          loggerFactory.AddConsole(Configuration.GetSection("Logging"));
          loggerFactory.AddDebug();
  
          if (env.IsDevelopment())
          {
              app.UseDeveloperExceptionPage();
              app.UseDatabaseErrorPage();
              app.UseBrowserLink();
          }
          else
          {
              app.UseExceptionHandler("/Home/Error");
          }
  
          //app.UseJwtBearerAuthentication(new JwtBearerOptions
          //{
          //    AutomaticAuthenticate = true,
          //    AutomaticChallenge = true,
          //    SaveToken = true,
          //    TokenValidationParameters = new TokenValidationParameters
          //    {
          //        //Iss     
          //        ValidateIssuer = true,
          //        ValidIssuer = "http://FSSTARS-BO-ADFS.linkedgaming.com/adfs/services/trust",
          //        //    ValidIssuer = "7fe2cdc6-4c2d-4d92-bac9-990df31f669c",
  
          //        ValidateAudience = true,
          //        ValidAudience = "microsoft:identityserver:StarsRelyingTrustProvider",
          //        ValidateIssuerSigningKey = true,
  
          //        IssuerSigningKey = new X509SecurityKey(certificate),
  
          //        ValidateLifetime = true,
          //        ClockSkew = TimeSpan.Zero
  
          //    },
          //});
  
          app.UseStaticFiles();
  
          app.UseIdentity();
  
          app.UseCookieAuthentication(new CookieAuthenticationOptions
          {
              AuthenticationScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
  
              AutomaticAuthenticate = false,
              AutomaticChallenge = false
          });
  
          app.UseOAuthAuthentication(new OAuthOptions()
          {
              DisplayName = "ADFS",
              //AutomaticAuthenticate = false,
              //AutomaticChallenge = false,
              AuthenticationScheme = "OAuth2",
              SignInScheme = IdentityServerConstants.ExternalCookieAuthenticationScheme,
              SaveTokens = true,
  
              //ClientId = "7fe2cdc6-4c2d-4d92-bac9-990df31f669c",
              ClientId = "9fe2cdc6-4c2d-4d92-bac9-990df31f669g",
              ClientSecret = "notneeded",
              CallbackPath = new            Microsoft.AspNetCore.Http.PathString("/About"),
              AuthorizationEndpoint = "https://fsstars-bo-adfs.linkedgaming.com/adfs/oauth2/authorize",
              TokenEndpoint = "https://fsstars-bo-adfs.linkedgaming.com/adfs/oauth2/token",
              Events = new OAuthEvents
              {
                  OnRedirectToAuthorizationEndpoint = context =&gt;
                  {
                      context.Response.Redirect($"{context.RedirectUri}&amp;resource=StarsRelyingTrustProvider");
                      return Task.FromResult(0);
                  }
              },
  
  
          });
  
          app.UseIdentityServer();
          app.UseMvc(routes =&gt;
          {
              routes.MapRoute(
                  name: "default",
                  template: "{controller=Home}/{action=Index}/{id?}");
          });
      }
  }
  }
  `
  </code></pre>
  
  <p>AccountController.cs:</p>
  
  <pre><code>`[Authorize]
  public class AccountController : Controller
  {
  public AccountController(
  IIdentityServerInteractionService interaction,
  IPersistedGrantService persistedGrantService,
  UserManager&lt;ApplicationUser&gt; userManager,
  SignInManager&lt;ApplicationUser&gt; signInManager,
  IEmailSender emailSender,
  ISmsSender smsSender,
  ILoggerFactory loggerFactory)
  {
  _interaction = interaction;
  _persistedGrantService = persistedGrantService;
  _userManager = userManager;
  _signInManager = signInManager;
  _emailSender = emailSender;
  _smsSender = smsSender;
  _logger = loggerFactory.CreateLogger&lt;AccountController&gt;();
  }
      //
      // GET: /Account/Login
      [HttpGet]
      [AllowAnonymous]
      public IActionResult Login(string returnUrl = null)
      {
          ViewData["ReturnUrl"] = returnUrl;
          return View();
      }
  
      //
      // POST: /Account/Login
      [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public async Task&lt;IActionResult&gt; Login(LoginViewModel model, string returnUrl = null)
      {
          ViewData["ReturnUrl"] = returnUrl;
          if (ModelState.IsValid)
          {
              // This doesn't count login failures towards account lockout
              // To enable password failures to trigger account lockout, set lockoutOnFailure: true
              var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false);
              if (result.Succeeded)
              {
                  _logger.LogInformation(1, "User logged in.");
                  return RedirectToLocal(returnUrl);
              }
              if (result.RequiresTwoFactor)
              {
                  return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
              }
              if (result.IsLockedOut)
              {
                  _logger.LogWarning(2, "User account locked out.");
                  return View("Lockout");
              }
              else
              {
                  ModelState.AddModelError(string.Empty, "Invalid login attempt.");
                  return View(model);
              }
          }
  
          // If we got this far, something failed, redisplay form
          return View(model);
      }
  
  
      //
      // POST: /Account/LogOff
      //[HttpPost]
      //[ValidateAntiForgeryToken]
      //public async Task&lt;IActionResult&gt; LogOff()
      //{
      //    await _signInManager.SignOutAsync();
      //    _logger.LogInformation(4, "User logged out.");
      //    return RedirectToAction(nameof(HomeController.Index), "Home");
      //}
  
      //
      // POST: /Account/ExternalLogin
      [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public IActionResult ExternalLogin(string provider, string returnUrl = null)
      {
          // Request a redirect to the external login provider.
          var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl });
          var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl);
          return Challenge(properties, provider);
      }
  
       //
      // GET: /Account/ExternalLoginCallback
      [HttpGet]
      [AllowAnonymous]
      public async Task&lt;IActionResult&gt; ExternalLoginCallback(
          string returnUrl = null, string remoteError = null)
      {
          if (remoteError != null)
          {
              ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}");
              return View(nameof(Login));
          }
          var info = await _signInManager.GetExternalLoginInfoAsync();
          if (info == null)
          {
              return RedirectToAction(nameof(Login));
          }
  
          // Sign in the user with this external login provider if the user already has a login.
          var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false);
          if (result.Succeeded)
          {
              _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider);
              return RedirectToLocal(returnUrl);
          }
          if (result.RequiresTwoFactor)
          {
              return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl });
          }
          if (result.IsLockedOut)
          {
              return View("Lockout");
          }
          else
          {
              // If the user does not have an account, then ask the user to create an account.
              ViewData["ReturnUrl"] = returnUrl;
              ViewData["LoginProvider"] = info.LoginProvider;
              var email = info.Principal.FindFirstValue(ClaimTypes.Email);
              return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email });
          }
      }
  
      //
      // POST: /Account/ExternalLoginConfirmation
      [HttpPost]
      [AllowAnonymous]
      [ValidateAntiForgeryToken]
      public async Task&lt;IActionResult&gt; ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null)
      {
          if (ModelState.IsValid)
          {
              // Get the information about the user from the external login provider
              var info = await _signInManager.GetExternalLoginInfoAsync();
              if (info == null)
              {
                  return View("ExternalLoginFailure");
              }
              var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
              var result = await _userManager.CreateAsync(user);
              if (result.Succeeded)
              {
                  result = await _userManager.AddLoginAsync(user, info);
                  if (result.Succeeded)
                  {
                      await _signInManager.SignInAsync(user, isPersistent: false);
                      _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider);
                      return RedirectToLocal(returnUrl);
                  }
              }
              AddErrors(result);
          }
  
          ViewData["ReturnUrl"] = returnUrl;
          return View(model);
      }
  
      // GET: /Account/ConfirmEmail
      [HttpGet]
      [AllowAnonymous]
      public async Task&lt;IActionResult&gt; ConfirmEmail(string userId, string code)
      {
          if (userId == null || code == null)
          {
              return View("Error");
          }
          var user = await _userManager.FindByIdAsync(userId);
          if (user == null)
          {
              return View("Error");
          }
          var result = await _userManager.ConfirmEmailAsync(user, code);
          return View(result.Succeeded ? "ConfirmEmail" : "Error");
      }
  
      /// &lt;summary&gt;
      /// Show logout page
      /// &lt;/summary&gt;
      [HttpGet]
      public IActionResult Logout(string logoutId)
      {
          var vm = new LogoutViewModel
          {
              LogoutId = logoutId
          };
  
          return View(vm);
      }
  
      /// &lt;summary&gt;
      /// Handle logout page postback
      /// &lt;/summary&gt;
      [HttpPost]
      [ValidateAntiForgeryToken]
      public async Task&lt;IActionResult&gt; Logout(LogoutViewModel model)
      {
          var user = HttpContext.User.Identity.Name;
          var subjectId = HttpContext.User.Identity.GetSubjectId();
  
          // delete authentication cookie
          await HttpContext.Authentication.SignOutAsync();
  
  
          // set this so UI rendering sees an anonymous user
          HttpContext.User = new ClaimsPrincipal(new ClaimsIdentity());
  
          // get context information (client name, post logout redirect URI and iframe for federated signout)
          var logout = await _interaction.GetLogoutContextAsync(model.LogoutId);
  
           var vm = new LoggedOutViewModel
          {
              PostLogoutRedirectUri = logout?.PostLogoutRedirectUri,
              ClientName = logout?.ClientId,
              SignOutIframeUrl = logout?.SignOutIFrameUrl
          };
  
  
          await _persistedGrantService.RemoveAllGrantsAsync(subjectId, "angular2client");
  
          return View("LoggedOut", vm);
      }
  
      #region Helpers
  
      private void AddErrors(IdentityResult result)
      {
          foreach (var error in result.Errors)
          {
              ModelState.AddModelError(string.Empty, error.Description);
          }
      }
  
      private Task&lt;ApplicationUser&gt; GetCurrentUserAsync()
      {
          return _userManager.GetUserAsync(HttpContext.User);
      }
  
      private IActionResult RedirectToLocal(string returnUrl)
      {
          if (Url.IsLocalUrl(returnUrl))
          {
              return Redirect(returnUrl);
          }
          else
          {
              return RedirectToAction(nameof(HomeController.Index), "Home");
          }
      }
  </code></pre>