public async Task <IHttpActionResult> AddExternalLoginCallback(string userId, string error = null, string returnUrl = "") { Uri returnUri = new Uri(!string.IsNullOrEmpty(returnUrl) ? returnUrl : CORSConfig.returnOrigin); string returnHost = returnUri.GetLeftPart(UriPartial.Authority); ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (error != null) { return(Redirect(returnHost + "/unauthorized")); } if (externalLogin == null) { return(Redirect(returnHost + "/unauthorized")); } if (externalLogin.LoginProvider == "Steam") { string steamId = SteamServiceProvider.SteamUserId(externalLogin.ProviderKey); ApplicationUser user = _dbContext.Users.FirstOrDefault(u => u.SteamID == steamId); if (user != null && user.Id != userId) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(Redirect(returnHost + "/unauthorized/Steam account already associated with another user")); } if (user == null) { user = _dbContext.Users.Find(userId); } user.SteamID = steamId; try { _dbContext.SaveChanges(); } catch (Exception e) { System.Diagnostics.Trace.TraceError("Setting user steam id exception: " + e.Message); } } IdentityResult result = await UserManager.AddLoginAsync(userId, new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)).ConfigureAwait(false); if (!result.Succeeded) { return(Redirect(returnHost + "/unauthorized")); } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(Redirect(returnUrl)); }
// POST api/Account/RegisterExternal //[OverrideAuthentication] //[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)] //[Route("RegisterExternal")] //public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model) //{ // if (!ModelState.IsValid) // { // return BadRequest(ModelState); // } // var info = await Authentication.GetExternalLoginInfoAsync(); // if (info == null) // { // return InternalServerError(); // } // var user = new ApplicationUser() { UserName = model.Email, Email = model.Email }; // IdentityResult result = await UserManager.CreateAsync(user); // if (!result.Succeeded) // { // return GetErrorResult(result); // } // result = await UserManager.AddLoginAsync(user.Id, info.Login); // if (!result.Succeeded) // { // return GetErrorResult(result); // } // return Ok(); //} #region Helpers private async Task <IdentityResult> Register(ExternalLoginData info) { string id = info.LoginProvider == "Steam" ? SteamServiceProvider.SteamUserId(info.ProviderKey) : Guid.NewGuid().ToString(); string steamId = info.LoginProvider == "Steam" ? id : null; var user = new ApplicationUser() { Id = id, UserName = User.Identity.Name, SteamID = steamId }; IdentityResult result = await UserManager.CreateAsync(user).ConfigureAwait(false); if (!result.Succeeded) { return(result); } return(await UserManager.AddLoginAsync(user.Id, new UserLoginInfo(info.LoginProvider, info.ProviderKey)).ConfigureAwait(false)); }