Exemple #1
0
        public async Task <IHttpActionResult> GetLocalExternalAccessToken(string provider, string externalAccessToken, string client_id, string client_secret = "")
        {
            if (string.IsNullOrWhiteSpace(provider) || string.IsNullOrWhiteSpace(externalAccessToken))
            {
                return(BadRequest("Provider or external access token is not sent"));
            }
            KeyValuePair <string, Func <ITokenInfo> > searchExternalProvider;

            try
            {
                searchExternalProvider = WebApiApplication.TokenInfoList.First(x => x.Key == provider);
            }
            catch (InvalidOperationException)
            {
                ModelState.AddModelError("Provider", GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                return(BadRequest(ModelState));
            }
            var instance = searchExternalProvider.Value.Invoke();
            var verifiedTokenExternal = await instance.Get(externalAccessToken);

            if (verifiedTokenExternal == null)
            {
                ModelState.AddModelError(GenericNames.AUTHENTICATION_EXTERNAL_LOGIN, GenericError.INVALID_GIVEN_PARAMETER);
                return(BadRequest(ModelState));
            }
            Client userClient = await Manager.FindAsync(new UserLoginInfo(provider, verifiedTokenExternal.user_id));

            if (userClient == null)
            {
                ModelState.AddModelError("Client", GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                return(BadRequest(ModelState));
            }
            Service service = null;

            try
            {
                service = await AuthenticationTools.GetServiceActiveAndExists(Request.GetOwinContext().Get <ManahostManagerDAL>(), client_id, client_secret);
            }
            catch (AuthenticationToolsException e)
            {
                ModelState.AddModelError(e.Key, e.Value);
                return(BadRequest(ModelState));
            }
            var ticket = AuthenticationTools.GenerateTicket(OAuthDefaults.AuthenticationType, client_id, userClient);
            var accessTokenExternal = AuthenticationTools.GenerateToken(ticket, userClient);

            return(OkWithHeader(accessTokenExternal, new Dictionary <string, string>()
            {
                { GenericNames.OWIN_CONTEXT_CORS_HEADER, service.AllowedOrigin }
            }));
        }
Exemple #2
0
        /// <summary>
        /// Methode qui sert à la vérification de l'authentification du client
        /// </summary>
        /// <param name="context">Le context de la requête et d'autre information utiles à la gestions du service</param>
        /// <returns></returns>
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            IDependencyScope  Scope        = context.OwinContext.Get <IDependencyScope>();
            ClientUserManager manager      = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
            ClientRoleManager managerRoles = Scope.GetService(typeof(ClientRoleManager)) as ClientRoleManager;

            /*ClientUserManager manager = context.OwinContext.GetUserManager<ClientUserManager>();
             * ClientRoleManager managerRoles = context.OwinContext.Get<ClientRoleManager>();*/

            var AllowOriginCORS      = context.OwinContext.Get <string>(GenericNames.OWIN_CONTEXT_CORS);
            var attempt              = Convert.ToInt32(ConfigurationManager.AppSettings[GenericNames.CAPTCHA_FAILED_COUNT]);
            int RefreshTokenLifeTime = context.OwinContext.Get <int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME);

            if (AllowOriginCORS == null)
            {
                AllowOriginCORS = "*";
            }

            context.OwinContext.Response.Headers.Remove(GenericNames.OWIN_CONTEXT_CORS_HEADER);
            context.OwinContext.Response.Headers.Add(GenericNames.OWIN_CONTEXT_CORS_HEADER, new[] { AllowOriginCORS });

            Client user = await manager.FindAsync(context.UserName, context.Password);

            if (user == null)
            {
                Client FindByEmail = await manager.FindByEmailAsync(context.UserName);

                if (FindByEmail != null)
                {
                    FindByEmail.AccessFailedCount++;
                    FindByEmail.LastAttemptConnexion = DateTime.UtcNow;
                    await manager.UpdateAsync(FindByEmail);

                    if (FindByEmail.AccessFailedCount > attempt)
                    {
                        context.SetError("captcha", GenericError.NEED_CAPTCHA);
                        return;
                    }
                }
                context.SetError("invalid_grant", GenericError.INVALID_GIVEN_PARAMETER);
                return;
            }
            if (!user.EmailConfirmed)
            {
                context.SetError("email_confirmation", GenericError.EMAIL_NOT_CONFIRMED);
                return;
            }
            if (user.LockoutEnabled)
            {
                context.SetError("client", GenericError.ACCOUNT_DISABLED);
                return;
            }

            AuthenticationTicket ticket = null;

            if (user.AccessFailedCount > attempt)
            {
                var data = await context.Request.ReadFormAsync();

                var Code = data[GenericNames.GOOGLE_RECAPTCHA_FORM];
                if (Code == null)
                {
                    context.SetError("captcha", GenericError.CAPTCHA_MISSING_RESPONSE);
                    return;
                }
                else
                {
                    ICaptchaTools tools       = GoogleReCaptchValidator.Create();
                    var           testCaptcha = await tools.VerifyCaptcha(Code, context.Request.RemoteIpAddress);

                    if (testCaptcha)
                    {
                        user.AccessFailedCount = 0;
                        await manager.UpdateAsync(user);

                        ticket = AuthenticationTools.GenerateTicket(context.Options.AuthenticationType, context.ClientId, user, RefreshTokenLifeTime);
                    }
                    else
                    {
                        context.SetError("captcha", GenericError.CAPTCHA_INVALID_SOLUTION);
                        return;
                    }
                }
            }
            else
            {
                ticket = AuthenticationTools.GenerateTicket(context.Options.AuthenticationType, context.ClientId, user, RefreshTokenLifeTime);
            }

            context.Validated(ticket);
        }
Exemple #3
0
        public async Task <IHttpActionResult> PostRegisterExternel(RegisterExternalBindingModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            KeyValuePair <string, Func <ITokenInfo> > searchExternalProvider;

            try
            {
                searchExternalProvider = WebApiApplication.TokenInfoList.First(x => x.Key == model.Provider);
            }
            catch (InvalidOperationException)
            {
                ModelState.AddModelError("Provider", GenericError.FORBIDDEN_RESOURCE_OR_DOES_NO_EXIST);
                return(BadRequest(ModelState));
            }
            var instance    = searchExternalProvider.Value.Invoke();
            var parsedToken = await instance.Get(model.ExternalAccessToken);

            if (parsedToken == null)
            {
                ModelState.AddModelError(GenericNames.AUTHENTICATION_EXTERNAL_LOGIN, GenericError.INVALID_GIVEN_PARAMETER);
                return(BadRequest(ModelState));
            }
            Client user = await Manager.FindAsync(new UserLoginInfo(model.Provider, parsedToken.user_id));

            if (user != null)
            {
                ModelState.AddModelError("Client", GenericError.ALREADY_EXISTS);
                return(BadRequest(ModelState));
            }

            var informationUser = await instance.GetUserInfo(model.ExternalAccessToken);

            var client       = Factory.Create(informationUser);
            var resultClient = await Manager.CreateAsync(client);

            if (!resultClient.Succeeded)
            {
                //TODO ERROR
                return(BadRequest());
            }
            var ResultLoginClient = await Manager.AddLoginAsync(client.Id, new UserLoginInfo(model.Provider, parsedToken.user_id));

            if (!ResultLoginClient.Succeeded)
            {
                //TODO ERROR
                return(BadRequest());
            }
            Service service = null;

            try
            {
                service = await AuthenticationTools.GetServiceActiveAndExists(Request.GetOwinContext().Get <ManahostManagerDAL>(), model.client_id, model.client_secret);
            }
            catch (AuthenticationToolsException e)
            {
                ModelState.AddModelError(e.Key, e.Value);
                return(BadRequest(ModelState));
            }
            var ticket = AuthenticationTools.GenerateTicket(OAuthDefaults.AuthenticationType, model.client_id, client);
            var accessTokenExternal = AuthenticationTools.GenerateToken(ticket, client);

            return(OkWithHeader(accessTokenExternal, new Dictionary <string, string>()
            {
                { GenericNames.OWIN_CONTEXT_CORS_HEADER, service.AllowedOrigin }
            }));
        }