public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            try
            {  //context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

            using (AuthService _repo = new AuthService())
            {
                var user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            context.Validated(identity);
        }

        catch (Exception exp)
    {}
        }
 static IAppHost GetAppHost()
 {
     if (_appHost == null)
     {
         _appHost = new BasicAppHost();
         var authService = new AuthService();
         authService.SetResolver(_appHost);
         _appHost.Container.Register(authService);
         _appHost.Container.Register<IAuthSession>(authUserSession);
     }
     return _appHost;
 }
Esempio n. 3
0
        public static void CopyAuthorization( ISecured sourceEntity, ISecured targetEntity, int? personId )
        {
            using ( new Rock.Helpers.UnitOfWorkScope() )
            {
                // If there's no Authorizations object, create it
                if ( Authorizations == null )
                    Load();

                AuthService authService = new AuthService();

                // Delete the current authorizations for the target entity
                foreach(Auth auth in authService.GetAuthsByEntityTypeAndEntityId(targetEntity.AuthEntity, targetEntity.Id))
                    authService.DeleteAuth(auth);

                Dictionary<string, List<AuthRule>> newActions = new Dictionary<string, List<AuthRule>>();

                int order = 0;
                foreach ( KeyValuePair<string, List<AuthRule>> action in Authorizations[sourceEntity.AuthEntity][sourceEntity.Id] )
                    if (targetEntity.SupportedActions.Contains(action.Key))
                    {
                        newActions.Add( action.Key, new List<AuthRule>() );

                        foreach ( AuthRule rule in action.Value )
                        {
                            Auth auth = new Auth();
                            auth.EntityType = targetEntity.AuthEntity;
                            auth.EntityId = targetEntity.Id;
                            auth.Order = order;
                            auth.Action = action.Key;
                            auth.AllowOrDeny = rule.AllowOrDeny;
                            auth.UserOrRole = rule.UserOrRole;
                            auth.UserOrRoleName = rule.UserOrRoleName;

                            authService.AddAuth(auth);
                            authService.Save(auth, personId);

                            newActions[action.Key].Add( new AuthRule( rule.AllowOrDeny, rule.UserOrRole, rule.UserOrRoleName ) );

                            order++;
                        }
                    }

                if ( !Authorizations.ContainsKey( targetEntity.AuthEntity ) )
                    Authorizations.Add( targetEntity.AuthEntity, new Dictionary<int, Dictionary<string, List<AuthRule>>>() );

                Dictionary<int, Dictionary<string, List<AuthRule>>> entityType = Authorizations[targetEntity.AuthEntity];

                if ( !entityType.ContainsKey( targetEntity.Id ) )
                    entityType.Add( targetEntity.Id, new Dictionary<string, List<AuthRule>>() );

                entityType[targetEntity.Id] = newActions;
            }
        }
Esempio n. 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        IApplicationContext ctx = ContextRegistry.GetContext();
        authService = (AuthService)ctx.GetObject("AuthService");

        if (!Page.IsPostBack)
        {
            setPrgName();
            initMenu();
            initInfo();
        }
    }
        /// <summary>
        /// Create an APM token
        /// </summary>
        internal static string CreateAPMToken(AuthService authService)
        {
            var tokenRequest = new TokenRequest();
            tokenRequest.clientKey = Configuration.ClientKey;

            var cardRequest = new APMRequest();
            cardRequest.type = "APM";
            cardRequest.apmName = "PAYPAL";
            cardRequest.shopperCountryCode = "GB";
            cardRequest.apmFields = new Dictionary<string, string>();

            tokenRequest.paymentMethod = cardRequest;

            TokenResponse response = authService.GetToken(tokenRequest);
            return response.token;
        }
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            var hashedTokenId = Helper.GetHash( context.Token) ;
            authRepository = new AuthService();
            var refreshToken = await authRepository.FindRefreshToken(hashedTokenId);

            if (refreshToken != null)
            {
                //Get protectedTicket from refreshToken class
                context.DeserializeTicket(refreshToken.ProtectedTicket);

                var result = await authRepository.RemoveRefreshToken( hashedTokenId );
            }
        }
        /// <summary>
        /// Create an access token
        /// </summary>
        internal static string CreateToken(AuthService authService)
        {
            var tokenRequest = new TokenRequest();
            tokenRequest.clientKey = Configuration.ClientKey;

            var cardRequest = new CardRequest();
            cardRequest.cardNumber = TestMastercardNumber;
            cardRequest.cvc = TestCvv;
            cardRequest.name = "csharplib client";
            cardRequest.expiryMonth = 2;
            cardRequest.expiryYear = 2018;
            cardRequest.type = "Card";

            tokenRequest.paymentMethod = cardRequest;

            TokenResponse response = authService.GetToken(tokenRequest);
            return response.token;
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            try
            {
                if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
                    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

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

                var refreshTokenId = Helper.GetHash(ObjectId.GenerateNewId().ToString ());

                var refreshTokenLifeTime = context.OwinContext.Get<string>("as:clientRefreshTokenLifeTime");

                var token = new RefreshToken()
                {

                    Token = refreshTokenId  ,
                    ClientId = clientid,
                    Subject = context.Ticket.Identity.Name,
                    IssuedUtc = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
                };

                context.Ticket.Properties.IssuedUtc = token.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;
                 

                token.ProtectedTicket = context.SerializeTicket();
                authRepository = new AuthService();
                var result = await authRepository.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
            catch (Exception exp)
            { }
        }
        public void should_succeed_if_registered()
        {


            AuthService auth = new AuthService();
            var acontroller = new AccountController(auth);
            acontroller.Request = new HttpRequestMessage();
            acontroller.Configuration = new HttpConfiguration();
            var p = new UserModel
           {
               Name = "*****@*****.**",
               Password = "******",
               ConfirmPassword = "******"

           };
            var res = acontroller.Register(p);


        }
Esempio n. 10
0
    protected void Page_Load(object sender, EventArgs e)
    {
        IApplicationContext ctx = ContextRegistry.GetContext();
        authService = (AuthService)ctx.GetObject("AuthService");

        if (!Page.IsPostBack)
        {
            SetConcrol();
            if (Request.QueryString["id"] != null)
            {
                UseUpdateMode();
                hdnId.Value = Request.QueryString["id"].ToString();
                LoadDataToUI(hdnId.Value);
            }
            else
            {
                UseAddMode();
            }
        }
    }
Esempio n. 11
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);
            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            SetContentView(Resource.Layout.activity_auth);
            loginText    = FindViewById <EditText>(Resource.Id.vklogin);
            passwordText = FindViewById <EditText>(Resource.Id.vkpassword);

            Button btn = FindViewById <Button>(Resource.Id.log_in_btn);

            btn.Click += async(sender, e) =>
            {
                if (loginText.Text == "" || passwordText.Text == "")
                {
                    Toast.MakeText(this, "Вы не указали логин и пароль", ToastLength.Long).Show();
                    return;
                }

                var progressBarLoading = FindViewById <ProgressBar>(Resource.Id.progressBarLogin);
                progressBarLoading.Visibility = ViewStates.Visible;
                btn.Visibility = ViewStates.Invisible;
                Toast.MakeText(this, "Пытаюсь связаться с ВКонтакте...", ToastLength.Long).Show();
                string token = null;
                try
                {
                    token = await Auth.User(loginText.Text, passwordText.Text, TwoFactorAuth, null);
                }catch (VkNet.Exception.UserAuthorizationFailException)
                {
                    AuthService.ShowIncorrectLoginDialog(this.FragmentManager);
                }catch (VkNet.Exception.VkAuthorizationException)
                {
                    AuthService.ShowIncorrectLoginDialog(this.FragmentManager);
                }
                catch (VkNet.Exception.VkApiAuthorizationException)
                {
                    AuthService.ShowIncorrectLoginDialog(this.FragmentManager);
                }
                catch (VkNet.Exception.UserDeletedOrBannedException)
                {
                    AuthService.ShowIncorrectLoginDialog(this.FragmentManager);
                }
                catch (Flurl.Http.FlurlHttpException)
                {
                    Toast.MakeText(this, "Нет доступа к интернету", ToastLength.Long).Show();
                }
                catch (System.Exception ex)
                {
                    Toast.MakeText(this, "Неизвестная ошибка авторизации: " + ex, ToastLength.Long).Show();
                }

                if (token != null)
                {
                    //Toast.MakeText(this, "Ваш токен " + token, ToastLength.Long).Show();
                    var prefs  = Application.Context.GetSharedPreferences("MusicX", FileCreationMode.Private);
                    var editor = prefs.Edit();
                    editor.PutString("VKToken", token);
                    editor.Commit();

                    Intent intent = new Intent(this.ApplicationContext, typeof(MainActivity));
                    intent.SetFlags(ActivityFlags.NewTask);
                    StartActivity(intent);
                    Finish();
                }
                else
                {
                    progressBarLoading.Visibility = ViewStates.Invisible;
                    btn.Visibility = ViewStates.Visible;
                }
            };
        }
Esempio n. 12
0
 public Edit(AuthService authService)
 {
     _httpService = new HttpService(authService.GetHttpClient(), authService.ApiUrl);
 }
Esempio n. 13
0
 public UnAuthorizeCommand(AppConfig appConfig, LiteDatabaseAsync liteDb, IEasyCachingProvider easyCachingProvider, AuthService authService)
 {
     _appConfig           = appConfig;
     _easyCachingProvider = easyCachingProvider;
     _authService         = authService;
     _liteDb = liteDb;
 }
Esempio n. 14
0
 public AuthController(AuthService authService)
 {
     AuthService = authService;
 }
 public async Task ActivateAsync()
 {
     Identity = await AuthService.GetIdentityAsync().ConfigureAwait(true);
 }
Esempio n. 16
0
        public static void Init(string customUserAgent           = null, string clearCipherCacheKey = null,
                                string[] allClearCipherCacheKeys = null)
        {
            if (Inited)
            {
                return;
            }
            Inited = true;

            var           platformUtilsService  = Resolve <IPlatformUtilsService>("platformUtilsService");
            var           storageService        = Resolve <IStorageService>("storageService");
            var           stateService          = Resolve <IStateService>("stateService");
            var           i18nService           = Resolve <II18nService>("i18nService");
            var           messagingService      = Resolve <IMessagingService>("messagingService");
            var           cryptoFunctionService = Resolve <ICryptoFunctionService>("cryptoFunctionService");
            var           cryptoService         = Resolve <ICryptoService>("cryptoService");
            SearchService searchService         = null;

            var tokenService = new TokenService(stateService);
            var apiService   = new ApiService(tokenService, platformUtilsService, (extras) =>
            {
                messagingService.Send("logout", extras);
                return(Task.CompletedTask);
            }, customUserAgent);
            var appIdService        = new AppIdService(storageService);
            var organizationService = new OrganizationService(stateService);
            var settingsService     = new SettingsService(stateService);
            var fileUploadService   = new FileUploadService(apiService);
            var cipherService       = new CipherService(cryptoService, stateService, settingsService, apiService,
                                                        fileUploadService, storageService, i18nService, () => searchService, clearCipherCacheKey,
                                                        allClearCipherCacheKeys);
            var folderService     = new FolderService(cryptoService, stateService, apiService, i18nService, cipherService);
            var collectionService = new CollectionService(cryptoService, stateService, i18nService);
            var sendService       = new SendService(cryptoService, stateService, apiService, fileUploadService, i18nService,
                                                    cryptoFunctionService);

            searchService = new SearchService(cipherService, sendService);
            var policyService       = new PolicyService(stateService, organizationService);
            var keyConnectorService = new KeyConnectorService(stateService, cryptoService, tokenService, apiService,
                                                              organizationService);
            var vaultTimeoutService = new VaultTimeoutService(cryptoService, stateService, platformUtilsService,
                                                              folderService, cipherService, collectionService, searchService, messagingService, tokenService,
                                                              policyService, keyConnectorService,
                                                              (extras) =>
            {
                messagingService.Send("locked", extras);
                return(Task.CompletedTask);
            },
                                                              (extras) =>
            {
                messagingService.Send("logout", extras);
                return(Task.CompletedTask);
            });
            var syncService = new SyncService(stateService, apiService, settingsService, folderService, cipherService,
                                              cryptoService, collectionService, organizationService, messagingService, policyService, sendService,
                                              keyConnectorService, (extras) =>
            {
                messagingService.Send("logout", extras);
                return(Task.CompletedTask);
            });
            var passwordGenerationService = new PasswordGenerationService(cryptoService, stateService,
                                                                          cryptoFunctionService, policyService);
            var totpService = new TotpService(stateService, cryptoFunctionService);
            var authService = new AuthService(cryptoService, cryptoFunctionService, apiService, stateService,
                                              tokenService, appIdService, i18nService, platformUtilsService, messagingService, vaultTimeoutService,
                                              keyConnectorService);
            var exportService           = new ExportService(folderService, cipherService, cryptoService);
            var auditService            = new AuditService(cryptoFunctionService, apiService);
            var environmentService      = new EnvironmentService(apiService, stateService);
            var eventService            = new EventService(apiService, stateService, organizationService, cipherService);
            var userVerificationService = new UserVerificationService(apiService, platformUtilsService, i18nService,
                                                                      cryptoService);

            Register <ITokenService>("tokenService", tokenService);
            Register <IApiService>("apiService", apiService);
            Register <IAppIdService>("appIdService", appIdService);
            Register <IOrganizationService>("organizationService", organizationService);
            Register <ISettingsService>("settingsService", settingsService);
            Register <ICipherService>("cipherService", cipherService);
            Register <IFolderService>("folderService", folderService);
            Register <ICollectionService>("collectionService", collectionService);
            Register <ISendService>("sendService", sendService);
            Register <ISearchService>("searchService", searchService);
            Register <IPolicyService>("policyService", policyService);
            Register <ISyncService>("syncService", syncService);
            Register <IVaultTimeoutService>("vaultTimeoutService", vaultTimeoutService);
            Register <IPasswordGenerationService>("passwordGenerationService", passwordGenerationService);
            Register <ITotpService>("totpService", totpService);
            Register <IAuthService>("authService", authService);
            Register <IExportService>("exportService", exportService);
            Register <IAuditService>("auditService", auditService);
            Register <IEnvironmentService>("environmentService", environmentService);
            Register <IEventService>("eventService", eventService);
            Register <IKeyConnectorService>("keyConnectorService", keyConnectorService);
            Register <IUserVerificationService>("userVerificationService", userVerificationService);
        }
Esempio n. 17
0
 public MediaController(MediaPresenterService media, CacheService cache, AuthService auth)
 {
     _media = media;
     _cache = cache;
     _auth  = auth;
 }
 public PosLoginPageViewModel(ICustomerNavService navService, AuthService authService) : base(navService)
 {
     AuthService = authService;
 }
Esempio n. 19
0
 public AuthController(
     AuthService <AccountUser> authService)
 {
     _authService = authService;
 }
Esempio n. 20
0
        /// <inheritdoc/>
        protected override async Task <TaskModel> ProtectedHandleAsync(UpdateTaskStatusCommand request, CancellationToken cancellationToken)
        {
            var entity = await Context.TaskRepository
                         .GetFirstOrDefaultAsync(e => e.Id == Guid.Parse(request.Id));

            if (entity == null)
            {
                throw new NotFoundException(nameof(TaskEntity), request.Id);
            }

            if (!AuthService.IsAuthorized(entity.UserId))
            {
                throw new ForbiddenException("Not authorized");
            }

            entity.ModifiedDate = DateTime.UtcNow;
            entity.Status       = (int)request.Status;
            entity.Message      = request.Message;

            switch (request.Status)
            {
            case Domain.Enums.TaskStatus.Created:
                entity.QueuedDate  = null;
                entity.StartedDate = null;
                entity.EndedDate   = null;
                break;

            case Domain.Enums.TaskStatus.Queued:
                entity.QueuedDate  = DateTime.UtcNow;
                entity.StartedDate = null;
                entity.EndedDate   = null;
                break;

            case Domain.Enums.TaskStatus.Processing:
                entity.StartedDate = DateTime.UtcNow;
                entity.EndedDate   = null;
                break;

            case Domain.Enums.TaskStatus.Canceled:
            case Domain.Enums.TaskStatus.Failed:
            case Domain.Enums.TaskStatus.Finished:
                entity.EndedDate = DateTime.UtcNow;
                break;

            default:
                break;
            }

            if (request.Status != Domain.Enums.TaskStatus.Queued)
            {
                entity.Position = 0;
            }

            if (!string.IsNullOrWhiteSpace(request.ResultId))
            {
                entity.ResultId = Guid.Parse(request.ResultId);
            }

            Context.TaskRepository.Update(entity);

            await Context.SaveChangesAsync(cancellationToken);

            var result = await mediator.Send(new GetByIdQuery()
            {
                Id = entity.Id.ToString()
            });

            if (result == null)
            {
                throw new UnexpectedNullException($"The task '{entity.Id.ToString()}' could not be retrieved after updating it.");
            }

            if (entity.Object != null)
            {
                await Events.CreateAsync(entity.Object.UserId, EventType.TaskUpdated, result, cancellationToken);

                await Gateway.NotifyGroupsAsync(entity.Object.UserId, EventType.TaskUpdated, result, cancellationToken);
            }

            return(result);
        }
Esempio n. 21
0
        public async Task <ActionResult> Validate(String token)
        {
            await AuthService.ValidateRegistration(token);

            return(Ok());
        }
Esempio n. 22
0
        public async Task <ActionResult> Register([FromBody] API.Request.NewUser newUser)
        {
            await AuthService.Register(newUser);

            return(StatusCode(StatusCodes.Status201Created));
        }
Esempio n. 23
0
 public AuthController(
     AuthService <ColossusUser> authService)
 {
     _authService = authService;
 }
Esempio n. 24
0
 public AccountController(UserService userService, AuthService authService)
 {
     _userService = userService;
     _authService = authService;
 }
Esempio n. 25
0
        private async Task Login()
        {
            ClearErrorMessage();
            if (!EmailHelper.IsValidEmail(email))
            {
                ErrorMessageEmail = "Invalid Email.";
                IsErrorEmail      = true;
                return;
            }
            IsBusy = true;
            await Task.Delay(1000);

            try
            {
                //LoadingLottie = true;
                if (NullValidate(Email) == false)
                {
                    ErrorMessageEmail = "Please enter E-mail";
                    IsErrorEmail      = true;
                }
                else if (!EmailHelper.IsValidEmail(email))
                {
                    ErrorMessageEmail = "E-mail is invalid";
                    IsErrorEmail      = true;
                }
                else if (NullValidate(Password) == false)
                {
                    ErrorMessagePassword = "******";
                    IsErrorPassword      = true;
                }
                else
                {
                    var checkNet    = true;
                    int workingStep = 1;
                    retry = 1;
                    int loopcheck = 0;

                    bool internetCheck = true;
                    do
                    {
                        switch (workingStep)
                        {
                        case 1:    //check internet
                            checkNet = CheckingInternet();
                            if (checkNet == true)
                            {
                                workingStep = 10;
                            }
                            else
                            {
                                workingStep = 2;
                            }
                            break;

                        case 2:    //delay
                            await Task.Delay(300);

                            workingStep = 3;
                            break;

                        case 3:    //action result
                            bool istryAgain = await Application.Current.MainPage.DisplayAlert("", "No Internet", "Try Again", "Cancel");

                            if (istryAgain)
                            {
                                workingStep = 1;
                            }
                            else
                            {
                                internetCheck = false;
                            }
                            break;

                        case 10:    //call api
                            loopcheck++;
                            LoginCommandModel command = new LoginCommandModel()
                            {
                                Email    = Email,
                                Password = Password
                            };

                            result = await AuthService.Login(command);

                            if (result.StatusCode == Enums.StatusCode.Ok)
                            {
                                // await App.Current.MainPage.Navigation.PushAsync(new LoginPage());
                                App.Email            = result.Success.Email;
                                App.FullName         = result.Success.FullName;
                                App.UserId           = result.Success.Id;
                                App.AccessToken      = result.Success.AccessToken;
                                App.About            = result.Success.About;
                                App.ImagePath        = result.Success.ImageProfilePath;
                                App.Current.MainPage = new AppShell();
                                workingStep          = 100;
                            }
                            else
                            {
                                if (loopcheck <= maxRetry)
                                {
                                    if (result.StatusCode == Enums.StatusCode.Unauthorized)
                                    {
                                        //	await GetToken();
                                    }
                                    else
                                    {
                                        workingStep++;
                                    }
                                }
                                else
                                {
                                    internetCheck = false;
                                }
                            }
                            break;

                        case 11:    //
                            await Task.Delay(300);

                            workingStep++;
                            break;

                        case 12:    //

                            if (result.StatusCode == Enums.StatusCode.BadRequest)
                            {
                                //await PopupNavigation.Instance.PushAsync(new ErrorPopup(resultHistory.Error.ErrorMessage));
                                //await Application.Current.MainPage.DisplayAlert("", resultHistory.Error.ErrorMessage.ToString(), "OK");
                            }
                            else if (result.StatusCode == Enums.StatusCode.NotFound)
                            {
                                //await PopupNavigation.Instance.PushAsync(new ErrorPopup(resultHistory.Error.ErrorMessage));
                                //await Application.Current.MainPage.DisplayAlert("", resultHistory.Error.ErrorMessage.ToString(), "OK");
                            }
                            else if (result.StatusCode == Enums.StatusCode.InternalServerError)
                            {
                                //await PopupNavigation.Instance.PushAsync(new ErrorPopup(resultHistory.Error.ErrorMessage));
                                //await Application.Current.MainPage.DisplayAlert("", resultHistory.Error.ErrorMessage.ToString(), "OK");
                            }
                            else
                            {
                                //await PopupNavigation.Instance.PushAsync(new ErrorPopup(resultHistory.Error.ErrorMessage));
                                //await Application.Current.MainPage.DisplayAlert("", resultHistory.Error.ErrorMessage.ToString(), "OK");
                            }
                            workingStep++;
                            break;

                        case 13:    //
                            internetCheck = false;
                            break;

                        case 100:    //
                            internetCheck = false;
                            break;

                        default:
                            internetCheck = false;
                            break;
                        }
                    } while (internetCheck);
                }
            }
            catch (OperationCanceledException ex)
            {
                //await PopupNavigation.Instance.PushAsync(new ErrorPopup("ปิดปรับปรุงServer"));
                await Application.Current.MainPage.DisplayAlert("", "ปิดปรับปรุงServer", "OK");

                //Application.Current.MainPage = new NavigationPage(new LoginPage());
            }
            catch (TimeoutException ex)
            {
                //await PopupNavigation.Instance.PushAsync(new ErrorPopup("กรุณาลองใหม่อีกครั้ง"));
                await Application.Current.MainPage.DisplayAlert("", "กรุณาลองใหม่อีกครั้ง", "OK");

                //Application.Current.MainPage = new NavigationPage(new LoginPage());
            }
            catch (Exception ex)
            {
                //await PopupNavigation.Instance.PushAsync(new ErrorPopup("กรุณาลองใหม่อีกครั้ง"));
                await Application.Current.MainPage.DisplayAlert("", "กรุณาลองใหม่อีกครั้ง", "OK");
            }
            //Call Api
            //Home
            IsBusy = false;
        }
        public SignInController(UserRepository userRepository, AuthService authService)
        {
            _userRepository = userRepository;

            _authService = authService;
        }
Esempio n. 27
0
 public void TestFixtureSetUp()
 {
     AuthService.Init(new TestAppHost(), () => new AuthUserSession(),
                      new CredentialsAuthProvider());
 }
Esempio n. 28
0
 public AuthController(UserManager <Person> userManager, SignInManager <Person> signInManager, PersonService personService, AuthService authService)
 {
     _userManager   = userManager;
     _signInManager = signInManager;
     PersonService  = personService;
     AuthService    = authService;
 }
Esempio n. 29
0
 public ReservationDetailsViewModel()
 {
     _proxy       = AutofacHelper.Container.Resolve <ApiClientProxy>();
     _mapper      = AutofacHelper.Container.Resolve <Mapper>();
     _authService = AutofacHelper.Container.Resolve <AuthService>();
 }
Esempio n. 30
0
        private AuthViewModel()
        {
            IsActiveProgressRing = false;
            VisibilityButton     = Visibility.Visible;
            LoginCommand         = new RelayCommand(async() =>
            {
                IsActiveProgressRing = true;
                VisibilityButton     = Visibility.Collapsed;
                Changed("IsActiveProgressRing");
                Changed("VisibilityButton");

                if (Login == null || Password == null)
                {
                    await new MessageDialog("Вы не указали логин или пароль").ShowAsync();
                    IsActiveProgressRing = false;
                    VisibilityButton     = Visibility.Visible;
                    Changed("IsActiveProgressRing");
                    Changed("VisibilityButton");
                    return;
                }

                string token = null;

                try
                {
                    token = await AuthService.FirstAuth(Login, Password);
                }
                catch (VkNet.Exception.UserAuthorizationFailException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (VkNet.Exception.VkAuthorizationException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (VkNet.Exception.VkApiAuthorizationException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (VkNet.Exception.UserDeletedOrBannedException)
                {
                    await ContentDialogService.Show(new IncorrectLoginOrPasswordContentDialog());
                }
                catch (Flurl.Http.FlurlHttpException)
                {
                    await ContentDialogService.Show(new ErrorConnectContentDialog());
                }catch (Exception e)
                {
                    await ContentDialogService.Show(new ExceptionDialog("Неизвестная ошибка авторизации", "", e));
                }

                if (token != null)
                {
                    try
                    {
                        PlayerMenuViewModel.Instanse.VkontaktePages = Visibility.Visible;
                        await TokenService.Save(token);
                        StaticContent.IsAuth = true;
                        StaticContent.CurrentSessionIsAuth = true;
                        StaticContent.NavigationContentService.Go(typeof(HomeView));
                    }catch (Exception e)
                    {
                        await ContentDialogService.Show(new ExceptionDialog("Неизвестная ошибка после авторизации", "Возможно, ошибка навигации или сохранения", e));
                        PlayerMenuViewModel.Instanse.VkontaktePages = Visibility.Collapsed;
                        StaticContent.IsAuth = false;
                        StaticContent.CurrentSessionIsAuth = false;
                    }
                }
                else
                {
                    IsActiveProgressRing = false;
                    VisibilityButton     = Visibility.Visible;
                    Changed("IsActiveProgressRing");
                    Changed("VisibilityButton");
                }
            });
        }
Esempio n. 31
0
 public AudioController()
 {
     _vkAuthService  = new AuthService();
     _vkMusicService = new AudioService();
 }
 public SimpleRefreshTokenProvider(AuthService authRepository)
 {
     this.authRepository = authRepository;
 }
Esempio n. 33
0
        public async Task <IViewComponentResult> InvokeAsync(PageComponentContext context)
        {
            ErpPage currentPage = null;

            try
            {
                #region << Init >>
                if (context.Node == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The node Id is required to be set as query param 'nid', when requesting this component")));
                }

                var pageFromModel = context.DataModel.GetProperty("Page");
                if (pageFromModel is ErpPage)
                {
                    currentPage = (ErpPage)pageFromModel;
                }
                else
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: PageModel does not have Page property or it is not from ErpPage Type")));
                }

                if (currentPage == null)
                {
                    return(await Task.FromResult <IViewComponentResult>(Content("Error: The page Id is required to be set as query param 'pid', when requesting this component")));
                }

                var options = new PcSectionOptions();
                if (context.Options != null)
                {
                    options = JsonConvert.DeserializeObject <PcSectionOptions>(context.Options.ToString());
                }

                //Check if it is defined in form group
                if (options.LabelMode == LabelRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(LabelRenderMode)))
                    {
                        options.LabelMode = (LabelRenderMode)context.Items[typeof(LabelRenderMode)];
                    }
                    else
                    {
                        options.LabelMode = LabelRenderMode.Stacked;
                    }
                }

                //Check if it is defined in form group
                if (options.FieldMode == FieldRenderMode.Undefined)
                {
                    if (context.Items.ContainsKey(typeof(FieldRenderMode)))
                    {
                        options.FieldMode = (FieldRenderMode)context.Items[typeof(FieldRenderMode)];
                    }
                    else
                    {
                        options.FieldMode = FieldRenderMode.Form;
                    }
                }
                var componentMeta = new PageComponentLibraryService().GetComponentMeta(context.Node.ComponentName);

                //Init IsCollapsed from userPreferences
                if (HttpContext.User != null)
                {
                    var currentUser = AuthService.GetUser(HttpContext.User);
                    if (currentUser != null)
                    {
                        var componentData = new UserPreferencies().GetComponentData(currentUser.Id, "WebVella.Erp.Web.Components.PcSection");
                        if (componentData != null)
                        {
                            var collapsedNodeIds   = new List <Guid>();
                            var uncollapsedNodeIds = new List <Guid>();
                            if (componentData.Properties.ContainsKey("collapsed_node_ids") && componentData["collapsed_node_ids"] != null)
                            {
                                if (componentData["collapsed_node_ids"] is string)
                                {
                                    try
                                    {
                                        collapsedNodeIds = JsonConvert.DeserializeObject <List <Guid> >((string)componentData["collapsed_node_ids"]);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("WebVella.Erp.Web.Components.PcSection component data object in user preferences not in the correct format. collapsed_node_ids should be List<Guid>");
                                    }
                                }
                                else if (componentData["collapsed_node_ids"] is List <Guid> )
                                {
                                    collapsedNodeIds = (List <Guid>)componentData["collapsed_node_ids"];
                                }
                                else if (componentData["collapsed_node_ids"] is JArray)
                                {
                                    collapsedNodeIds = ((JArray)componentData["collapsed_node_ids"]).ToObject <List <Guid> >();
                                }
                                else
                                {
                                    throw new Exception("Unknown format of collapsed_node_ids");
                                }
                            }
                            if (componentData.Properties.ContainsKey("uncollapsed_node_ids") && componentData["uncollapsed_node_ids"] != null)
                            {
                                if (componentData["uncollapsed_node_ids"] is string)
                                {
                                    try
                                    {
                                        uncollapsedNodeIds = JsonConvert.DeserializeObject <List <Guid> >((string)componentData["uncollapsed_node_ids"]);
                                    }
                                    catch (Exception ex)
                                    {
                                        throw new Exception("WebVella.Erp.Web.Components.PcSection component data object in user preferences not in the correct format. uncollapsed_node_ids should be List<Guid>");
                                    }
                                }
                                else if (componentData["uncollapsed_node_ids"] is List <Guid> )
                                {
                                    uncollapsedNodeIds = (List <Guid>)componentData["uncollapsed_node_ids"];
                                }
                                else if (componentData["uncollapsed_node_ids"] is JArray)
                                {
                                    uncollapsedNodeIds = ((JArray)componentData["uncollapsed_node_ids"]).ToObject <List <Guid> >();
                                }
                                else
                                {
                                    throw new Exception("Unknown format of uncollapsed_node_ids");
                                }
                            }
                            if (collapsedNodeIds.Contains(context.Node.Id))
                            {
                                options.IsCollapsed = true;
                            }
                            else if (uncollapsedNodeIds.Contains(context.Node.Id))
                            {
                                options.IsCollapsed = false;
                            }
                        }
                    }
                }



                #endregion

                ViewBag.Options            = options;
                ViewBag.Node               = context.Node;
                ViewBag.ComponentMeta      = componentMeta;
                ViewBag.RequestContext     = ErpRequestContext;
                ViewBag.AppContext         = ErpAppContext.Current;
                ViewBag.ComponentContext   = context;
                ViewBag.GeneralHelpSection = HelpJsApiGeneralSection;

                if (context.Mode == ComponentMode.Display || context.Mode == ComponentMode.Design)
                {
                    var isVisible   = true;
                    var isVisibleDS = context.DataModel.GetPropertyValueByDataSource(options.IsVisible);
                    if (isVisibleDS is string && !String.IsNullOrWhiteSpace(isVisibleDS.ToString()))
                    {
                        if (Boolean.TryParse(isVisibleDS.ToString(), out bool outBool))
                        {
                            isVisible = outBool;
                        }
                    }
                    else if (isVisibleDS is Boolean)
                    {
                        isVisible = (bool)isVisibleDS;
                    }
                    ViewBag.IsVisible = isVisible;

                    ViewBag.ProcessedTitle = context.DataModel.GetPropertyValueByDataSource(options.Title);
                }

                context.Items[typeof(LabelRenderMode)] = options.LabelMode;
                context.Items[typeof(FieldRenderMode)] = options.FieldMode;

                switch (context.Mode)
                {
                case ComponentMode.Display:
                    return(await Task.FromResult <IViewComponentResult>(View("Display")));

                case ComponentMode.Design:
                    return(await Task.FromResult <IViewComponentResult>(View("Design")));

                case ComponentMode.Options:
                    ViewBag.LabelRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <LabelRenderMode>();
                    ViewBag.FieldRenderModeOptions = ModelExtensions.GetEnumAsSelectOptions <FieldRenderMode>();
                    return(await Task.FromResult <IViewComponentResult>(View("Options")));

                case ComponentMode.Help:
                    return(await Task.FromResult <IViewComponentResult>(View("Help")));

                default:
                    ViewBag.Error = new ValidationException()
                    {
                        Message = "Unknown component mode"
                    };
                    return(await Task.FromResult <IViewComponentResult>(View("Error")));
                }
            }
            catch (ValidationException ex)
            {
                ViewBag.Error = ex;
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
            catch (Exception ex)
            {
                ViewBag.Error = new ValidationException()
                {
                    Message = ex.Message
                };
                return(await Task.FromResult <IViewComponentResult>(View("Error")));
            }
        }
Esempio n. 34
0
 public AuthController(IMediator mediator, AuthService authService)
 {
     _mediator    = mediator;
     _authService = authService;
 }
Esempio n. 35
0
 public OnboardingRestService(AuthService authService, ILogger logger, string baseUrl)
     : base(authService, logger, baseUrl)
 {
     client.Authenticator = new HttpBasicAuthenticator("Administrator", "Edison1234");
 }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
             if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
                    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            var allowedOrigin = context.OwinContext.Get<string>("as:clientAllowedOrigin");
            ApplicationUser user = new ApplicationUser(); 
            if (allowedOrigin == null) allowedOrigin = "*";

            
            using (AuthService _repo = new AuthService())
            {
                user = await _repo.FindUser(context.UserName, context.Password);
            }
            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));
           
            
            //using (AuthService _repo = new AuthService())
            //{

            //    var identity = await _repo.CreateIdentity(user, context.Options.AuthenticationType);

            
            
            var props = new AuthenticationProperties(new Dictionary<string, string>
                {
                    { 
                        "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                    },
                    { 
                        "userName", context.UserName
                    }
                });

            var ticket = new AuthenticationTicket(identity, props);
            try
            {
                var accessToken = Startup.OAuthServerOptions.AccessTokenFormat.Protect(ticket);
            }
            catch
            { }
            context.Validated(ticket);
            //}
        }
        /// <summary>Gets registration service.</summary>
        ///
        /// <param name="userAuthRepository">The user authentication repository.</param>
        /// <param name="oAuthUserSession">  The authentication user session.</param>
        /// <param name="requestContext">    Context for the request.</param>
        ///
        /// <returns>The registration service.</returns>
		public static RegistrationService GetRegistrationService(
			IUserAuthRepository userAuthRepository,
			AuthUserSession oAuthUserSession = null,
			MockRequestContext requestContext = null)
		{
			if (requestContext == null)
				requestContext = new MockRequestContext();
			if (oAuthUserSession == null)
				oAuthUserSession = requestContext.ReloadSession();

			var httpReq = requestContext.Get<IHttpRequest>();
			var httpRes = requestContext.Get<IHttpResponse>();
			oAuthUserSession.Id = httpRes.CreateSessionId(httpReq);
			httpReq.Items[ServiceExtensions.RequestItemsSessionKey] = oAuthUserSession;

			var mockAppHost = new BasicAppHost {
				Container = requestContext.Container
			};

			requestContext.Container.Register(userAuthRepository);

		    var authService = new AuthService {
                RequestContext = requestContext,
            };
            authService.SetResolver(mockAppHost);
            mockAppHost.Register(authService);

			var registrationService = new RegistrationService {
				UserAuthRepo = userAuthRepository,
				RequestContext = requestContext,
				RegistrationValidator =
					new RegistrationValidator { UserAuthRepo = RegistrationServiceTests.GetStubRepo() },
			};
			registrationService.SetResolver(mockAppHost);

			return registrationService;
		}
        public async void LogoutUser(object sender, EventArgs e)
        {
            await AuthService.Logout();

            NavigateToDashboard?.Invoke();
        }
Esempio n. 39
0
 public CreditCardController(AuthService authService)
 {
     this.authService = authService;
 }
 public AuthController(AuthService authService, UserService userService = null)
 {
     this.authService = authService;
     this.userService = userService;
 }
Esempio n. 41
0
        /// <summary>
        /// Load the static Authorizations object
        /// </summary>
        public static void Load()
        {
            Authorizations = new Dictionary<string, Dictionary<int, Dictionary<string, List<AuthRule>>>>();

            AuthService authService = new AuthService();

            foreach ( Auth auth in authService.Queryable().
                OrderBy( A => A.EntityType ).ThenBy( A => A.EntityId ).ThenBy( A => A.Action ).ThenBy( A => A.Order ) )
            {
                if ( !Authorizations.ContainsKey( auth.EntityType ) )
                    Authorizations.Add( auth.EntityType, new Dictionary<int, Dictionary<string, List<AuthRule>>>() );
                Dictionary<int, Dictionary<string, List<AuthRule>>> entityAuths = Authorizations[auth.EntityType];

                if ( !entityAuths.ContainsKey( auth.EntityId ?? 0 ) )
                    entityAuths.Add( auth.EntityId ?? 0, new Dictionary<string, List<AuthRule>>() );
                Dictionary<string, List<AuthRule>> instanceAuths = entityAuths[auth.EntityId ?? 0];

                if ( !instanceAuths.ContainsKey( auth.Action ) )
                    instanceAuths.Add( auth.Action, new List<AuthRule>() );
                List<AuthRule> actionPermissions = instanceAuths[auth.Action];

                actionPermissions.Add( new AuthRule(
                    auth.AllowOrDeny,
                    auth.UserOrRole,
                    auth.UserOrRoleName ) );
            }
        }
        private async Task <Response> LoginUser()
        {
            var userId         = string.Empty;
            var dateTimeOffset = Request.Form.DateTimeOffset;
            var username       = Request.Form.username.Value;

            Log.Debug("Username \"{0}\" attempting to login", username);
            if (string.IsNullOrWhiteSpace(username))
            {
                Session["TempMessage"] = Resources.UI.UserLogin_IncorrectUserPass;
                var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex");
                return(Response.AsRedirect(uri.ToString()));  // TODO Check this
            }

            var authenticated = false;

            var settings = await AuthService.GetSettingsAsync();

            var plexSettings = await PlexSettings.GetSettingsAsync();

            if (IsUserInDeniedList(username, settings))
            {
                Log.Debug("User is in denied list, not allowing them to authenticate");
                Session["TempMessage"] = Resources.UI.UserLogin_IncorrectUserPass;
                var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex");
                return(Response.AsRedirect(uri.ToString()));  // TODO Check this
            }

            var password = string.Empty;

            if (settings.UsePassword)
            {
                Log.Debug("Using password");
                password = Request.Form.password.Value;
            }


            if (settings.UserAuthentication && settings.UsePassword) // Authenticate with Plex
            {
                Log.Debug("Need to auth and also provide pass");
                var signedIn = (PlexAuthentication)Api.SignIn(username, password);
                if (signedIn.user?.authentication_token != null)
                {
                    Log.Debug("Correct credentials, checking if the user is account owner or in the friends list");
                    if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, signedIn.user?.username))
                    {
                        Log.Debug("User is the account owner");
                        authenticated = true;
                    }
                    else
                    {
                        authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
                        Log.Debug("Friends list result = {0}", authenticated);
                    }
                    userId = signedIn.user.uuid;
                }
            }
            else if (settings.UserAuthentication) // Check against the users in Plex
            {
                Log.Debug("Need to auth");
                authenticated = CheckIfUserIsInPlexFriends(username, plexSettings.PlexAuthToken);
                if (authenticated)
                {
                    userId = GetUserIdIsInPlexFriends(username, plexSettings.PlexAuthToken);
                }
                if (CheckIfUserIsOwner(plexSettings.PlexAuthToken, username))
                {
                    Log.Debug("User is the account owner");
                    authenticated = true;
                    userId        = GetOwnerId(plexSettings.PlexAuthToken, username);
                }
                Log.Debug("Friends list result = {0}", authenticated);
            }
            else if (!settings.UserAuthentication) // No auth, let them pass!
            {
                Log.Debug("No need to auth");
                authenticated = true;
            }

            if (authenticated)
            {
                UserLogins.Insert(new UserLogins {
                    UserId = userId, Type = UserType.PlexUser, LastLoggedIn = DateTime.UtcNow
                });
                Log.Debug("We are authenticated! Setting session.");
                // Add to the session (Used in the BaseModules)
                Session[SessionKeys.UsernameKey]             = (string)username;
                Session[SessionKeys.ClientDateTimeOffsetKey] = (int)dateTimeOffset;
            }

            if (!authenticated)
            {
                var uri = Linker.BuildRelativeUri(Context, "UserLoginIndex");
                Session["TempMessage"] = Resources.UI.UserLogin_IncorrectUserPass;
                return(Response.AsRedirect(uri.ToString())); // TODO Check this
            }

            var landingSettings = await LandingPageSettings.GetSettingsAsync();

            if (landingSettings.Enabled)
            {
                if (!landingSettings.BeforeLogin)
                {
                    var uri = Linker.BuildRelativeUri(Context, "LandingPageIndex");
                    return(Response.AsRedirect(uri.ToString()));
                }
            }
            var retVal = Linker.BuildRelativeUri(Context, "SearchIndex");

            return(Response.AsRedirect(retVal.ToString())); // TODO Check this
        }
 public void Setup()
 {
     var restClient = new WorldpayRestClient(Configuration.ServiceKey);
     _authService = restClient.GetAuthService();
     _orderService = restClient.GetOrderService();
 }
        public async Task <ActionResult <User> > Authenticated([FromServices] AuthService authService)
        {
            User user = await authService.getAuthUser(User.Identity.Name);

            return(user);
        }
Esempio n. 45
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// </summary>
        /// <param name="services">The injected services provider.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            this.logger.LogDebug("Starting Service Configuration...");
            services.AddHttpClient();
            services.AddResponseCompression(options =>
            {
                options.Providers.Add <GzipCompressionProvider>();
                options.EnableForHttps = true;
            });
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultSignInScheme       = CookieAuthenticationDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddCookie()
            .AddOpenIdConnect(o =>
            {
                this.configuration.GetSection("OpenIdConnect").Bind(o);
                if (string.IsNullOrEmpty(o.Authority))
                {
                    this.logger.LogCritical("OpenIdConnect Authority is missing, bad things are going to occur");
                }

                o.Events = new OpenIdConnectEvents()
                {
                    OnTokenValidated = ctx =>
                    {
                        JwtSecurityToken accessToken = ctx.SecurityToken;
                        if (accessToken != null)
                        {
                            ClaimsIdentity identity = ctx.Principal.Identity as ClaimsIdentity;
                            if (identity != null)
                            {
                                identity.AddClaim(new Claim("access_token", accessToken.RawData));
                            }
                        }

                        return(Task.CompletedTask);
                    },
                    OnRedirectToIdentityProvider = ctx =>
                    {
                        if (ctx.Properties.Items.ContainsKey(this.configuration["KeyCloak:IDPHintKey"]))
                        {
                            this.logger.LogDebug("Adding IDP Hint passed in from client to provider");
                            ctx.ProtocolMessage.SetParameter(
                                this.configuration["KeyCloak:IDPHintKey"], ctx.Properties.Items[this.configuration["KeyCloak:IDPHintKey"]]);
                        }
                        else
                        {
                            if (!string.IsNullOrEmpty(this.configuration["KeyCloak:IDPHint"]))
                            {
                                this.logger.LogDebug("Adding IDP Hint on Redirect to provider");
                                ctx.ProtocolMessage.SetParameter(this.configuration["KeyCloak:IDPHintKey"], this.configuration["KeyCloak:IDPHint"]);
                            }
                        }

                        return(Task.FromResult(0));
                    },
                    OnAuthenticationFailed = c =>
                    {
                        c.HandleResponse();
                        c.Response.StatusCode  = 500;
                        c.Response.ContentType = "text/plain";
                        this.logger.LogError(c.Exception.ToString());
                        return(c.Response.WriteAsync(c.Exception.ToString()));
                    },
                };
            });

            // Auth Service
            services.AddTransient <IAuthService>(serviceProvider =>
            {
                this.logger.LogDebug("Configuring Transient Service IAuthService");
                IAuthService service = new AuthService(
                    serviceProvider.GetService <ILogger <AuthService> >(),
                    serviceProvider.GetService <IHttpContextAccessor>(),
                    serviceProvider.GetService <IConfiguration>());
                return(service);
            });

            // Inject HttpContextAccessor
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services
            .AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.Configure <SwaggerSettings>(this.configuration.GetSection(nameof(SwaggerSettings)));

            services
            .AddApiVersionWithExplorer()
            .AddSwaggerOptions()
            .AddSwaggerGen();
        }
        public override   Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            try
            {
                if (!context.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
                    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
                
                var clientId = default(string);
                var clientSecret = default(string);
                var client = default(Client);

                if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
                {
                    context.TryGetFormCredentials(out clientId, out clientSecret);
                }

                if (context.ClientId == null)
                {
                    // Remove the comments from the below line context.SetError, and invalidate context 
                    // if you want to force sending clientId/secrects once obtain access tokens. 
                    context.Validated();

                    // context.SetError("invalid_clientId", "ClientId should be sent.");

                    return Task.FromResult<object>(null);
                }
                using (AuthService _repo = new AuthService())
                {
                    client = _repo.FindClient(context.ClientId).Result;
                }
                if (client == null)
                {
                    context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));

                    return Task.FromResult<object>(null);
                }

                if (client.ApplicationType == ApplicationTypes.NativeConfidential)
                {
                    if (string.IsNullOrWhiteSpace(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret should be sent.");

                        return Task.FromResult<object>(null);
                    }
                    else
                    {
                        if (client.Secret != Helper.GetHash(clientSecret))
                        {
                            context.SetError("invalid_clientId", "Client secret is invalid.");

                            return Task.FromResult<object>(null);
                        }
                    }
                }

                if (!client.Active)
                {
                    context.SetError("invalid_clientId", "Client is inactive.");

                    return Task.FromResult<object>(null);
                }

                context.OwinContext.Set<string>("as:clientAllowedOrigin", client.AllowedOrigin);
                context.OwinContext.Set<string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

                context.Validated();
            }
            catch (Exception exp)
            { }
            return Task.FromResult<object>(null);
        }