Example #1
0
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException("actionContext");
            }

            IPrincipal user = actionContext.ControllerContext.RequestContext.Principal;

            if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
            {
                return(false);
            }
            if (Users.Length > 0 && !(Users.IndexOf(user.Identity.Name, StringComparison.OrdinalIgnoreCase) >= 0))
            {
                return(false);
            }
            if (Roles.Length > 0)
            {
                IDependencyScope  Scope       = actionContext.Request.GetOwinContext().Get <IDependencyScope>();
                ClientUserManager UserManager = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
                var client    = UserManager.FindByEmailAsync(user.Identity.Name).Result;
                var GroupList = UserManager.GetRolesAsync(client.Id).Result;
                var listRoles = Roles.Split(',');
                if (listRoles.Where(x => GroupList.Any(y => y.Equals(x))).Count() == 0)
                {
                    return(false);
                }
            }
            return(true);
        }
Example #2
0
        public async override Task Invoke(IOwinContext context)
        {
            if (context.Authentication.User != null && !String.IsNullOrWhiteSpace(context.Authentication.User.Identity.Name) && context.Authentication.User.Identity.IsAuthenticated)
            {
                IDependencyScope  Scope       = context.Get <IDependencyScope>();
                ClientUserManager UserManager = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
                var userClient = await UserManager.FindByEmailAsync(context.Authentication.User.Identity.Name);

                if (userClient.Locale != null && !string.IsNullOrEmpty(userClient.Locale))
                {
                    Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo(userClient.Locale);
                }
            }
            await Next.Invoke(context);
        }
Example #3
0
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientId = context.Ticket.Properties.Dictionary[GenericNames.AUTHENTICATION_CLIENT_ID_KEY];

            if (string.IsNullOrEmpty(clientId))
            {
                return;
            }

            var refreshTokenLifeTime = context.OwinContext.Get <int>(GenericNames.OWIN_CONTEXT_REFRESH_TOKEN_LIFETIME);

            var refreshToken = Guid.NewGuid().ToString("n");

            //var refreshTokenRepository = new RefreshTokenRepository(context.OwinContext.Get<ManahostManagerDAL>());
            /*var ClientManager = ClientUserManager.Create(null, context.OwinContext.Get<ManahostManagerDAL>());*/

            IDependencyScope        Scope                  = context.OwinContext.Get <IDependencyScope>();
            ClientUserManager       ClientManager          = Scope.GetService(typeof(ClientUserManager)) as ClientUserManager;
            IRefreshTokenRepository refreshTokenRepository = Scope.GetService(typeof(IRefreshTokenRepository)) as IRefreshTokenRepository;

            var ServiceRepository = new ServiceRepository(context.OwinContext.Get <ManahostManagerDAL>());

            var client = await ClientManager.FindByEmailAsync(context.Ticket.Identity.Name);

            var service = ServiceRepository.GetUniq(x => x.Id == clientId);

            var token = new RefreshToken()
            {
                Id         = refreshToken,
                Client     = client,
                Service    = service,
                IssuedUtc  = DateTime.UtcNow,
                ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
            };

            token.ProtectedTicket = context.SerializeTicket();
            refreshTokenRepository.Add(token);
            await refreshTokenRepository.SaveAsync();

            context.SetToken(refreshToken);
        }
Example #4
0
 public async Task <Client> FindUserByMailAsync(string mail)
 {
     return(await _userManager.FindByEmailAsync(mail));
 }
Example #5
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);
        }