public BaseAuthenticateHub()
 {
     _topicService         = (ITopicService)UnityConfig.GetConfiguredContainer().GetService(typeof(ITopicService));
     _logger               = (ILogger)UnityConfig.GetConfiguredContainer().GetService(typeof(ILogger));
     _parameterEnvService  = (IParameterEnvService)UnityConfig.GetConfiguredContainer().GetService(typeof(IParameterEnvService));
     _messageConfiguration = (IMessageConfiguration)UnityConfig.GetConfiguredContainer().GetService(typeof(IMessageConfiguration));
     _messageMappings      = _messageConfiguration.GetConfigurations();
     _unitOfWork           = (IDataUnitOfWork)UnityConfig.GetConfiguredContainer().GetService(typeof(IDataUnitOfWork));
 }
示例#2
0
        public TopicService(IServiceBusConfiguration configuration, ILogger logger,
                            IServiceBusMessageMapper mapper_to_brokered, IBrokeredMessageMapper mapper_to_message,
                            IServiceBusTopicContext topicContext, IMessageConfiguration messageConfiguration)
        {
            if (configuration == null || string.IsNullOrEmpty(configuration.ConnectionString))
            {
                throw new DSWException(SERVICE_BASE_CONNECTIONSTRING_IS_EMPTY, null, DSWExceptionCode.SS_Mapper);
            }

            _instanceId           = Guid.NewGuid();
            _configuration        = configuration;
            _messageConfiguration = messageConfiguration.GetConfigurations();
            _logger             = logger;
            _mapper_to_brokered = mapper_to_brokered;
            _mapper_to_message  = mapper_to_message;
            _topicContext       = topicContext;
        }
        public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });
            string appId, kind, username, @params, authRule, year, number, uniqueId, token, user;

            appId = kind = username = @params = authRule = year = number = uniqueId = token = user = string.Empty;
            try
            {
                _logger.WriteDebug(new LogMessage("GrantResourceOwnerCredentials"), LogCategories);
                IFormCollection forms = await context.OwinContext.Request.ReadFormAsync();

                appId = forms.Single(f => f.Key == "appId").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("AppID-> ", appId)), LogCategories);

                kind = forms.Single(f => f.Key == "kind").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("Kind-> ", kind)), LogCategories);

                username = forms.Single(f => f.Key == "username").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("Username-> ", username)), LogCategories);

                authRule = forms.Single(f => f.Key == "authRule").Value.Single();
                _logger.WriteDebug(new LogMessage(string.Concat("AuthRule-> ", authRule)), LogCategories);

                @params = forms.Single(f => f.Key == "params").Value.SingleOrDefault();
                _logger.WriteDebug(new LogMessage(string.Concat("Params-> ", @params)), LogCategories);

                if (kind == "Protocol")
                {
                    string[] keys = @params.Split('|');
                    year     = keys.Single(f => f.StartsWith("year=")).Split('=').Last();
                    number   = keys.Single(f => f.StartsWith("number=")).Split('=').Last();
                    uniqueId = _unitOfWork.Repository <Protocol>().GetByCompositeKey(short.Parse(year), int.Parse(number)).Single().UniqueId.ToString();
                }
                if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token)
                {
                    string[] keys = @params.Split('|');
                    token = keys.Single(f => f.StartsWith("token=")).Split('=').Last();
                    user  = keys.Single(f => f.StartsWith("user="******"The AppId '{appId}' is not valid."), LogCategories);
                context.SetError("invalid_grant", $"The AppId {appId} is not valid.");
                context.Rejected();
                return;
            }
            if (string.IsNullOrEmpty(kind))
            {
                _logger.WriteWarning(new LogMessage($"The Kind '{kind}' is not valid."), LogCategories);
                context.SetError("invalid_grant", "The Kind is not valid.");
                context.Rejected();
                return;
            }
            if (string.IsNullOrEmpty(username) || !ValidIntegrations.Any(f => f.Key == username))
            {
                _logger.WriteWarning(new LogMessage($"The Username '{username}' is not valid."), LogCategories);
                context.SetError("invalid_grant", $"The Username {username} is not valid.");
                context.Rejected();
                return;
            }

            if (string.IsNullOrEmpty(authRule))
            {
                _logger.WriteWarning(new LogMessage($"The AuthRule '{authRule}' is not valid."), LogCategories);
                context.SetError("invalid_grant", "The AuthRule is not valid.");
                context.Rejected();
                return;
            }
            currentIntegration = ValidIntegrations[username];
            if (currentIntegration.Key != authenticationId || currentIntegration.Value != authRule)
            {
                _logger.WriteWarning(new LogMessage($"{username}: The configuration is not valid."), LogCategories);
                context.SetError("invalid_grant", "The configuration is not valid.");
                context.Rejected();
                return;
            }

            if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_OAuth2 &&
                (string.IsNullOrEmpty(year) || string.IsNullOrEmpty(number)))
            {
                _logger.WriteWarning(new LogMessage($"The protocols oauth2 params {year}/{number} is not valid."), LogCategories);
                context.SetError("invalid_grant", "The protocols oauth2 params is not valid.");
                context.Rejected();
                return;
            }
            if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token &&
                (string.IsNullOrEmpty(user) || string.IsNullOrEmpty(token) || string.IsNullOrEmpty(year) || string.IsNullOrEmpty(number)))
            {
                _logger.WriteWarning(new LogMessage($"The protocols token params {user}/{token}/{year}/{number} is not valid."), LogCategories);
                context.SetError("invalid_grant", "The protocols token params is not valid.");
                context.Rejected();
                return;
            }
            if (kind == "Protocol" && authRule == VALUE_ExternalViewer_AuthenticationRule_Token)
            {
                string topicName = _messageConfiguration.GetConfigurations()["EventTokenSecurity"].TopicName;
                if (!await _topicService.SubscriptionExists(topicName, token))
                {
                    _logger.WriteWarning(new LogMessage($"AppId {appId} has no valid token {authenticationId}"), LogCategories);
                    context.SetError($"AppId {appId} has not validate token {authenticationId}", "The protocols params is not valid.");
                    context.Rejected();
                    return;
                }
                ServiceBusMessage   serviceBusMessage  = (await _topicService.GetMessagesAsync(topicName, token)).FirstOrDefault();
                IEventTokenSecurity tokenSecurityModel = null;
                if (serviceBusMessage == null || (tokenSecurityModel = (IEventTokenSecurity)serviceBusMessage.Content) == null)
                {
                    _logger.WriteWarning(new LogMessage($"AppId {appId} has no valid token"), LogCategories);
                    context.SetError($"AppId {appId} has not validate token {token}", "The protocols params is not valid.");
                    context.Rejected();
                    return;
                }
                if (tokenSecurityModel.ContentType.ContentTypeValue.DocumentUnitAuhtorized.UniqueId.ToString() != uniqueId)
                {
                    _logger.WriteWarning(new LogMessage($"AppId {appId} token is not valid for protocol {uniqueId}-{year}/{number}"), LogCategories);
                    context.SetError($"AppId {appId} token is not valid for protocol {uniqueId}-{year}/{number}", "The protocols params is not valid.");
                    context.Rejected();
                    return;
                }
                Guid secureToken = tokenSecurityModel.ContentType.ContentTypeValue.Token;
                _logger.WriteDebug(new LogMessage($"SecureToken is {secureToken}"), LogCategories);
            }
            ClaimsIdentity identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Kind, kind, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
            identity.AddClaim(new Claim(CLAIM_ExternalViewer_AuthenticationRule, authRule, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));

            if (kind == "Protocol")
            {
                identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Year, year, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_Number, number, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                identity.AddClaim(new Claim(CLAIM_ExternalViewer_OAuth2_UniqueId, uniqueId, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));

                if (authRule == VALUE_ExternalViewer_AuthenticationRule_Token)
                {
                    identity.AddClaim(new Claim(CLAIM_ExternalViewer_Token_Hash, token, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                    identity.AddClaim(new Claim(CLAIM_ExternalViewer_Token_User, user, ClaimValueTypes.String, ClaimsIdentity.DefaultIssuer, string.Empty));
                }
            }
            context.Validated(identity);
        }
示例#4
0
 public CQRSMessageMapper(IMessageConfiguration messageConfiguration)
 {
     _configurations = messageConfiguration.GetConfigurations();
 }
        public async Task <IHttpActionResult> Post(Guid authenticationId, string documentUnit, short year, int number)
        {
            return(await ActionHelper.TryCatchWithLoggerGeneric(async() =>
            {
                _logger.WriteInfo(new LogMessage($"Token securities receive a request for authenticationId {authenticationId}, documentUnit {documentUnit}, year {year} and number {number}"), LogCategories);
                if (!DSWAuthorizationServerProvider.ValidAuthenticationList.Any(f => f == authenticationId))
                {
                    _logger.WriteWarning(new LogMessage($"AuthenticationId {authenticationId} is not valid"), LogCategories);
                    throw new DSWSecurityException($"AuthenticationId {authenticationId} is not valid", null, DSWExceptionCode.SC_InvalidAccount);
                }
                DocumentUnit reference = null;
                switch (documentUnit)
                {
                case "Protocol":
                    {
                        reference = _unitOfWork.Repository <DocumentUnit>().GetByNumbering(year, number, (int)DSWEnvironmentType.Protocol, optimization: true);
                        break;
                    }

                default:
                    {
                        _logger.WriteWarning(new LogMessage($"AuthenticationId {authenticationId} has no valid documentUnit '{documentUnit}' name"), LogCategories);
                        throw new DSWSecurityException($"AuthenticationId {authenticationId} is not valid", null, DSWExceptionCode.SC_InvalidAccount);
                    }
                }
                if (reference == null)
                {
                    _logger.WriteWarning(new LogMessage($"DocumentUnit {documentUnit} - {year}/{number} not found"), LogCategories);
                    throw new DSWSecurityException($"DocumentUnit {documentUnit} - {year}/{number} not found", null, DSWExceptionCode.SC_InvalidAccount);
                }
                Guid currentToken = Guid.NewGuid();
                DateTimeOffset creationDate = DateTimeOffset.UtcNow;
                DateTimeOffset expiryDate = creationDate.AddMilliseconds(30 * 1000);
                HostIdentify hostIdentify = new HostIdentify(Environment.MachineName, "Public WebAPI");
                TokenSecurityModel tokenModel = new TokenSecurityModel()
                {
                    AuthenticationId = authenticationId,
                    ExpiryDate = expiryDate,
                    Token = currentToken,
                    Host = hostIdentify,
                    DocumentUnitAuhtorized = new DocSuiteWeb.Model.Entities.DocumentUnits.DocumentUnitModel()
                    {
                        Environment = reference.Environment,
                        UniqueId = reference.UniqueId,
                        Year = reference.Year,
                        Number = reference.Number.ToString(),
                        Title = reference.Title
                    }
                };
                string username = "******";
                if (WindowsIdentity.GetCurrent() != null)
                {
                    username = WindowsIdentity.GetCurrent().Name;
                }
                IdentityContext identityContext = new IdentityContext(username);
                EventTokenSecurity eventTokenSecurity = new EventTokenSecurity(Guid.NewGuid(), currentToken, _parameterEnvService.CurrentTenantName, _parameterEnvService.CurrentTenantId,
                                                                               Guid.Empty, identityContext, tokenModel, null);
                _logger.WriteDebug(new LogMessage($"Generated token {currentToken} by {username} expiry on {expiryDate}"), LogCategories);
                string topicName = _messageConfiguration.GetConfigurations()[eventTokenSecurity.EventName].TopicName;
                string dynamicSubscriptionName = currentToken.ToString();
                await _topicService.CreateSubscriptionAsync(topicName, dynamicSubscriptionName, currentToken.ToString(), eventTokenSecurity.EventName);

                ServiceBusMessage message = _cqrsMapper.Map(eventTokenSecurity, new ServiceBusMessage());
                ServiceBusMessage response = await _topicService.SendToTopicAsync(message);
                return Ok(currentToken);
            }, _logger, LogCategories));
        }