/// <summary>
 /// This method gets called when the user uses an external identity provider to authenticate.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     return inner.AuthenticateExternalAsync(context);
 }
        public override Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            // look for the user in our local identity system from the external identifiers
            var user = Users.SingleOrDefault(x => x.Provider == context.ExternalIdentity.Provider && x.ProviderID == context.ExternalIdentity.ProviderId);
            string name = "Unknown";
            if (user == null)
            {
                // new user, so add them here
                var nameClaim = context.ExternalIdentity.Claims.First(x => x.Type == Constants.ClaimTypes.Name);
                if (nameClaim != null) name = nameClaim.Value;

                user = new CustomUser
                {
                    Subject = Guid.NewGuid().ToString(),
                    Provider = context.ExternalIdentity.Provider,
                    ProviderID = context.ExternalIdentity.ProviderId,
                    Claims = new List<Claim> { new Claim(Constants.ClaimTypes.Name, name) }
                };
                Users.Add(user);
            }

            name = user.Claims.First(x => x.Type == Constants.ClaimTypes.Name).Value;
            context.AuthenticateResult = new AuthenticateResult(user.Subject, name, identityProvider: user.Provider);
            
            return Task.FromResult(0);
        }
Пример #3
0
        public async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            var externalIdentity = Mapper.Map<IdentityServerExternalIdentity, DomainExternalIdentity>(context.ExternalIdentity);
            var signInData = Mapper.Map<SignInMessage, SignInData>(context.SignInMessage);
            var result = await domainService.AuthenticateExternalAsync(externalIdentity, signInData);

            context.AuthenticateResult = Mapper.Map<AuthenticationResult, AuthenticateResult>(result);
        }
        public override Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            var provider = context.ExternalIdentity.Provider;
            UserProfiles existingUser = null;
            switch(provider)
            {
                case "Facebook":
                    existingUser = dbContext.UserProfiles.FirstOrDefault(x => x.FacebookId == context.ExternalIdentity.ProviderId);
                    break;
                case "Google":
                    existingUser = dbContext.UserProfiles.FirstOrDefault(x => x.GoogleId == context.ExternalIdentity.ProviderId);
                    break;
            }

            if(existingUser == null)
            {
                var newUser = new UserProfiles();
                // Add other claims
                newUser.EmailAddress = context.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == IdentityServer3.Core.Constants.ClaimTypes.Email).Value;
                newUser.FirstName = context.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == IdentityServer3.Core.Constants.ClaimTypes.GivenName).Value;
                newUser.LastName = context.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == IdentityServer3.Core.Constants.ClaimTypes.FamilyName).Value;
                newUser.CreatedDate = DateTime.UtcNow;

                switch (provider)
                {
                    case "Facebook":
                        newUser.FacebookId = context.ExternalIdentity.ProviderId;
                        break;
                    case "Google":
                        newUser.GoogleId = context.ExternalIdentity.ProviderId;
                        break;
                }

                dbContext.UserProfiles.Add(newUser);
                dbContext.SaveChanges();

                existingUser = newUser;
            }

            // Add other claims
            List<Claim> existingUserClaims = new List<Claim>();
            existingUserClaims.Add(new Claim(ClaimTypes.Email, existingUser.EmailAddress));

            context.AuthenticateResult = new AuthenticateResult(
                existingUser.Id.ToString(),
                existingUser.FirstName,
                existingUserClaims,
                provider,
                provider);

            return Task.FromResult(0);
            //return base.AuthenticateExternalAsync(context);
        }
 public async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     context.AuthenticateResult = null;
     foreach (var service in this.services)
     {
         await service.AuthenticateExternalAsync(context);
         if (context.AuthenticateResult != null && !context.AuthenticateResult.IsError)
         {
             return;
         }
     }
 }
		/// <summary>
		/// This method gets called when the user uses an external identity provider to authenticate.
		/// </summary>
		/// <param name="context">The context.</param>
		/// <returns></returns>
		public override Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
		{
			var query =
				from u in _users
				where
					u.Provider == context.ExternalIdentity.Provider &&
					u.ProviderId == context.ExternalIdentity.ProviderId
				select u;

			var user = query.SingleOrDefault();
			if (user == null)
			{
				string displayName;

				var name = context.ExternalIdentity.Claims.FirstOrDefault(x => x.Type == Constants.ClaimTypes.Name);
				if (name == null)
				{
					displayName = context.ExternalIdentity.ProviderId;
				}
				else
				{
					displayName = name.Value;
				}

				user = new InMemoryUser
				{
					Subject = CryptoRandom.CreateUniqueId(),
					Provider = context.ExternalIdentity.Provider,
					ProviderId = context.ExternalIdentity.ProviderId,
					Username = displayName,
					Claims = context.ExternalIdentity.Claims
				};
				_users.Add(user);
			}

			// TEST CODE
			//List<Claim> claims = new List<Claim>()
			//{
			// new Claim(ClaimTypes.Upn, context.ExternalIdentity.ProviderId)
			//};

			context.AuthenticateResult = new AuthenticateResult(user.Subject, GetDisplayName(user), identityProvider: context.ExternalIdentity.Provider);

			return Task.FromResult(0);
		}
        public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            using (var client = await CreateClientAsync())
            {
                if (!(await ExternalUserExistsAsync(client, context.ExternalIdentity.ProviderId)))
                {
                    context.AuthenticateResult = await AddExternalUserAsync(client, context.ExternalIdentity);
                }
            }

            if (context.AuthenticateResult == null)
            {
                context.AuthenticateResult = new AuthenticateResult(
                    context.ExternalIdentity.ProviderId, 
                    GetDisplayName(context.ExternalIdentity.Claims) ?? context.ExternalIdentity.ProviderId, 
                    context.ExternalIdentity.Claims);
            }
        }
Пример #8
0
        public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            using (var client = new HttpClient { BaseAddress = new Uri(this.usersApiUri) })
            {
                if (!(await ExternalUserExistsAsync(client, context.ExternalIdentity.ProviderId)))
                {
                    context.AuthenticateResult = await AddExternalUserAsync(client, context.ExternalIdentity);
                }
            }

            if (context.AuthenticateResult == null)
            {
                context.AuthenticateResult = new AuthenticateResult(
                    context.ExternalIdentity.ProviderId, 
                    GetDisplayName(context.ExternalIdentity.Claims) ?? context.ExternalIdentity.ProviderId, 
                    context.ExternalIdentity.Claims);
            }
        }
        public override Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            var externalUser = context.ExternalIdentity;

            // look for the user in our local identity system from the external identifiers
            var user = Users.SingleOrDefault(x => x.Provider == externalUser.Provider && x.ProviderID == externalUser.ProviderId);
            if (user == null)
            {
                // user is not registered so redirect
                context.AuthenticateResult = new AuthenticateResult("~/registerfirstexternalregistration", externalUser);
            }
            else
            {
                // user is registered so continue
                var name = user.Claims.First(x => x.Type == Constants.ClaimTypes.Name).Value;
                context.AuthenticateResult = new AuthenticateResult(user.Subject, name, identityProvider: user.Provider);
            }
            
            return Task.FromResult(0);
        }
Пример #10
0
        public async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            if (context.ExternalIdentity == null)
                throw new ArgumentNullException("ExternalIdentity");

            var userLoginInfo = new UserLoginInfo(context.ExternalIdentity.Provider, context.ExternalIdentity.ProviderId);
            var user = await this.userManager.FindAsync(userLoginInfo);
            if (user == null)
            {
                // TODO log.WarnFormat("Unknown user '{0}' tries to login with external provider '{1}'", externalUser.ProviderId, externalUser.Provider);
                return;
            }

            var claims = await this.GetClaimsFromAccountAsync(user);
            var name = await this.GetDisplayNameForAccountAsync(user);
            context.AuthenticateResult = new AuthenticateResult(
                subject: user.Id.ToString(),
                name: name,
                claims: claims,
                identityProvider: context.ExternalIdentity.Provider,
                authenticationMethod: Constants.AuthenticationMethods.External);
        }
        public async Task<IHttpActionResult> ResumeLoginFromRedirect(string resume)
        {
            Logger.Info("Callback requested to resume login from partial login");

            if (resume.IsMissing())
            {
                Logger.Error("no resumeId passed");
                return RenderErrorPage();
            }

            if (resume.Length > MaxSignInMessageLength)
            {
                Logger.Error("resumeId length longer than allowed length");
                return RenderErrorPage();
            }

            var user = await context.GetIdentityFromPartialSignIn();
            if (user == null)
            {
                Logger.Error("no identity from partial login");
                return RenderErrorPage();
            }

            var type = GetClaimTypeForResumeId(resume);
            var resumeClaim = user.FindFirst(type);
            if (resumeClaim == null)
            {
                Logger.Error("no claim matching resumeId");
                return RenderErrorPage();
            }

            var signInId = resumeClaim.Value;
            if (signInId.IsMissing())
            {
                Logger.Error("No signin id found in resume claim");
                return RenderErrorPage();
            }

            var signInMessage = signInMessageCookie.Read(signInId);
            if (signInMessage == null)
            {
                Logger.Error("No cookie matching signin id found");
                return RenderErrorPage();
            }

            AuthenticateResult result = null;

            // determine which return path the user is taking -- are they coming from
            // a ExternalProvider partial logon, or not
            var externalProviderClaim = user.FindFirst(Constants.ClaimTypes.ExternalProviderUserId);

            // cleanup the claims from the partial login
            if (user.HasClaim(c => c.Type == Constants.ClaimTypes.PartialLoginRestartUrl))
            {
                user.RemoveClaim(user.FindFirst(Constants.ClaimTypes.PartialLoginRestartUrl));
            }
            if (user.HasClaim(c => c.Type == Constants.ClaimTypes.PartialLoginReturnUrl))
            {
                user.RemoveClaim(user.FindFirst(Constants.ClaimTypes.PartialLoginReturnUrl));
            }
            if (user.HasClaim(c => c.Type == Constants.ClaimTypes.ExternalProviderUserId))
            {
                user.RemoveClaim(user.FindFirst(Constants.ClaimTypes.ExternalProviderUserId));
            }
            if (user.HasClaim(c => c.Type == GetClaimTypeForResumeId(resume)))
            {
                user.RemoveClaim(user.FindFirst(GetClaimTypeForResumeId(resume)));
            }

            if (externalProviderClaim != null)
            {
                Logger.Info("using ExternalProviderUserId to call AuthenticateExternalAsync");

                var provider = externalProviderClaim.Issuer;
                var providerId = externalProviderClaim.Value;
                var externalIdentity = new ExternalIdentity
                {
                    Provider = provider,
                    ProviderId = providerId,
                    Claims = user.Claims
                };

                Logger.InfoFormat("external user provider: {0}, provider ID: {1}", externalIdentity.Provider, externalIdentity.ProviderId);

                var externalContext = new ExternalAuthenticationContext
                {
                    ExternalIdentity = externalIdentity,
                    SignInMessage = signInMessage
                };

                await userService.AuthenticateExternalAsync(externalContext);

                result = externalContext.AuthenticateResult;
                if (result == null)
                {
                    Logger.Warn("user service failed to authenticate external identity");

                    var msg = localizationService.GetMessage(MessageIds.NoMatchingExternalAccount);
                    await eventService.RaiseExternalLoginFailureEventAsync(externalIdentity, signInId, signInMessage, msg);

                    return await RenderLoginPage(signInMessage, signInId, msg);
                }

                if (result.IsError)
                {
                    Logger.WarnFormat("user service returned error message: {0}", result.ErrorMessage);

                    await eventService.RaiseExternalLoginFailureEventAsync(externalIdentity, signInId, signInMessage, result.ErrorMessage);

                    return await RenderLoginPage(signInMessage, signInId, result.ErrorMessage);
                }

                Logger.Info("External identity successfully validated by user service");

                await eventService.RaiseExternalLoginSuccessEventAsync(externalIdentity, signInId, signInMessage, result);
            }
            else
            {
                // check to see if the resultant user has all the claim types needed to login
                if (!Constants.AuthenticateResultClaimTypes.All(claimType => user.HasClaim(c => c.Type == claimType)))
                {
                    Logger.Error("Missing AuthenticateResultClaimTypes -- rendering error page");
                    return RenderErrorPage();
                }

                // this is a normal partial login continuation
                Logger.Info("Partial login resume success -- logging user in");

                result = new AuthenticateResult(new ClaimsPrincipal(user));

                await eventService.RaisePartialLoginCompleteEventAsync(result.User.Identities.First(), signInId, signInMessage);
            }

            return await SignInAndRedirectAsync(signInMessage, signInId, result);
        }
        public async Task<IHttpActionResult> LoginExternalCallback(string error = null)
        {
            Logger.Info("Callback invoked from external identity provider");
            
            if (error.IsPresent())
            {
                if (error.Length > options.InputLengthRestrictions.ExternalError) error = error.Substring(0, options.InputLengthRestrictions.ExternalError);

                Logger.ErrorFormat("External identity provider returned error: {0}", error);
                await eventService.RaiseExternalLoginErrorEventAsync(error);
                return RenderErrorPage(String.Format(localizationService.GetMessage(MessageIds.ExternalProviderError), error));
            }

            var signInId = await context.GetSignInIdFromExternalProvider();
            if (signInId.IsMissing())
            {
                Logger.Info("No signin id passed");
                return HandleNoSignin();
            }

            var signInMessage = signInMessageCookie.Read(signInId);
            if (signInMessage == null)
            {
                Logger.Info("No cookie matching signin id found");
                return HandleNoSignin();
            }

            var user = await context.GetIdentityFromExternalProvider();
            if (user == null)
            {
                Logger.Error("no identity from external identity provider");
                return await RenderLoginPage(signInMessage, signInId, localizationService.GetMessage(MessageIds.NoMatchingExternalAccount));
            }

            var externalIdentity = ExternalIdentity.FromClaims(user.Claims);
            if (externalIdentity == null)
            {
                var claims = user.Claims.Select(x => new { x.Type, x.Value });
                Logger.ErrorFormat("no subject or unique identifier claims from external identity provider. Claims provided:\r\n{0}", LogSerializer.Serialize(claims));
                return await RenderLoginPage(signInMessage, signInId, localizationService.GetMessage(MessageIds.NoMatchingExternalAccount));
            }

            Logger.InfoFormat("external user provider: {0}, provider ID: {1}", externalIdentity.Provider, externalIdentity.ProviderId);

            var externalContext = new ExternalAuthenticationContext
            {
                ExternalIdentity = externalIdentity,
                SignInMessage = signInMessage
            };

            await userService.AuthenticateExternalAsync(externalContext);
            
            var authResult = externalContext.AuthenticateResult;
            if (authResult == null)
            {
                Logger.Warn("user service failed to authenticate external identity");
                
                var msg = localizationService.GetMessage(MessageIds.NoMatchingExternalAccount);
                await eventService.RaiseExternalLoginFailureEventAsync(externalIdentity, signInId, signInMessage, msg);
                
                return await RenderLoginPage(signInMessage, signInId, msg);
            }

            if (authResult.IsError)
            {
                Logger.WarnFormat("user service returned error message: {0}", authResult.ErrorMessage);

                await eventService.RaiseExternalLoginFailureEventAsync(externalIdentity, signInId, signInMessage, authResult.ErrorMessage);
                
                return await RenderLoginPage(signInMessage, signInId, authResult.ErrorMessage);
            }

            Logger.Info("External identity successfully validated by user service");

            await eventService.RaiseExternalLoginSuccessEventAsync(externalIdentity, signInId, signInMessage, authResult);

            return await SignInAndRedirectAsync(signInMessage, signInId, authResult);
        }
 public override Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     return base.AuthenticateExternalAsync(context);
 }
Пример #14
0
 public async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     await this.innerUserService.AuthenticateExternalAsync(context);
 }
Пример #15
0
 public override async Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     var externalIdentity = context.ExternalIdentity;
     context.AuthenticateResult = await GetAppropriateAuthenticationResult(externalIdentity);
 }
        public Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
        {
            context.AuthenticateResult = new AuthenticateResult("robink", "Robin van der Knaap");

            return Task.FromResult(0);
        }
Пример #17
0
 public Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     context.AuthenticateResult = null;
     return Task.FromResult(0);
 }
Пример #18
0
 /// <summary>
 /// This method gets called when the user uses an external identity provider to authenticate.
 /// The user's identity from the external provider is passed via the `externalUser` parameter which contains the
 /// provider identifier, the provider's identifier for the user, and the claims from the provider for the external user.
 /// </summary>
 /// <param name="context">The context.</param>
 /// <returns></returns>
 public virtual Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     return Task.FromResult(0);
 }
 public Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     context.ExternalIdentity.Claims = filter.Filter(context.ExternalIdentity.Provider, context.ExternalIdentity.Claims);
     return inner.AuthenticateExternalAsync(context);
 }
 public override Task AuthenticateExternalAsync(ExternalAuthenticationContext context)
 {
     return Task.FromResult<AuthenticateResult>(null);
 }