Ejemplo n.º 1
0
 /// <summary>
 /// Updates the auth state with a queue of
 /// <see cref="AuthOption">AuthOption</see>
 /// s.
 /// </summary>
 /// <param name="authOptions">a queue of auth options. May not be null or empty.</param>
 /// <since>4.2</since>
 public virtual void Update(Queue <AuthOption> authOptions)
 {
     Args.NotEmpty(authOptions, "Queue of auth options");
     this.authOptions = authOptions;
     this.authScheme  = null;
     this.credentials = null;
 }
Ejemplo n.º 2
0
        private void DoPreemptiveAuth(HttpHost host, AuthScheme authScheme, AuthState authState
                                      , CredentialsProvider credsProvider)
        {
            string schemeName = authScheme.GetSchemeName();

            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Re-using cached '" + schemeName + "' auth scheme for " + host);
            }
            AuthScope   authScope = new AuthScope(host, AuthScope.AnyRealm, schemeName);
            Credentials creds     = credsProvider.GetCredentials(authScope);

            if (creds != null)
            {
                if (Sharpen.Runtime.EqualsIgnoreCase("BASIC", authScheme.GetSchemeName()))
                {
                    authState.SetState(AuthProtocolState.Challenged);
                }
                else
                {
                    authState.SetState(AuthProtocolState.Success);
                }
                authState.Update(authScheme, creds);
            }
            else
            {
                this.log.Debug("No credentials for preemptive authentication");
            }
        }
        public virtual void AuthSucceeded(HttpHost authhost, AuthScheme authScheme, HttpContext
                                          context)
        {
            Args.NotNull(authhost, "Host");
            Args.NotNull(authScheme, "Auth scheme");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));

            if (IsCachable(authScheme))
            {
                AuthCache authCache = clientContext.GetAuthCache();
                if (authCache == null)
                {
                    authCache = new BasicAuthCache();
                    clientContext.SetAuthCache(authCache);
                }
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Caching '" + authScheme.GetSchemeName() + "' auth scheme for " +
                                   authhost);
                }
                authCache.Put(authhost, authScheme);
            }
        }
Ejemplo n.º 4
0
 public AuthOption(AuthScheme authScheme, Credentials creds) : base()
 {
     Args.NotNull(authScheme, "Auth scheme");
     Args.NotNull(creds, "User credentials");
     this.authScheme = authScheme;
     this.creds      = creds;
 }
Ejemplo n.º 5
0
        public ProtoSchemes()
        {
            byte id = 0;

            AuthNonce = new AuthNonceScheme(messageId: id++);
            Auth      = new AuthScheme(messageId: id++);
            AuthOk    = new AuthOkScheme(messageId: id++);
            Error     = new ErrorScheme(messageId: id++);

            Order       = new OrderScheme(messageId: id++);
            OrderSend   = new OrderSendScheme(messageId: id++);
            OrderCancel = new OrderCancelScheme(messageId: id++);
            OrderStatus = new OrderStatusScheme(messageId: id++);
            Orders      = new OrdersScheme(messageId: id++);

            Swap         = new SwapScheme(messageId: id++);
            SwapInitiate = new SwapInitiateScheme(messageId: id++);
            SwapAccept   = new SwapAcceptScheme(messageId: id++);
            SwapStatus   = new SwapStatusScheme(messageId: id++);
            Swaps        = new SwapsScheme(messageId: id++);

            Subscribe   = new SubscribeScheme(messageId: id++);
            Unsubscribe = new UnsubscribeScheme(messageId: id++);
            Quotes      = new QuotesScheme(messageId: id++);
            Entries     = new EntriesScheme(messageId: id++);
            Snapshot    = new SnapshotScheme(messageId: id++);
            OrderLog    = new OrderLogScheme(messageId: id++);

            HeartBeat = new HeartBeatScheme(messageId: id);
        }
Ejemplo n.º 6
0
 public static DataSet.SubscriberRow PublishSubscriber(AuthScheme authScheme)
 {
     DataSet.SubscriberDataTable dt = new DataSet.SubscriberDataTable();
     SubscriberTableAdapter ta = new SubscriberTableAdapter();
     dt.AddSubscriberRow(SiteConstant.Title, Guid.NewGuid().ToString("N"), authScheme.ToString(), Constant.Ago);
     ta.Update(dt);
     return dt[0];
 }
Ejemplo n.º 7
0
 /// <summary>Resets the auth state.</summary>
 /// <remarks>Resets the auth state.</remarks>
 /// <since>4.2</since>
 public virtual void Reset()
 {
     this.state       = AuthProtocolState.Unchallenged;
     this.authOptions = null;
     this.authScheme  = null;
     this.authScope   = null;
     this.credentials = null;
 }
Ejemplo n.º 8
0
 /// <summary>
 /// Updates the auth state with
 /// <see cref="AuthScheme">AuthScheme</see>
 /// and
 /// <see cref="Credentials">Credentials</see>
 /// .
 /// </summary>
 /// <param name="authScheme">auth scheme. May not be null.</param>
 /// <param name="credentials">user crednetials. May not be null.</param>
 /// <since>4.2</since>
 public virtual void Update(AuthScheme authScheme, Credentials credentials)
 {
     Args.NotNull(authScheme, "Auth scheme");
     Args.NotNull(credentials, "Credentials");
     this.authScheme  = authScheme;
     this.credentials = credentials;
     this.authOptions = null;
 }
Ejemplo n.º 9
0
 public virtual void SetAuthScheme(AuthScheme authScheme)
 {
     if (authScheme == null)
     {
         Reset();
         return;
     }
     this.authScheme = authScheme;
 }
Ejemplo n.º 10
0
        public Credentials getCredentials(AuthScheme scheme, string __p2, int __p3, bool __p4)
        {
            if (scheme.isComplete())
            {
                return(null);
            }
            GSSCredential creds = m_internalProvider.getCredentials();

            return(new DelegatedCredentials(creds));
        }
        protected internal virtual bool IsCachable(AuthScheme authScheme)
        {
            if (authScheme == null || !authScheme.IsComplete())
            {
                return(false);
            }
            string schemeName = authScheme.GetSchemeName();

            return(Sharpen.Runtime.EqualsIgnoreCase(schemeName, AuthSchemes.Basic) || Sharpen.Runtime.EqualsIgnoreCase
                       (schemeName, AuthSchemes.Digest));
        }
Ejemplo n.º 12
0
 /// <exception cref="Apache.Http.Auth.AuthenticationException"></exception>
 private Header DoAuth(AuthScheme authScheme, Credentials creds, IHttpRequest request
                       , HttpContext context)
 {
     if (authScheme is ContextAwareAuthScheme)
     {
         return(((ContextAwareAuthScheme)authScheme).Authenticate(creds, request, context));
     }
     else
     {
         return(authScheme.Authenticate(creds, request));
     }
 }
Ejemplo n.º 13
0
        /// <exception cref="Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void Process(IHttpRequest request, HttpContext context)
        {
            Args.NotNull(request, "HTTP request");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            AuthCache authCache = clientContext.GetAuthCache();

            if (authCache == null)
            {
                this.log.Debug("Auth cache not set in the context");
                return;
            }
            CredentialsProvider credsProvider = clientContext.GetCredentialsProvider();

            if (credsProvider == null)
            {
                this.log.Debug("Credentials provider not set in the context");
                return;
            }
            RouteInfo route  = clientContext.GetHttpRoute();
            HttpHost  target = clientContext.GetTargetHost();

            if (target.GetPort() < 0)
            {
                target = new HttpHost(target.GetHostName(), route.GetTargetHost().GetPort(), target
                                      .GetSchemeName());
            }
            AuthState targetState = clientContext.GetTargetAuthState();

            if (targetState != null && targetState.GetState() == AuthProtocolState.Unchallenged)
            {
                AuthScheme authScheme = authCache.Get(target);
                if (authScheme != null)
                {
                    DoPreemptiveAuth(target, authScheme, targetState, credsProvider);
                }
            }
            HttpHost  proxy      = route.GetProxyHost();
            AuthState proxyState = clientContext.GetProxyAuthState();

            if (proxy != null && proxyState != null && proxyState.GetState() == AuthProtocolState
                .Unchallenged)
            {
                AuthScheme authScheme = authCache.Get(proxy);
                if (authScheme != null)
                {
                    DoPreemptiveAuth(proxy, authScheme, proxyState, credsProvider);
                }
            }
        }
        private static Principal GetAuthPrincipal(AuthState authState)
        {
            AuthScheme scheme = authState.GetAuthScheme();

            if (scheme != null && scheme.IsComplete() && scheme.IsConnectionBased())
            {
                Credentials creds = authState.GetCredentials();
                if (creds != null)
                {
                    return(creds.GetUserPrincipal());
                }
            }
            return(null);
        }
Ejemplo n.º 15
0
        public async Task TestCreateUser(AuthScheme authscheme, string roleId)
        {
            // Arrange
            var  email = "*****@*****.**";
            User user  = authscheme == AuthScheme.AzureADB2BGuest ? null : new User()
            {
                Email = email
            };

            var request = GetNewUserRequest(roleId);

            Mock <IReCaptchaService> reCaptchaMock = null;

            if (authscheme == AuthScheme.AzureADB2BGuest)
            {
                request.Email            = email;
                request.RecaptchaPayload = "recaptchaPayload";

                reCaptchaMock = new Mock <IReCaptchaService>();
                reCaptchaMock.Setup(a => a.ValidatePayload(It.IsAny <string>())).Returns(Task.FromResult(new ReCaptchaResponse()
                {
                    Success     = true,
                    ErrorCodes  = null,
                    ChallengeTs = null,
                }));
            }

            // Act
            var result = await GetUsersController(user, authscheme, reCaptchaMock : reCaptchaMock).Create(request);

            // Assert
            var expectedResult = new OkObjectResult(ExpectedUserResponse(email, request, roleId));

            result.Result.Should().BeEquivalentTo(expectedResult);

            var expectedUserRow = ExpectedUserRow(user, request);
            var userRow         = db.User.Single(u => u.Email == email);

            userRow.Should().BeEquivalentTo(expectedUserRow, options => options.Excluding(u => u.Id).Excluding(u => u.Request).Excluding(u => u.Role.Users).Excluding(u => u.UserStatus.Users));

            if (authscheme == AuthScheme.AzureADB2BGuest)
            {
                reCaptchaMock.Verify(reCaptcha => reCaptcha.ValidatePayload(request.RecaptchaPayload), Times.Once());
            }
        }
        public virtual void AuthFailed(HttpHost authhost, AuthScheme authScheme, HttpContext
                                       context)
        {
            Args.NotNull(authhost, "Host");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            AuthCache authCache = clientContext.GetAuthCache();

            if (authCache != null)
            {
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug("Clearing cached auth scheme for " + authhost);
                }
                authCache.Remove(authhost);
            }
        }
        public HttpCommunicationWorker(string baseUrl, string base64Auth, AuthScheme schemeToUse)
        {
            this.baseUrl = new Uri(baseUrl);

            switch (schemeToUse)
            {
            case AuthScheme.Basic:
                SetBasicAuthentication(base64Auth);
                break;

            case AuthScheme.Bearer:
                SetBearerAuthentication(base64Auth);
                break;

            default:
                throw new ApplicationException("Unsupported authentication scheme");
            }
        }
        /// <summary>
        /// Creates a new instance of System.Net.Http.HttpClient
        /// </summary>
        /// <remarks>Should only be instantiated onces</remarks>
        private void SetupHttpClient(string baseUrl, string base64Auth, AuthScheme schemeToUse)
        {
            httpClient.BaseAddress = new Uri(baseUrl);

            switch (schemeToUse)
            {
            case AuthScheme.Basic:
                SetBasicAuthentication(base64Auth);
                break;

            case AuthScheme.Bearer:
                SetBearerAuthentication(base64Auth);
                break;

            default:
                throw new ApplicationException("Unsupported authentication scheme");
            }
        }
Ejemplo n.º 19
0
        public static object AuthSchemeGetter(IPropertyBag propertyBag)
        {
            MultiValuedProperty <string> multiValuedProperty = (MultiValuedProperty <string>)propertyBag[AuthRedirectSchema.Keywords];
            string     value      = multiValuedProperty.Find((string x) => !string.Equals(x, AuthRedirect.AuthRedirectKeywords, StringComparison.OrdinalIgnoreCase));
            AuthScheme authScheme = Microsoft.Exchange.Data.Directory.SystemConfiguration.AuthScheme.Unknown;

            if (!string.IsNullOrEmpty(value))
            {
                try
                {
                    authScheme = (AuthScheme)Enum.Parse(typeof(AuthScheme), value, true);
                }
                catch (ArgumentException)
                {
                }
            }
            return(authScheme);
        }
Ejemplo n.º 20
0
 public static DataSet.SubscriberRow ResolveSubscriber(string tokenBody, AuthScheme authScheme)
 {
     if (tokenBody == null)
     {
         return PublishSubscriber(authScheme);
     }
     TokenTableAdapter tta = new TokenTableAdapter();
     DataSet.TokenDataTable tdt = tta.GetDataByBody(tokenBody);
     if (tdt.Count == 0)
     {
         return PublishSubscriber(authScheme);
     }
     DataSet.TokenRow token = tdt[0];
     SubscriberTableAdapter sta = new SubscriberTableAdapter();
     DataSet.SubscriberRow subscriber = sta.GetDataById(token.SubscriberId)[0];
     if (subscriber.AuthScheme != authScheme.ToString())
     {
         throw new DoubtfulAuthBehaviorException("�F�؃g�[�N�������s���ꂽ�Ƃ��Ƃ͈قȂ�F�ؕ����œn����܂����B");
     }
     return subscriber;
 }
        public virtual Scheme getSchemeFromPanRange(PANRange binRange)
        {
            if (binRange != null)
            {
                // Have a range - see what scheme it thinks it is.
                Scheme     scheme         = null;
                AuthScheme cardAuthScheme = binRange.Scheme;
                if (cardAuthScheme != null)
                {
                    switch (cardAuthScheme)
                    {
                    case AuthScheme.VISA:
                        //scheme = visaScheme;
                        break;

                    case AuthScheme.MASTERCARD:
                        //scheme = mastercardScheme;
                        break;

                    case AuthScheme.AMEX:
                        //scheme = amexScheme;
                        break;
                    }
                }
                if (scheme == null)
                {
                    //LOGGER.error("Couldn't determine AuthScheme for available PanRange");
                    return(null);
                }
                else
                {
                    return(scheme);
                }
            }
            else
            {
                //LOGGER.error("Couldn't determine PanRange scheme for card.");
                return(null);
            }
        }
        public override void stageExecute(SalePostContext context)
        {
            ActionStatistics schemeStats = context.getTerminalSchemeStatitics();
            AuthScheme       scheme      = context.saleBuild().AuthScheme;

            if ((scheme != null) && (schemeStats != null))
            {
                if (terminalStatsCheckUtility.isUnderThreshold(schemeStats, scheme))
                {
                    nextStage(context);
                }
                else
                {
                    // Over threshold and approval rate too low - Block the transaction.
                    context.responseBuilder().ResponseCode = ResponseCode.SCHEME_AUTH_LIMIT_REACHED;
                }
            }
            else
            {
                // Cannot get stats, can't guarantee won't exceed limits, so have to decline.
                //Logger.error("Cannot get scheme statistics, or determine scheme - " + "Rejecting transaction");
                context.responseBuilder().ResponseCode = ResponseCode.COULD_NOT_CHECK_AUTH_LIMIT;
            }
        }
        /// <exception cref="Apache.Http.Auth.MalformedChallengeException"></exception>
        public virtual Queue <AuthOption> Select(IDictionary <string, Header> challenges, HttpHost
                                                 authhost, HttpResponse response, HttpContext context)
        {
            Args.NotNull(challenges, "Map of auth challenges");
            Args.NotNull(authhost, "Host");
            Args.NotNull(response, "HTTP response");
            Args.NotNull(context, "HTTP context");
            HttpClientContext clientContext = ((HttpClientContext)HttpClientContext.Adapt(context
                                                                                          ));
            Queue <AuthOption>          options  = new List <AuthOption>();
            Lookup <AuthSchemeProvider> registry = clientContext.GetAuthSchemeRegistry();

            if (registry == null)
            {
                this.log.Debug("Auth scheme registry not set in the context");
                return(options);
            }
            CredentialsProvider credsProvider = clientContext.GetCredentialsProvider();

            if (credsProvider == null)
            {
                this.log.Debug("Credentials provider not set in the context");
                return(options);
            }
            RequestConfig        config    = clientContext.GetRequestConfig();
            ICollection <string> authPrefs = GetPreferredAuthSchemes(config);

            if (authPrefs == null)
            {
                authPrefs = DefaultSchemePriority;
            }
            if (this.log.IsDebugEnabled())
            {
                this.log.Debug("Authentication schemes in the order of preference: " + authPrefs);
            }
            foreach (string id in authPrefs)
            {
                Header challenge = challenges.Get(id.ToLower(CultureInfo.InvariantCulture));
                if (challenge != null)
                {
                    AuthSchemeProvider authSchemeProvider = registry.Lookup(id);
                    if (authSchemeProvider == null)
                    {
                        if (this.log.IsWarnEnabled())
                        {
                            this.log.Warn("Authentication scheme " + id + " not supported");
                        }
                        // Try again
                        continue;
                    }
                    AuthScheme authScheme = authSchemeProvider.Create(context);
                    authScheme.ProcessChallenge(challenge);
                    AuthScope authScope = new AuthScope(authhost.GetHostName(), authhost.GetPort(), authScheme
                                                        .GetRealm(), authScheme.GetSchemeName());
                    Credentials credentials = credsProvider.GetCredentials(authScope);
                    if (credentials != null)
                    {
                        options.AddItem(new AuthOption(authScheme, credentials));
                    }
                }
                else
                {
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Challenge for " + id + " authentication scheme not available");
                    }
                }
            }
            // Try again
            return(options);
        }
Ejemplo n.º 24
0
		public Credentials getCredentials (AuthScheme scheme, string __p2, int __p3, bool __p4) {
			if (scheme.isComplete ())
				return null;			
			GSSCredential creds = m_internalProvider.getCredentials ();			
			return new DelegatedCredentials (creds);
		}
Ejemplo n.º 25
0
        public virtual bool HandleAuthChallenge(HttpHost host, HttpResponse response, AuthenticationStrategy
                                                authStrategy, AuthState authState, HttpContext context)
        {
            try
            {
                if (this.log.IsDebugEnabled())
                {
                    this.log.Debug(host.ToHostString() + " requested authentication");
                }
                IDictionary <string, Header> challenges = authStrategy.GetChallenges(host, response
                                                                                     , context);
                if (challenges.IsEmpty())
                {
                    this.log.Debug("Response contains no authentication challenges");
                    return(false);
                }
                AuthScheme authScheme = authState.GetAuthScheme();
                switch (authState.GetState())
                {
                case AuthProtocolState.Failure:
                {
                    return(false);
                }

                case AuthProtocolState.Success:
                {
                    authState.Reset();
                    break;
                }

                case AuthProtocolState.Challenged:
                case AuthProtocolState.Handshake:
                {
                    if (authScheme == null)
                    {
                        this.log.Debug("Auth scheme is null");
                        authStrategy.AuthFailed(host, null, context);
                        authState.Reset();
                        authState.SetState(AuthProtocolState.Failure);
                        return(false);
                    }
                    goto case AuthProtocolState.Unchallenged;
                }

                case AuthProtocolState.Unchallenged:
                {
                    if (authScheme != null)
                    {
                        string id        = authScheme.GetSchemeName();
                        Header challenge = challenges.Get(id.ToLower(CultureInfo.InvariantCulture));
                        if (challenge != null)
                        {
                            this.log.Debug("Authorization challenge processed");
                            authScheme.ProcessChallenge(challenge);
                            if (authScheme.IsComplete())
                            {
                                this.log.Debug("Authentication failed");
                                authStrategy.AuthFailed(host, authState.GetAuthScheme(), context);
                                authState.Reset();
                                authState.SetState(AuthProtocolState.Failure);
                                return(false);
                            }
                            else
                            {
                                authState.SetState(AuthProtocolState.Handshake);
                                return(true);
                            }
                        }
                        else
                        {
                            authState.Reset();
                        }
                    }
                }
                }
                // Retry authentication with a different scheme
                Queue <AuthOption> authOptions = authStrategy.Select(challenges, host, response, context
                                                                     );
                if (authOptions != null && !authOptions.IsEmpty())
                {
                    if (this.log.IsDebugEnabled())
                    {
                        this.log.Debug("Selected authentication options: " + authOptions);
                    }
                    authState.SetState(AuthProtocolState.Challenged);
                    authState.Update(authOptions);
                    return(true);
                }
                else
                {
                    return(false);
                }
            }
            catch (MalformedChallengeException ex)
            {
                if (this.log.IsWarnEnabled())
                {
                    this.log.Warn("Malformed challenge: " + ex.Message);
                }
                authState.Reset();
                return(false);
            }
        }
Ejemplo n.º 26
0
 private void EnsureAuthScheme(AuthScheme authScheme)
 {
     Asserts.NotNull(authScheme, "Auth scheme");
 }
Ejemplo n.º 27
0
        /// <exception cref="Apache.Http.HttpException"></exception>
        /// <exception cref="System.IO.IOException"></exception>
        public virtual void GenerateAuthResponse(IHttpRequest request, AuthState authState
                                                 , HttpContext context)
        {
            AuthScheme  authScheme = authState.GetAuthScheme();
            Credentials creds      = authState.GetCredentials();

            switch (authState.GetState())
            {
            case AuthProtocolState.Failure:
            {
                return;
            }

            case AuthProtocolState.Success:
            {
                EnsureAuthScheme(authScheme);
                if (authScheme.IsConnectionBased())
                {
                    return;
                }
                break;
            }

            case AuthProtocolState.Challenged:
            {
                Queue <AuthOption> authOptions = authState.GetAuthOptions();
                if (authOptions != null)
                {
                    while (!authOptions.IsEmpty())
                    {
                        AuthOption authOption = authOptions.Remove();
                        authScheme = authOption.GetAuthScheme();
                        creds      = authOption.GetCredentials();
                        authState.Update(authScheme, creds);
                        if (this.log.IsDebugEnabled())
                        {
                            this.log.Debug("Generating response to an authentication challenge using " + authScheme
                                           .GetSchemeName() + " scheme");
                        }
                        try
                        {
                            Header header = DoAuth(authScheme, creds, request, context);
                            request.AddHeader(header);
                            break;
                        }
                        catch (AuthenticationException ex)
                        {
                            if (this.log.IsWarnEnabled())
                            {
                                this.log.Warn(authScheme + " authentication error: " + ex.Message);
                            }
                        }
                    }
                    return;
                }
                else
                {
                    EnsureAuthScheme(authScheme);
                }
            }
            }
            if (authScheme != null)
            {
                try
                {
                    Header header = DoAuth(authScheme, creds, request, context);
                    request.AddHeader(header);
                }
                catch (AuthenticationException ex)
                {
                    if (this.log.IsErrorEnabled())
                    {
                        this.log.Error(authScheme + " authentication error: " + ex.Message);
                    }
                }
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// 使用认证
 /// </summary>
 /// <param name="scheme">认证类型</param>
 /// <param name="auth">认证数据</param>
 public void Authorize(AuthScheme scheme, string auth = "")
 {
     CheckConnection();
     zookeeper.addAuthInfo(scheme.ToString().ToLower(), Encoding.GetBytes(auth));
 }
 public virtual CostDesignatorParameters determineParameters(SchemeAuthorisationResult schemeAuthResult, AuthScheme authScheme, Sale sale)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 30
0
 public bool IsAuthScheme(AuthScheme authScheme)
 {
     return subscriber.AuthScheme == authScheme.ToString();
 }
 public virtual string generateARN(ResponseCode responseCode, string bid, AuthScheme scheme, DateTime timestamp, params core_develop.cashflows.core.authorisation.Action[] successActions)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 32
0
        public static IServiceCollection AddFreshly(this IServiceCollection services, AuthScheme scheme, Action <FreshlyOptions> defaults)
        {
            defaults?.Invoke(D);
            SetDefaults(D);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>()
            .AddTransient <IAuthorizationHandler, AccessRuleHandler>()
            .AddTransient <UserManager>()
            .AddTransient <GroupManager>();

            if (scheme == AuthScheme.Cookie)
            {
                services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(option =>
                {
                    option.LoginPath         = new PathString("/account/login");
                    option.AccessDeniedPath  = new PathString("/error/accessdenied");
                    option.SlidingExpiration = true;
                    option.ExpireTimeSpan    = TimeSpan.FromMinutes(15);
                    option.Cookie            = new CookieBuilder()
                    {
                        Domain = D.CookieDomain
                    };
                    option.Events.OnValidatePrincipal = CookieEvents.ValidateAsync;
                });
                services.AddAuthorization(options =>
                {
                    if (D.Policies.Count > 0)
                    {
                        foreach (var ar in D.Policies)
                        {
                            options.AddPolicy(ar, policy => {
                                policy.RequireAuthenticatedUser();
                                policy.Requirements.Add(new AccessRuleRequirement(ar));
                                //policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme);
                            });
                        }
                    }
                });
            }
            else if (scheme == AuthScheme.JwtBearer)
            {
                services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(option =>
                {
                    option.RequireHttpsMetadata      = true;
                    option.SaveToken                 = true;
                    option.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = true,
                        ValidIssuer      = D.TokenIssuer,
                        ValidAudience    = D.TokenAudience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(D.TokenKey))
                    };
                });
                services.AddAuthorization(options =>
                {
                    if (D.Policies.Count > 0)
                    {
                        foreach (var ar in D.Policies)
                        {
                            options.AddPolicy(ar, policy => {
                                policy.RequireAuthenticatedUser();
                                policy.Requirements.Add(new AccessRuleRequirement(ar));
                                //policy.AddAuthenticationSchemes(JwtBearerDefaults.AuthenticationScheme);
                            });
                        }
                    }
                });
            }
            else if (scheme == AuthScheme.Both)
            {
                services.AddAuthentication()//CookieAuthenticationDefaults.AuthenticationScheme)
                .AddCookie(option =>
                {
                    option.LoginPath         = new PathString("/account/login");
                    option.AccessDeniedPath  = new PathString("/error/accessdenied");
                    option.SlidingExpiration = true;
                    option.ExpireTimeSpan    = TimeSpan.FromMinutes(15);
                    option.Cookie            = new CookieBuilder()
                    {
                        HttpOnly = true,
                        Domain   = D.CookieDomain
                    };
                    option.Events.OnValidatePrincipal = CookieEvents.ValidateAsync;
                })
                .AddJwtBearer(option =>
                {
                    option.RequireHttpsMetadata      = true;
                    option.SaveToken                 = true;
                    option.TokenValidationParameters = new TokenValidationParameters()
                    {
                        ValidateIssuerSigningKey = true,
                        ValidIssuer      = D.TokenIssuer,
                        ValidAudience    = D.TokenAudience,
                        IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(D.TokenKey))
                    };
                });
                services.AddAuthorization(options =>
                {
                    //var defaultAuthorizationPolicyBuilder = new AuthorizationPolicyBuilder(
                    //CookieAuthenticationDefaults.AuthenticationScheme,
                    //JwtBearerDefaults.AuthenticationScheme);
                    //defaultAuthorizationPolicyBuilder = defaultAuthorizationPolicyBuilder.RequireAuthenticatedUser();
                    //options.DefaultPolicy = defaultAuthorizationPolicyBuilder.Build();

                    if (D.Policies.Count > 0)
                    {
                        foreach (var ar in D.Policies)
                        {
                            options.AddPolicy(ar, policy => {
                                policy.RequireAuthenticatedUser();
                                policy.Requirements.Add(new AccessRuleRequirement(ar));
                                policy.AddAuthenticationSchemes(CookieAuthenticationDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme);
                            });
                        }
                    }
                });
            }

            return(services);
        }
        private ResponseCode checkSchemeFundsRecipient(PANRange binRange, Terminal terminal, FundsRecipient recipient, AuthScheme authScheme, bool debtRepayFlag)
        {
            ResponseCode?errorCode           = null;;
            bool         isVisaFinancial     = VisaMerchantClassificationGroup.FINANCAL_INSTITUTION.contains(terminal.MCC);
            bool         isVisaDebtRepayment = VisaMerchantClassificationGroup.DEBT_REPAYMENT.contains(terminal.MCC) && isDebtRepaySale;

            if ((binRange.IssueCountry == Country.GB) && (terminal.Country == Country.GB) && (((isVisaFinancial || isVisaDebtRepayment) && authScheme == AuthScheme.VISA) || (isDebtRepaySale && authScheme == AuthScheme.MASTERCARD)))
            {
                //Logger.info(authScheme.name() + " Funds Recipient data is required for this Sale");
                bool dataMissing;

                // VISA : GB merchant and shopper, and an 6012 or 7299 merchant
                // MC : if debt repayment transaction
                // Then - All FraudRecipient fields are required..
                dataMissing = (recipient == null);
                if (recipient != null)
                {
                    dataMissing |= (recipient.DateOfBirth == null);
                    dataMissing |= missingRecipientData(recipient.AccountNumber);
                    dataMissing |= missingRecipientData(recipient.PostalCode);
                    dataMissing |= missingRecipientData(recipient.Surname);
                }
                if (dataMissing)
                {
                    //Logger.info("Not all Funds Recipient data was provided");
                    errorCode = ResponseCode.FUNDSRECIPIENT_MISSING;
                }
                else
                {
                    // .. and the postcode must look like a UK one.
                    if (missingRecipientData(recipient.UKPostalCodePrefix))
                    {
                        //Logger.info("Recipient Postal code doesn't appear to be UK based");
                        errorCode = ResponseCode.FUNDSRECIPIENT_INVALID;
                    }
                }
            }
            return(errorCode.Value);
            //throw new NotImplementedException();
        }
 /// <summary>
 /// Initializes the <see cref="SwaggerAuthorizeAttribute"/> with the given AuthScheme.
 /// </summary>
 /// <param name="scheme"></param>
 public SwaggerAuthorizeAttribute(AuthScheme scheme)
 {
     Scheme = scheme;
 }