public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } return(Ok()); }
public void CheckAuthenticatedInDataBase_UserAuthenticatedSuccess() { var signInStatus = Microsoft.AspNet.Identity.Owin.SignInStatus.Success; var AuthenticateResult = new AuthenticateResult(); var user = new User() { LastPasswordChangedDate = DateTime.Now }; var authenticateResult = ApplicationOAuthProvider.CheckAuthenticatedInDataBase(user, AuthenticateResult, signInStatus); Assert.AreEqual(true, authenticateResult.IsAuthenticated); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(PortoGoContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // In production mode set AllowInsecureHttp = false #if DEBUG AllowInsecureHttp = true #else AllowInsecureHttp = false #endif }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); } }
public void CheckUser_UserDisabled() { User user = new User() { UserName = "******", Active = false }; var generalSeetings = new GeneralSettingsApp(); var authenticateResult = ApplicationOAuthProvider.CheckUser(user, user.UserName, generalSeetings); Assert.AreEqual(false, authenticateResult.CheckUserIsOk); Assert.AreEqual("alerts:error.user_disabled", authenticateResult.MessageCode); }
public void Configuration(IAppBuilder app) { var oAuthProvider = new ApplicationOAuthProvider(LoginBusiness); var options = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = oAuthProvider }; app.UseOAuthAuthorizationServer(options); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); }
public void CheckUser_AuthenticateTypeActiveDirectoryEnabled() { User user = new User() { UserName = "******", Active = true, AuthenticationType = AuthenticationType.ActiveDirectory }; var generalSeetings = new GeneralSettingsApp() { AuthenticateActiveDirectory = true }; var authenticateResult = ApplicationOAuthProvider.CheckUser(user, user.UserName, generalSeetings); Assert.AreEqual(true, authenticateResult.CheckUserIsOk); }
static Startup() { PublicClientId = "self"; ExternalAuthPageUrl = "ExtAuthRequest"; var applicationOAuthProvider = new ApplicationOAuthProvider(PublicClientId, ExternalAuthPageUrl); OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/api/token"), Provider = applicationOAuthProvider, RefreshTokenProvider = applicationOAuthProvider, AuthorizeEndpointPath = new PathString("/api/account/externalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(30), AllowInsecureHttp = false }; }
public void CheckUser_AuthenticateTypeActiveDirectoryDisabled() { User user = new User() { UserName = "******", Active = true, AuthenticationType = AuthenticationType.ActiveDirectory }; var generalSeetings = new GeneralSettingsApp() { AuthenticateActiveDirectory = false }; var authenticateResult = ApplicationOAuthProvider.CheckUser(user, user.UserName, generalSeetings); Assert.AreEqual(false, authenticateResult.CheckUserIsOk); Assert.AreEqual("alerts:error.authentication_type_disabled", authenticateResult.MessageCode); }
public async Task <IHttpActionResult> Login(LoginInfoModel loginInfo) { if (!User.Identity.IsAuthenticated) { var user = await UserManager.FindAsync(loginInfo.Email, loginInfo.Password); ClaimsIdentity userIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, userIdentity, cookieIdentity); } return(Ok()); }
public void TestValidateFail3() { var provider = new ApplicationOAuthProvider("1"); var dict = new Dictionary <string, object>() { { "owin.RequestScheme", "http" }, { "Host", "localhost" }, { "owin.RequestPathBase", "/" }, { "owin.RequestPath", "" }, { "owin.RequestQueryString", "" }, { "owin.RequestHeaders", new Dictionary <string, string[]>() } }; var context = new OAuthValidateClientRedirectUriContext(new OwinContext(dict), new OAuthAuthorizationServerOptions(), "1", ""); provider.ValidateClientRedirectUri(context); Assert.IsFalse(context.IsValidated); }
public async Task <IHttpActionResult> ExternalLogin(string provider) { if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } string userId = await IdentityManager.Logins.GetUserIdForLoginAsync(externalLogin.LoginProvider, externalLogin.ProviderKey); bool hasRegistered = userId != null; if (hasRegistered) { Authentication.SignOut(Startup.ExternalCookieAuthenticationType); IEnumerable <Claim> claims = await ApplicationOAuthProvider.GetClaimsAsync(IdentityManager, userId); ClaimsIdentity oAuthIdentity = ApplicationOAuthProvider.CreateIdentity(IdentityManager, claims, OAuthOptions.AuthenticationType); ClaimsIdentity cookieIdentity = ApplicationOAuthProvider.CreateIdentity(IdentityManager, claims, CookieOptions.AuthenticationType); AuthenticationProperties properties = await ApplicationOAuthProvider.CreatePropertiesAsync( IdentityManager, userId); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = ApplicationOAuthProvider.CreateIdentity(IdentityManager, claims, OAuthOptions.AuthenticationType); Authentication.SignIn(identity); } return(Ok()); }
private async Task <AuthenticationProperties> CreateInitialRefreshToken(string clientId, ApplicationUser user, ClaimsIdentity oAuthIdentity) { var userOrganization = new UserAndOrganizationDto { OrganizationId = user.OrganizationId, UserId = user.Id }; await _refreshTokenService.RemoveTokenBySubjectAsync(userOrganization); var properties = ApplicationOAuthProvider.CreateProperties(user.Id, clientId); var ticket = new AuthenticationTicket(oAuthIdentity, properties); var context = new AuthenticationTokenCreateContext(Request.GetOwinContext(), Startup.OAuthServerOptions.RefreshTokenFormat, ticket); await Startup.OAuthServerOptions.RefreshTokenProvider.CreateAsync(context); properties.Dictionary.Add("refresh_token", context.Token); return(properties); }
public void CheckAuthenticatedInDataBase_UserPasswordNotExpired() { var signInStatus = Microsoft.AspNet.Identity.Owin.SignInStatus.Success; var AuthenticateResult = new AuthenticateResult(); var settings = new GeneralSettingsApp { PasswordExpiresInDays = 2 }; SettingHelper.AddInCache(settings); var user = new User() { AuthenticationType = AuthenticationType.DataBase, LastPasswordChangedDate = DateTime.Now.Date.AddDays(-1) }; var authenticateResult = ApplicationOAuthProvider.CheckAuthenticatedInDataBase(user, AuthenticateResult, signInStatus); Assert.AreEqual(true, authenticateResult.IsAuthenticated); }
public void CheckAuthenticatedInDataBase_UserPasswordExpired() { var signInStatus = Microsoft.AspNet.Identity.Owin.SignInStatus.Success; var AuthenticateResult = new AuthenticateResult(); var settings = new GeneralSettingsApp { PasswordExpiresInDays = 1 }; SettingHelper.AddInCache(settings); var user = new User() { AuthenticationType = AuthenticationType.DataBase, LastPasswordChangedDate = DateTime.Now.Date.AddDays(-(SettingHelper.Get().PasswordExpiresInDays + 1)) }; var authenticateResult = ApplicationOAuthProvider.CheckAuthenticatedInDataBase(user, AuthenticateResult, signInStatus); Assert.AreEqual(false, authenticateResult.IsAuthenticated); Assert.AreEqual("alerts:warning.user_password_expired", authenticateResult.MessageCode); }
public async Task SignInAsync(ApplicationUser user, bool isPersistent, bool rememberBrowser) { // Clear any partial cookies from external or two factor partial sign ins AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie); var oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager); var cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); var properties = ApplicationOAuthProvider.CreateProperties(user.UserName, isPersistent); if (rememberBrowser) { var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(user.Id); AuthenticationManager.SignIn(properties, oAuthIdentity, cookieIdentity, rememberBrowserIdentity); } else { AuthenticationManager.SignIn(properties, oAuthIdentity, cookieIdentity); } }
public void Configuration(IAppBuilder app) { // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888 var myProvider = new ApplicationOAuthProvider(); OAuthOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(10), //10 minutes for the expiration of login (unverified) token (which represents the verification code life time) Provider = myProvider }; app.UseOAuthAuthorizationServer(OAuthOptions); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); VerifiedAccessTokenExpireTimeSpan = TimeSpan.FromHours(4); //The expiration of the verified token HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); }
public async Task <IHttpActionResult> Login(LoginViewModel loginVM) { ApplicationUser user = UserManager.Find(loginVM.Username, loginVM.Password); if (user != null) { if (!user.EmailConfirmed) { ModelState.AddModelError("", "Niste aktivirali profil"); return(BadRequest(ModelState)); } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); try { ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); var role = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.Role).FirstOrDefault().Value; var userId = oAuthIdentity.Claims.Where(c => c.Type == ClaimTypes.NameIdentifier).FirstOrDefault().Value; AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName, role, userId); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); return(Ok(properties.Dictionary)); } catch (Exception) { return(BadRequest()); } } else { ModelState.AddModelError("", "Ne postoji korisnik sa unetim Email-om i Å¡ifrom"); return(BadRequest(ModelState)); } }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll); // get some identity var provider = new ApplicationOAuthProvider(); // apply settings to provider OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = provider }; //user this identity app.UseOAuthAuthorizationServer(option); app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()); HttpConfiguration config = new HttpConfiguration(); WebApiConfig.Register(config); }
public async Task <IHttpActionResult> LoginWithExternalToken(LoginWithExternalTokenBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // validate token ExternalLoginData externalLogin = await FromToken(model.Provider, model.ExternalToken); if (externalLogin == null) { return(BadRequest("External login could not be found")); } if (externalLogin.LoginProvider != model.Provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(BadRequest("Login provider does not match")); } var passedLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey); // if we reached this point then token is valid, so query the user var user = await UserManager.FindAsync(passedLoginInfo); bool hasRegistered = user != null; if (!hasRegistered) { return(BadRequest("User has not been registered yet, must be a business error.")); } else { ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, user.UserName)); oAuthIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id)); AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, new AuthenticationProperties()); DateTime currentUtc = DateTime.UtcNow; ticket.Properties.IssuedUtc = currentUtc; ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromDays(365)); string accessToken = Startup.OAuthOptions.AccessTokenFormat.Protect(ticket); Request.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", accessToken); int expiryInDays = int.Parse(ConfigurationManager.AppSettings["TokenExpiryInDays"]); // Create the response building a JSON object that mimics exactly the one issued by the default /Token endpoint JObject token = new JObject( new JProperty("userName", user.UserName), new JProperty("access_token", accessToken), new JProperty("token_type", "bearer"), new JProperty("expires_in", TimeSpan.FromDays(expiryInDays).TotalSeconds.ToString()), new JProperty("issued", currentUtc.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", CultureInfo.InvariantCulture)), new JProperty("expires", currentUtc.Add(TimeSpan.FromDays(expiryInDays)).ToString("ddd, dd MMM yyyy HH:mm:ss 'GMT'", CultureInfo.InvariantCulture)) ); return(Ok(token)); } }
public void TestConstructorArgNull() { var provider = new ApplicationOAuthProvider(null); }
public void TestConstructor() { var provider = new ApplicationOAuthProvider(""); }
public async Task <ActionResult> ExternalLoginCallback(string returnUrl) { var result = await AuthenticationManager.AuthenticateAsync(DefaultAuthenticationTypes.ExternalCookie); if (result?.Identity == null) { return(RedirectToAction("Login")); } var idClaim = result.Identity.FindFirst(ClaimTypes.NameIdentifier); if (idClaim == null) { return(RedirectToAction("Login")); } var login = new UserLoginInfo(idClaim.Issuer, idClaim.Value); // Sign in the user with this external login provider if the user already has a login ApplicationUser user = await UserManager.FindAsync(login); if (user != null) { ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); user.LastConsent = DateTime.UtcNow; await UserManager.UpdateAsync(user); return(RedirectToLocal(returnUrl)); } else { RegisterExternalBindingModel model = new RegisterExternalBindingModel(); if (idClaim.Issuer == "Facebook") { // Get details from Facebook var accessToken = result.Identity.Claims.Where(c => c.Type.Equals("ExternalAccessToken")).Select(c => c.Value).FirstOrDefault(); Uri apiRequestUri = new Uri("https://graph.facebook.com/me?fields=id,first_name,last_name,email,picture.type(square)&access_token=" + accessToken); using (var webClient = new WebClient()) { var json = webClient.DownloadString(apiRequestUri); dynamic jsonResult = JsonConvert.DeserializeObject(json); model.Email = jsonResult.email; model.Given_name = jsonResult.first_name; model.Family_name = jsonResult.last_name; model.Picture = jsonResult.picture.data.url; } } else { // Get details from Google var accessToken = result.Identity.Claims.Where(c => c.Type.Equals("urn:google:accesstoken")).Select(c => c.Value).FirstOrDefault(); Uri apiRequestUri = new Uri("https://www.googleapis.com/oauth2/v2/userinfo?access_token=" + accessToken); using (var webClient = new WebClient()) { var json = webClient.DownloadString(apiRequestUri); dynamic jsonResult = JsonConvert.DeserializeObject(json); model.Email = jsonResult.email; model.Picture = jsonResult.picture; model.Family_name = jsonResult.family_name; model.Given_name = jsonResult.given_name; } } var appUser = new ApplicationUser { UserName = model.Email, Email = model.Email, ImageUrl = model.Picture, FirstName = model.Given_name, Surname = model.Family_name, DateCreated = DateTime.UtcNow, AuthProvider = idClaim.Issuer, Trusted = false, LastConsent = DateTime.UtcNow }; ApplicationUser existingResult = await UserManager.FindByEmailAsync(appUser.Email); if (existingResult == null) { // New user IdentityResult createResult = await UserManager.CreateAsync(appUser); if (!createResult.Succeeded) { return(RedirectToAction("Login")); } } else { // user already exists with that email appUser = existingResult; } // Add this oauth login to the user account IdentityResult idResult = await UserManager.AddLoginAsync(appUser.Id, login); if (!idResult.Succeeded) { return(RedirectToAction("Login")); } ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await appUser.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(appUser.UserName); await SignInManager.SignInAsync(appUser, true, true); Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); return(RedirectToLocal(returnUrl)); } }
public async Task <ActionResult> HandleResponseFromApple(InitialTokenResponse response) { try { // TODO should probably check state here but MVC seems to have different session IDs for each request yay // Create a new instance of AppleAuthProvider AppleAuthProvider provider = new AppleAuthProvider( ConfigurationManager.AppSettings["oauth:apple:id"], ConfigurationManager.AppSettings["oauth:apple:teamid"], ConfigurationManager.AppSettings["oauth:apple:keyid"], string.Format("https://{0}/account/HandleResponseFromApple", Request.Url.Authority), Session.SessionID); // Retrieve an authorization token AuthorizationToken authorizationToken = await provider.GetAuthorizationToken(response.code, ConfigurationManager.AppSettings["oauth:apple:secret"]); var login = new UserLoginInfo("Apple", authorizationToken.UserInformation.UserID); ApplicationUser user = await UserManager.FindAsync(login); // apple only returns the user's details on the first authentication if (user == null && !string.IsNullOrWhiteSpace(response.user)) { dynamic appleUser = JsonConvert.DeserializeObject(response.user); ApplicationUser appUser = new ApplicationUser { UserName = appleUser.email, Email = appleUser.email, FirstName = appleUser.name.firstName, Surname = appleUser.name.lastName, DateCreated = DateTime.UtcNow, AuthProvider = "Apple", Trusted = false, LastConsent = DateTime.UtcNow }; ApplicationUser existingResult = await UserManager.FindByEmailAsync(appUser.Email); if (existingResult == null) { // New user IdentityResult createResult = await UserManager.CreateAsync(appUser); if (!createResult.Succeeded) { return(RedirectToAction("Login")); } } else { // user already exists with that email appUser = existingResult; } // Add this oauth login to the user account IdentityResult idResult = await UserManager.AddLoginAsync(appUser.Id, login); if (!idResult.Succeeded) { return(RedirectToAction("Login")); } ClaimsIdentity oAuthIdentity = await appUser.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await appUser.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(appUser.UserName); await SignInManager.SignInAsync(appUser, true, true); Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); return(RedirectToLocal("/")); } else if (user != null) { // existing user ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Request.GetOwinContext().Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); user.LastConsent = DateTime.UtcNow; await UserManager.UpdateAsync(user); return(RedirectToLocal("/")); } else { // new user but apple didn't give details // TODO show instructions for removing ourplace from your apple account so that it can be re-added ViewData["errormessage"] = "Something went wrong while getting your details from Apple. Please remove OurPlace from your 'Sign in with Apple' security settings and try again."; return(View("Error")); } } catch (Exception e) { Console.WriteLine(e.Message); ViewData["errormessage"] = string.Format("HandleResponseFromApple\nkey{2}\n{0}\n{1}", e.Message, e.StackTrace, ConfigurationManager.AppSettings["oauth:apple:secret"]); return(View("Error")); } }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app, Func <ApplicationUserManager> userManagerFactory) { // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId, userManagerFactory), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // In production mode set AllowInsecureHttp = false #if DEBUG AllowInsecureHttp = true #else AllowInsecureHttp = false #endif }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); #region ExternalSign // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // (xdinos) // Commented out from original template. // But we keep them for possible future expansion //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); //// Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. //app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); //// Enables the application to remember the second login verification factor such as phone or email. //// Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. //// This is similar to the RememberMe option when you log in. //app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); #endregion } }
public async Task <IHttpActionResult> RegisterWithExternalToken(LoginWithExternalTokenBindingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } // validate token ExternalLoginData externalLogin = await FromToken(model.Provider, model.ExternalToken); if (externalLogin == null) { return(BadRequest("External login could not be found")); } if (externalLogin.LoginProvider != model.Provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(BadRequest("Login provider does not match")); } var passedLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey); // if we reached this point then token is valid, so query the user var user = await UserManager.FindAsync(passedLoginInfo); bool hasRegistered = user != null; if (!hasRegistered) { // the user has not been registered into the database yet // first we need to retrieve info for the user and register him/her user = await RetrieveUserDetailsWithProvider(model.Provider, model.ExternalToken); var result = await UserManager.CreateAsync(user); if (result.Succeeded) { var userLoginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey); result = await UserManager.AddLoginAsync(user.Id, userLoginInfo); if (result.Succeeded) { // TODO: gseng - add this user to the "asp_net_user_roles" table AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties); } } } else { AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties); } return(Ok()); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { string redirectUri = string.Empty; if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } var redirectUriValidationResult = ValidateClientAndRedirectUri(this.Request, ref redirectUri); if (!string.IsNullOrWhiteSpace(redirectUriValidationResult)) { return(BadRequest(redirectUriValidationResult)); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); Authentication.SignIn(identity); } //redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}", // redirectUri, // externalLogin.ExternalAccessToken, // externalLogin.LoginProvider, // hasRegistered.ToString(), // externalLogin.UserName); redirectUri = string.Format("{0}#external_access_token={1}&provider={2}&haslocalaccount={3}&external_user_name={4}", redirectUri, externalLogin.ExternalAccessToken, externalLogin.LoginProvider, hasRegistered.ToString(), externalLogin.UserName); return(Redirect(redirectUri)); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } var loginInfo = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey); ISofAUser user = await UserManager.FindAsync(loginInfo); bool hasRegistered = user != null; if (!hasRegistered) { var info = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey); user = new ISofAUser() { UserName = (User.Identity as ClaimsIdentity).FindFirstValue(ClaimTypes.Name), Email = (User.Identity as ClaimsIdentity).FindFirstValue(ClaimTypes.Email) }; IdentityResult result = await UserManager.CreateAsync(user); if (!result.Succeeded) { return(GetErrorResult(result)); } result = await UserManager.AddLoginAsync(user.Id, loginInfo); if (!result.Succeeded) { return(GetErrorResult(result)); } } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); return(Ok()); }
public async Task <IHttpActionResult> GetGitHubToken(string githubCode) { var config = GitHubAuthorizationConfiguration.CreateDefault(); string responseString = ""; using (var webClient = new WebClient()) { webClient.Headers.Add("Accept", "application/json"); responseString = webClient.UploadString(config.GetTokenEndpoint(), config.GetTokenEndpointParameters(githubCode)); } var responseDefiniton = new { token_type = "", scope = "", access_token = "" }; var response = JsonConvert.DeserializeAnonymousType(responseString, responseDefiniton); var accessToken = response.access_token; string userInformationString = ""; using (var webClient = new WebClient()) { webClient.Headers.Add("Accept", "application/json"); // Set a User-Agent ... any User-Agent..... , otherwise receive a 403 Unauthorized.... yup! webClient.Headers.Add("User-Agent", "Y U require this header, github? this cost me some 30 minutes!"); userInformationString = webClient.DownloadString(string.Format("https://api.github.com/user?access_token={0}", accessToken)); } ApplicationUser user = JsonConvert.DeserializeObject <ApplicationUser>(userInformationString); user.CheckAndRepairUselessRequiredFields(); ApplicationUser exisitingUser = await UserManager.FindByNameAsync(user.UserName); if (exisitingUser != null) { exisitingUser.AvatarUrl = user.AvatarUrl; exisitingUser.Email = user.Email; exisitingUser.GitHubId = user.GitHubId; exisitingUser.HtmlUrl = user.HtmlUrl; exisitingUser.RepositoriesUrl = user.RepositoriesUrl; exisitingUser.Url = user.Url; IdentityResult idr = await UserManager.UpdateAsync(exisitingUser); } else { await UserManager.CreateAsync(user); exisitingUser = await UserManager.FindByNameAsync(user.UserName); } await AddExternalLogin(exisitingUser, accessToken); ClaimsIdentity oAuthIdentity = await exisitingUser.GenerateUserIdentityAsync(UserManager, DefaultAuthenticationTypes.ExternalBearer); AuthenticationProperties authProperties = ApplicationOAuthProvider.CreateProperties(exisitingUser.UserName); oAuthIdentity.AddClaims(new Claim[] { new Claim(ClaimTypes.NameIdentifier, accessToken), new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "ASP.NET Identity", "http://www.w3.org/2001/XMLSchema#string"), new Claim(ClaimTypes.Name, exisitingUser.UserName), new Claim("Certificate", accessToken), }); Authentication.SignIn(new AuthenticationProperties { IsPersistent = false, }, oAuthIdentity); return(Ok(new { Token = accessToken, user = exisitingUser })); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null || externalLogin.LoginProvider != provider) { Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType); return(Redirect(Url.Content("~/"))); } IdentityAccount account = await _userManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); if (account == null) { IdentityResult result = null; account = await _userManager.FindByNameAsync(externalLogin.UserName); if (account == null) { account = new IdentityAccount { UserName = externalLogin.UserName }; result = await _userManager.CreateAsync(account); if (!result.Succeeded) { return(InternalServerError()); } } UserLoginInfo login = new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey); result = await _userManager.AddLoginAsync(account.Id, login); if (!result.Succeeded) { return(InternalServerError()); } } Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await _userManager.CreateIdentityAsync(account, OAuthDefaults.AuthenticationType); ClaimsIdentity cookieIdentity = await _userManager.CreateIdentityAsync(account, CookieAuthenticationDefaults.AuthenticationType); AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(account.UserName); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); return(Ok()); }
public async Task <IHttpActionResult> GetExternalLogin(string provider, string error = null) { if (error != null) { return(Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error))); } if (!User.Identity.IsAuthenticated) { return(new ChallengeResult(provider, this)); } ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity); if (externalLogin == null) { return(InternalServerError()); } if (externalLogin.LoginProvider != provider) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); return(new ChallengeResult(provider, this)); } ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider, externalLogin.ProviderKey)); bool hasRegistered = user != null; var otheruser = Request.GetOwinContext().Authentication.User; string googleAccessToken = null; if (otheruser.Claims.Any(cl => cl.Type.ToLower().Contains("emailaddress"))) { using (var appdbcontext = new ApplicationDbContext()) { var userEmail = otheruser.Claims.First(cl => cl.Type.ToLower().Contains("emailaddress")).Value; var googleExternalLoginData = appdbcontext.ExternalLoginDatas.FirstOrDefault(eld => eld.Type == "GoogleAccessToken" && eld.Key == userEmail); googleAccessToken = googleExternalLoginData.Value; } } if (hasRegistered) { Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie); ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager, OAuthDefaults.AuthenticationType); if (!string.IsNullOrEmpty(googleAccessToken)) { oAuthIdentity.AddClaim(new Claim("GoogleAccessToken", googleAccessToken)); } ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager, CookieAuthenticationDefaults.AuthenticationType); if (!string.IsNullOrEmpty(googleAccessToken)) { cookieIdentity.AddClaim(new Claim("GoogleAccessToken", googleAccessToken)); } AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user); Authentication.SignIn(properties, oAuthIdentity, cookieIdentity); } else { IEnumerable <Claim> claims = externalLogin.GetClaims(); ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType); if (!string.IsNullOrEmpty(googleAccessToken)) { identity.AddClaim(new Claim("GoogleAccessToken", googleAccessToken)); } Authentication.SignIn(identity); } return(Ok()); }