Beispiel #1
0
 internal async Task <TResult> CreateLoginAsync <TResult>(Guid authenticationRequestId, Guid authenticationId,
                                                          CredentialValidationMethodTypes method, Uri callbackLocation, IDictionary <string, string> authParams,
                                                          Func <Session, TResult> onSuccess,
                                                          Func <TResult> onAlreadyExists,
                                                          Func <string, TResult> onFailure)
 {
     return(await EastFive.Web.Configuration.Settings.GetUri(
                EastFive.Security.AppSettings.TokenScope,
                async (scope) =>
     {
         var sessionId = SecureGuid.Generate();
         var claims = await this.context.Claims.FindByAccountIdAsync(authenticationId,
                                                                     (cs) => cs.Select(c => c.Type.PairWithValue(c.Value)).ToDictionary(),
                                                                     () => new Dictionary <string, string>());
         return await Sessions.GenerateToken(sessionId, authenticationId, claims,
                                             (token) => this.dataContext.AuthenticationRequests.CreateAsync(authenticationRequestId,
                                                                                                            method, AuthenticationActions.signin, authenticationId, token, callbackLocation, callbackLocation,
                                                                                                            () =>
         {
             telemetry.TrackEvent("Sessions.CreateLoginAsync - Create Session", authParams);
             var session = new Session()
             {
                 id = authenticationRequestId,
                 method = method,
                 action = AuthenticationActions.signin,
                 token = token,
                 extraParams = authParams
             };
             return onSuccess(session);
         },
                                                                                                            onAlreadyExists),
                                             why => onFailure(why).ToTask());
     },
                onFailure.AsAsyncFunc()));
 }
Beispiel #2
0
 public static async Task <HttpResponseMessage> GetAsync(
     [QueryParameter(Name = StatePropertyName)] string state,
     [QueryParameter(Name = ClientPropertyName)] IRef <Client> clientRef,
     [QueryParameter(Name = ValidationPropertyName)] string validation,
     Api.Azure.AzureApplication application, UrlHelper urlHelper,
     //ContentTypeResponse<Authentication> onFound,
     RedirectResponse onFound,
     ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
 {
     return(await await clientRef.StorageGetAsync(
                (client) =>
     {
         var authentication = new Authentication
         {
             authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
             state = state,
         };
         return authentication.StorageCreateAsync(
             (entity) =>
         {
             var location = urlHelper.GetLocation <Authentication>(
                 auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                 application);
             return onFound(location);
         },
             () => throw new Exception("Secure guid not unique"));
     },
                () => onInvalidClient().AsTask()));
 }
 private static Resources.AuthenticationRequestLink Convert(CredentialValidationMethodTypes method, UrlHelper urlHelper)
 {
     return(new Resources.AuthenticationRequestLink
     {
         Id = urlHelper.GetWebId <Controllers.SessionController>(SecureGuid.Generate()),
         Method = method,
         Name = method.ToString(),
         SecureId = SecureGuid.Generate(),
     });
 }
Beispiel #4
0
        private static async Task <Auth.Session> CreateSession(string userIdentification,
                                                               IAzureApplication application, IHttpRequest request)
        {
            var authentication = new Authentication
            {
                authenticationRef  = Ref <Authentication> .SecureRef(),
                authenticated      = DateTime.UtcNow,
                userIdentification = userIdentification,
                token = SecureGuid.Generate().ToString("N"),
            };

            return(await await authentication
                   .StorageCreateAsync(
                       async (authenticationDiscard) =>
            {
                var method = EastFive.Azure.Auth.Method.ByMethodName(
                    CredentialProvider.IntegrationName, application);

                var parameters = new Dictionary <string, string>()
                {
                    { "state", authentication.authenticationRef.id.ToString() },
                    { "token", authentication.token },
                    { CredentialProvider.referrerKey, "https://example.com/internal" }
                };


                return await await method.RedeemTokenAsync(parameters, application,
                                                           async(externalAccountKey, authorizationRefMaybe, loginProvider, extraParams) =>
                {
                    var authorization = new Auth.Authorization
                    {
                        authorizationRef = new Ref <Auth.Authorization>(Security.SecureGuid.Generate()),
                        Method = method.authenticationId,
                        parameters = extraParams,
                        authorized = true,
                    };

                    return await await Auth.Redirection.AuthorizeWithAccountAsync(
                        authorization,
                        async(authorizationToSave) =>
                    {
                        bool created = await authorizationToSave.StorageCreateAsync(
                            discard => true);
                    },
                        method,
                        externalAccountKey, extraParams,
                        application, request, loginProvider,
                        request.RequestUri,
                        async(accountId, authorizationUpdated) =>
                    {
                        return await CreateSessionAsync(authorization);
                    },
                        (interruptTo, accountId, authorizationUpdated) => throw new Exception($"Cannot redirect to `{interruptTo}`"),
                        (why, authorizationUpdated) => throw new Exception(why),
Beispiel #5
0
        private static Resources.AuthenticationRequestLink Convert(KeyValuePair <string, IProvideLogin> providerPair, UrlHelper urlHelper)
        {
            var method = providerPair.Key;
            var name   = providerPair.Value is IProvideIntegration integrationProvider?integrationProvider.GetDefaultName(null) : method.ToString();

            return(new Resources.AuthenticationRequestLink
            {
                Id = urlHelper.GetWebId <Controllers.SessionController>(SecureGuid.Generate()),
                Method = method,
                Name = name,
                SecureId = SecureGuid.Generate(),
            });
        }
Beispiel #6
0
        public static async Task <IHttpResponse> GetAsync(
            //[WorkflowNewId]
            //[WorkflowVariable(
            //    Workflows.PasswordLoginCreateAccount.Variables.State,
            //    AuthorizationPropertyName)]
            [OptionalQueryParameter(Name = AuthorizationPropertyName)]
            IRefOptional <Authorization> authorizationRefOptional,

            [WorkflowParameter(
                 Value = "d989b604-1e25-4d77-b79e-fe1c7d36f833",
                 Description = "Unique and static to each client (i.e. iOS or Web)")]
            [QueryParameter(Name = ClientPropertyName)]
            IRef <Client> clientRef,

            [WorkflowNewId(Description = "No idea what this does.")]
            [OptionalQueryParameter(Name = ValidationPropertyName)]
            string validation,

            IAuthApplication application, IProvideUrl urlHelper,
            //ContentTypeResponse<Authentication> onFound,

            [WorkflowVariable(
                 Workflows.PasswordLoginCreateAccount.Variables.Authorization,
                 Authentication.AuthenticationPropertyName)]
            [WorkflowVariableRedirectUrl(
                 VariableName = Workflows.PasswordLoginCreateAccount.Variables.AuthorizationRedirect)]
            RedirectResponse onFound,

            ReferencedDocumentNotFoundResponse <Client> onInvalidClient)
        {
            return(await await clientRef.StorageGetAsync(
                       (client) =>
            {
                var authentication = new Authentication
                {
                    authenticationRef = SecureGuid.Generate().AsRef <Authentication>(),
                    authorizationMaybe = authorizationRefOptional,
                    client = clientRef,
                };
                return authentication.StorageCreateAsync(
                    (entity) =>
                {
                    var location = urlHelper.GetLocation <Authentication>(
                        auth => auth.authenticationRef.AssignQueryValue(authentication.authenticationRef),
                        application);
                    return onFound(location);
                });
            },
                       () => onInvalidClient().AsTask()));
        }
        public async Task <TResult> SendEmailInviteAsync <TResult>(Guid inviteId, Guid actorId, string email,
                                                                   Guid performingActorId, System.Security.Claims.Claim[] claims,
                                                                   Func <Guid, Guid, Uri> getRedirectLink,
                                                                   Func <TResult> success,
                                                                   Func <TResult> inviteAlreadyExists,
                                                                   Func <TResult> onCredentialMappingDoesNotExists,
                                                                   Func <TResult> onUnauthorized,
                                                                   Func <TResult> onServiceNotAvailable,
                                                                   Func <string, TResult> onFailed)
        {
            if (!await Library.configurationManager.CanAdministerCredentialAsync(actorId, performingActorId, claims))
            {
                return(onUnauthorized());
            }

            var token   = SecureGuid.Generate();
            var loginId = Guid.NewGuid(); // This creates a "user" in the invite system
            var result  = await await this.dataContext.CredentialMappings.CreateCredentialMappingAsync(inviteId,
                                                                                                       loginId, actorId, email, token, DateTime.UtcNow, false, false,
                                                                                                       async() =>
            {
                var templateName = ConfigurationManager.AppSettings[Configuration.EmailTemplateDefinitions.InviteNewAccount];
                if (string.IsNullOrEmpty(templateName))
                {
                    return(onFailed($"Email template setting not found.  Expected template value for key {Configuration.EmailTemplateDefinitions.InviteNewAccount}"));
                }

                var mailService = Web.Services.ServiceConfiguration.SendMessageService();
                var resultMail  = await mailService.SendEmailMessageAsync(templateName,
                                                                          email, string.Empty,
                                                                          "*****@*****.**", "New Account Services",
                                                                          "New Order Owl Account",
                                                                          new Dictionary <string, string>()
                {
                    { "create_account_link", getRedirectLink(inviteId, token).AbsoluteUri }
                },
                                                                          null,
                                                                          (sentCode) => success(),
                                                                          () => onServiceNotAvailable(),
                                                                          (why) => onFailed(why));
                return(resultMail);
            },
                                                                                                       () => inviteAlreadyExists().ToTask(),
                                                                                                       () => { throw new Exception("Token generated was not unique"); },
                                                                                                       () => { throw new Exception("Login Id generated was not unique"); });

            return(result);
        }
 public static Task <TResult> CreateByMethodAndKeyAsync <TResult>(IRef <Method> methodRef,
                                                                  Guid accountId, IDictionary <string, string> parameters,
                                                                  Func <XIntegration, Authorization, TResult> onCreated,
                                                                  Func <string, TResult> onFailure)
 {
     return(CreateByMethodAndKeyAsync(
                Guid.NewGuid().AsRef <XIntegration>(),
                SecureGuid.Generate().AsRef <Authorization>(),
                methodRef,
                accountId,
                parameters,
                onCreated,
                () => throw new Exception("Guid not unique"),
                () => throw new Exception("Guid not unique"),
                onFailure));
 }
Beispiel #9
0
 public async Task <TResult> CreateLinkAsync <TResult>(Guid integrationId,
                                                       Uri callbackLocation,
                                                       string method, Uri redirectUrl,
                                                       Guid authenticationId, Guid actorId, System.Security.Claims.Claim[] claims,
                                                       Func <Type, Uri> typeToUrl,
                                                       Func <Session, TResult> onSuccess,
                                                       Func <TResult> onAlreadyExists,
                                                       Func <string, TResult> onUnauthorized,
                                                       Func <TResult> onCredentialSystemNotAvailable,
                                                       Func <string, TResult> onCredentialSystemNotInitialized,
                                                       Func <string, TResult> onFailure)
 {
     if (!await Library.configurationManager.CanAdministerCredentialAsync(authenticationId, actorId, claims))
     {
         return(onUnauthorized($"Provided token does not permit access to link {authenticationId} to a login"));
     }
     return(await Context.GetLoginProvider <Task <TResult> >(method,
                                                             async (provider) =>
     {
         var sessionId = SecureGuid.Generate();
         return await BlackBarLabs.Security.Tokens.JwtTools.CreateToken <Task <TResult> >(sessionId, callbackLocation, TimeSpan.FromMinutes(30),
                                                                                          async(token) => await await this.dataContext.AuthenticationRequests.CreateAsync <Task <TResult> >(integrationId,
                                                                                                                                                                                            method, AuthenticationActions.access, authenticationId, token, redirectUrl, redirectUrl,
                                                                                                                                                                                            () => dataContext.Integrations.CreateUnauthenticatedAsync(integrationId, authenticationId, method,
                                                                                                                                                                                                                                                      () => onSuccess(
                                                                                                                                                                                                                                                          new Session()
         {
             id = integrationId,
             //method = method,
             name = method.ToString(),
             action = AuthenticationActions.access,
             loginUrl = provider.GetLoginUrl(integrationId, callbackLocation, typeToUrl),
             logoutUrl = provider.GetLogoutUrl(integrationId, callbackLocation, typeToUrl),
             redirectUrl = redirectUrl,
             authorizationId = authenticationId,
             token = token,
         }),
                                                                                                                                                                                                                                                      onAlreadyExists),
                                                                                                                                                                                            onAlreadyExists.AsAsyncFunc()),
                                                                                          why => onFailure(why).ToTask(),
                                                                                          (param, why) => onFailure($"Invalid configuration for {param}:{why}").ToTask());
     },
                                                             onCredentialSystemNotAvailable.AsAsyncFunc(),
                                                             onCredentialSystemNotInitialized.AsAsyncFunc()));
 }
 public async Task <TResult> CreateLoginAsync <TResult>(Guid authenticationRequestId,
                                                        string method, Uri redirectUrl, Uri redirectLogoutUrl,
                                                        Func <Type, Uri> controllerToLocation,
                                                        Func <Session, TResult> onSuccess,
                                                        Func <TResult> onAlreadyExists,
                                                        Func <TResult> onCredentialSystemNotAvailable,
                                                        Func <string, TResult> onCredentialSystemNotInitialized,
                                                        Func <string, TResult> onFailure)
 {
     return(await Context.GetLoginProvider(method,
                                           async (provider) =>
     {
         var callbackLocation = controllerToLocation(provider.CallbackController);
         var sessionId = SecureGuid.Generate();
         var methodName = method;
         var result = await this.dataContext.AuthenticationRequests.CreateAsync(authenticationRequestId,
                                                                                methodName, AuthenticationActions.signin, redirectUrl, redirectLogoutUrl,
                                                                                () => BlackBarLabs.Security.Tokens.JwtTools.CreateToken(sessionId, callbackLocation, TimeSpan.FromMinutes(30),
                                                                                                                                        (token) =>
         {
             var session = new Session()
             {
                 id = authenticationRequestId,
                 method = methodName,
                 name = methodName,
                 action = AuthenticationActions.signin,
                 loginUrl = provider.GetLoginUrl(authenticationRequestId, callbackLocation, controllerToLocation),
                 logoutUrl = provider.GetLogoutUrl(authenticationRequestId, callbackLocation, controllerToLocation),
                 redirectUrl = redirectUrl,
                 redirectLogoutUrl = redirectLogoutUrl,
                 token = token,
             };
             return onSuccess(session);
         },
                                                                                                                                        why => onFailure(why),
                                                                                                                                        (param, why) => onFailure($"Invalid configuration for {param}:{why}")),
                                                                                onAlreadyExists);
         return result;
     },
                                           onCredentialSystemNotAvailable.AsAsyncFunc(),
                                           onCredentialSystemNotInitialized.AsAsyncFunc()));
 }
Beispiel #11
0
        internal async Task <TResult> CreateSessionAsync <TResult>(Guid sessionId, Guid authenticationId,
                                                                   Func <string, string, TResult> onSuccess,
                                                                   Func <string, TResult> onConfigurationFailure)
        {
            Func <IDictionary <string, string>, TResult> authenticate =
                (claims) =>
            {
                var refreshToken = SecureGuid.Generate().ToString("N");
                var result       = GenerateToken(sessionId, authenticationId,
                                                 claims,
                                                 (jwtToken) => onSuccess(jwtToken, refreshToken),
                                                 (why) => onConfigurationFailure(why));
                return(result);
            };

            return(await this.context.Claims.FindByAccountIdAsync(authenticationId,
                                                                  (claims) => authenticate(claims
                                                                                           .Select(claim => new KeyValuePair <string, string>(claim.Type, claim.Value))
                                                                                           .ToDictionary()),
                                                                  () => authenticate(new Dictionary <string, string>())));
        }
Beispiel #12
0
 public static IRef <TType> SecureRef()
 {
     return(SecureGuid.Generate().AsRef <TType>());
 }