Example #1
0
        public void Configuration(IAppBuilder app)
        {
            var config      = new KatanaConfiguration();
            var application = new ApiApplication(config);

            app.UseWebApi(config);
        }
        public static IApplicationBuilder UseAutoMapper(this IApplicationBuilder app)
        {
            var mapperConfiguration = new MapperConfiguration(cfg =>
            {
                AssemblyHelper.GetAssemblies().ToList().ForEach(assembly =>
                {
                    AssemblyHelper
                    .GetAllTypes(assembly)
                    .Where(
                        type => type != null &&
                        type.IsClass &&
                        !type.IsAbstract &&
                        !type.IsGenericType &&
                        typeof(Profile).IsAssignableFrom(type)
                        ).ToList().ForEach(type =>
                    {
                        cfg.AddProfile(type);
                    });
                });
            });

            ApiApplication.GetService <MapperAccessor>().Mapper = mapperConfiguration.CreateMapper();

            return(app);
        }
Example #3
0
 public static string GetPersonNameByApiKey(string apiKey)
 {
     if (!String.IsNullOrEmpty(apiKey))
     {
         Guid           apiKeyGuid = new Guid(apiKey);
         ApiApplication aa         = new ApiApplication(apiKeyGuid);
         return(aa.Name + "(Anonymous)");
     }
     else
     {
         return("Api key was not specified.");
     }
 }
 public void Start()
 {
     try
     {
         var httpConfig = new HttpConfiguration();
         var apiConfig  = new ApiApplication(httpConfig);
         apiConfig.Configure();
         _server = new HttpServer(httpConfig);
     }
     catch (Exception e)
     {
         Console.WriteLine("Could not create server: {0}", e);
         Assert.Fail("Could not create server: {0}", e);
     }
 }
Example #5
0
        public static string GetPersonNameBySessionId(string sessionId)
        {
            if (!String.IsNullOrEmpty(sessionId))
            {
                Guid       sessionIdGuid = new Guid(sessionId);
                ApiSession apiSession    = new ApiSession(sessionIdGuid);

                ApiApplication aa = new ApiApplication(apiSession.ApplicationID);

                Person person = new Person(apiSession.LoginID);
                return(aa.Name + "(" + person.FirstName + " " + person.LastName + ", " + person.PersonID + ")");
            }
            else
            {
                return("Session was not specified.");
            }
        }
Example #6
0
        public Arena.Services.Contracts.Person getMe(Stream input, string fields)
        {
            string body = new StreamReader(input).ReadToEnd();
            NameValueCollection postVars = HttpUtility.ParseQueryString(body);

            // Verify we have a valid API key
            if (!postVars.AllKeys.Contains("api_key"))
            {
                throw new BadRequestException("Parameter api_key is required.");
            }

            // Check the API Key
            ApiApplication apiApplication = new ApiApplication(new Guid(postVars["api_key"]));

            if (apiApplication.ApplicationId == -1)
            {
                throw new ApplicationException("Invalid api_key");
            }
            try
            {
                // Make sure we have a username/password and authenticate
                if (postVars.AllKeys.Contains("username") && (postVars.AllKeys.Contains("password")))
                {
                    Int32 personId = Arena.Portal.PortalLogin.Authenticate(postVars["username"], postVars["password"], postVars["api_key"], 1);
                    if (personId > 0)
                    {
                        ArenaContext.Current.SetWebServiceProperties(ArenaContext.Current.CreatePrincipal(postVars["username"]), new Arena.Core.Person(personId));
                        return(GetPerson(Arena.Core.ArenaContext.Current.Person.PersonID, fields));
                    }
                    else
                    {
                        throw new AuthenticationException("Unknown authentication error");
                    }
                }
                else
                {
                    throw new BadRequestException("Username and Password are required.");
                }
            }
            catch (Exception e)
            {
                throw new AuthenticationException(e.Message);
            }
        }
Example #7
0
        public Contracts.ApiSession login(Stream input)
        {
            Core.ApiSession coreApiSession = null;
            Contracts.ApiSession contractApiSession = new Contracts.ApiSession();
            string body = new StreamReader(input).ReadToEnd();
            NameValueCollection postVars = HttpUtility.ParseQueryString(body);

            // Determine which kind of login attempt we have
            if (!postVars.AllKeys.Contains("api_key"))
            {
                throw new BadRequestException("Parameter api_key is required.");
            }
            try
            {

                // If username is passed
                if (postVars.AllKeys.Contains("username"))
                {
                    if (!postVars.AllKeys.Contains("password"))
                    {
                        throw new BadRequestException("Parameter password is required for username authentication.");
                    }

                    // Do a normal Arena API login
                    var api = new Arena.Services.ArenaAPI();
                    input.Seek(0, SeekOrigin.Begin);
                    coreApiSession = api.Login(input);

                    // Test scenario for authenticating with device id
                    /*coreApiSession.DateExpires = DateTime.Now.AddMinutes(1);
                    coreApiSession.Save(postVars["username"]);*/

                    // If we have a device id, register this device and issue a key for it
                    if (postVars.AllKeys.Contains("device_id"))
                    {
                        // First check to see if this device id is already associated with your account
                        Device device = new Device(postVars["device_id"]);
                        if (device.AuthDeviceId > 0)
                        {
                            // Make sure this device is owned by the current person
                            if (device.PersonId != coreApiSession.CurrentPerson.PersonID)
                            {
                                // Delete the old one and create a new one
                                device.Delete();
                                device = new Device();
                                device.PersonId = coreApiSession.CurrentPerson.PersonID;
                            }
                            // Generate a new guid
                            device.DeviceKey = Guid.NewGuid();
                        }
                        else
                        {
                            device.PersonId = coreApiSession.CurrentPerson.PersonID;
                        }
                        device.DeviceId = postVars["device_id"];
                        device.DeviceName = postVars["device_name"];
                        device.LoginId = postVars["username"];
                        device.LastLogin = DateTime.Now;
                        device.Save(postVars["username"]);
                        device.Active = true;
                        contractApiSession.DeviceKey = device.DeviceKey;
                    }
                }

                // Do device authentication
                if (postVars.AllKeys.Contains("device_key"))
                {
                    // First validate the API key
                    ApiApplication apiApp = new ApiApplication(new Guid(postVars["api_key"]));
                    if (apiApp.ApplicationId <= 0)
                    {
                        throw new AuthenticationException("Invalid api_key for device key authentication.");
                    }

                    // Now validatate the device key
                    Device device = new Device(new Guid(postVars["device_key"]));
                    if (device.Active==false || device.AuthDeviceId <= 0 || device.DeviceId != postVars["device_id"])
                    {
                        throw new AuthenticationException("Invalid device id/key pair.");
                    }

                    // Setup the API Session and save it
                    coreApiSession = new Arena.Core.ApiSession();
                    coreApiSession.SetupSession(device.Person, apiApp.ApiSecret, device.LoginId, apiApp);

                    // Test scenario for authenticating with device id
                    /*coreApiSession.DateExpires = DateTime.Now.AddMinutes(1);
                    coreApiSession.Save(device.LoginId);*/

                    // Update the Last Login time for the device
                    device.LastLogin = DateTime.Now;
                    // Generate a new guid
                    device.DeviceKey = Guid.NewGuid();
                    device.Save(device.LoginId);

                    // Update the API Session that we are returning
                    contractApiSession.DeviceKey = device.DeviceKey;
                    contractApiSession.SessionID = coreApiSession.SessionID;
                    contractApiSession.DateExpires = coreApiSession.DateExpires;
                }

            } catch (Exception e)
            {
                throw new AuthenticationException(e.Message);
            }

            Arena.Core.ApiSession.SetSession(coreApiSession);

            // Copy the values for mapping back to the custom contract
            contractApiSession.SessionID = coreApiSession.SessionID;
            contractApiSession.DateExpires = coreApiSession.DateExpires;
            return contractApiSession;
        }
Example #8
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var option = ApiApplication.GetService <IOptions <RedisCacheOptions> >();

            services.AddRedisCache(option.Value);
        }
Example #9
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var option = ApiApplication.GetService <IOptions <DbProviderOptions> >();

            services.AddWangSql(option.Value);
        }
Example #10
0
        public Contracts.ApiSession login(Stream input)
        {
            Core.ApiSession      coreApiSession     = null;
            Contracts.ApiSession contractApiSession = new Contracts.ApiSession();
            string body = new StreamReader(input).ReadToEnd();
            NameValueCollection postVars = HttpUtility.ParseQueryString(body);

            // Determine which kind of login attempt we have
            if (!postVars.AllKeys.Contains("api_key"))
            {
                throw new BadRequestException("Parameter api_key is required.");
            }
            try
            {
                // If username is passed
                if (postVars.AllKeys.Contains("username"))
                {
                    if (!postVars.AllKeys.Contains("password"))
                    {
                        throw new BadRequestException("Parameter password is required for username authentication.");
                    }

                    // Do a normal Arena API login
                    var api = new Arena.Services.ArenaAPI();
                    input.Seek(0, SeekOrigin.Begin);
                    coreApiSession = api.Login(input);

                    // Test scenario for authenticating with device id

                    /*coreApiSession.DateExpires = DateTime.Now.AddMinutes(1);
                     * coreApiSession.Save(postVars["username"]);*/

                    // If we have a device id, register this device and issue a key for it
                    if (postVars.AllKeys.Contains("device_id"))
                    {
                        // First check to see if this device id is already associated with your account
                        Device device = new Device(postVars["device_id"]);
                        if (device.AuthDeviceId > 0)
                        {
                            // Make sure this device is owned by the current person
                            if (device.PersonId != coreApiSession.CurrentPerson.PersonID)
                            {
                                // Delete the old one and create a new one
                                device.Delete();
                                device          = new Device();
                                device.PersonId = coreApiSession.CurrentPerson.PersonID;
                            }
                            // Generate a new guid
                            device.DeviceKey = Guid.NewGuid();
                        }
                        else
                        {
                            device.PersonId = coreApiSession.CurrentPerson.PersonID;
                        }
                        device.DeviceId   = postVars["device_id"];
                        device.DeviceName = postVars["device_name"];
                        device.LoginId    = postVars["username"];
                        device.LastLogin  = DateTime.Now;
                        device.Save(postVars["username"]);
                        device.Active = true;
                        contractApiSession.DeviceKey = device.DeviceKey;
                    }
                }

                // Do device authentication
                if (postVars.AllKeys.Contains("device_key"))
                {
                    // First validate the API key
                    ApiApplication apiApp = new ApiApplication(new Guid(postVars["api_key"]));
                    if (apiApp.ApplicationId <= 0)
                    {
                        throw new AuthenticationException("Invalid api_key for device key authentication.");
                    }

                    // Now validatate the device key
                    Device device = new Device(new Guid(postVars["device_key"]));
                    if (device.Active == false || device.AuthDeviceId <= 0 || device.DeviceId != postVars["device_id"])
                    {
                        throw new AuthenticationException("Invalid device id/key pair.");
                    }

                    // Setup the API Session and save it
                    coreApiSession = new Arena.Core.ApiSession();
                    coreApiSession.SetupSession(device.Person, apiApp.ApiSecret, device.LoginId, apiApp);

                    // Test scenario for authenticating with device id

                    /*coreApiSession.DateExpires = DateTime.Now.AddMinutes(1);
                     * coreApiSession.Save(device.LoginId);*/

                    // Update the Last Login time for the device
                    device.LastLogin = DateTime.Now;
                    // Generate a new guid
                    device.DeviceKey = Guid.NewGuid();
                    device.Save(device.LoginId);

                    // Update the API Session that we are returning
                    contractApiSession.DeviceKey   = device.DeviceKey;
                    contractApiSession.SessionID   = coreApiSession.SessionID;
                    contractApiSession.DateExpires = coreApiSession.DateExpires;
                }
            } catch (Exception e)
            {
                throw new AuthenticationException(e.Message);
            }

            Arena.Core.ApiSession.SetSession(coreApiSession);

            // Copy the values for mapping back to the custom contract
            contractApiSession.SessionID   = coreApiSession.SessionID;
            contractApiSession.DateExpires = coreApiSession.DateExpires;
            return(contractApiSession);
        }
        protected async Task <Application> RegisterServiceApplicationAsync(
            string serviceApplicationName,
            DirectoryObject owner,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new List <string>();

                Log.Information("Creating service application registration ...");

                // Setup AppRoles for service application
                var serviceApplicationAppRoles = new List <AppRole>();

                var serviceApplicationApproverRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Approver",
                    Value              = "Sign",
                    Description        = "Approvers have the ability to issue certificates.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationApproverRoleId
                });

                var serviceApplicationWriterRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Writer",
                    Value              = "Write",
                    Description        = "Writers Have the ability to change entities.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationWriterRoleId
                });

                var serviceApplicationAdministratorRoleId = Guid.NewGuid();
                serviceApplicationAppRoles.Add(new AppRole {
                    DisplayName        = "Administrator",
                    Value              = "Admin",
                    Description        = "Admins can access advanced features.",
                    AllowedMemberTypes = new List <string> {
                        "User", "Application"
                    },
                    Id = serviceApplicationAdministratorRoleId
                });

                // Setup RequiredResourceAccess for service application

                var keyVaultUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.AzureKeyVault.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.AzureKeyVault.ResourceAccess["user_impersonation"],
                            Type = "Scope"
                        }
                    }
                };

                var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                    ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                    ResourceAccess = new List <ResourceAccess> {
                        new ResourceAccess {
                            Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                            Type = "Scope"
                        }
                    }
                };

                var serviceApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
                {
                    keyVaultUserImpersonationRequiredResourceAccess,
                    microsoftGraphUserReadRequiredResourceAccess
                };

                // Add OAuth2Permissions
                var oauth2Permissions = new List <PermissionScope> {
                    new PermissionScope {
                        AdminConsentDescription = $"Allow the app to access {serviceApplicationName} on behalf of the signed-in user.",
                        AdminConsentDisplayName = $"Access {serviceApplicationName}",
                        Id        = Guid.NewGuid(),
                        IsEnabled = true,
                        Type      = "User",
                        UserConsentDescription = $"Allow the application to access {serviceApplicationName} on your behalf.",
                        UserConsentDisplayName = $"Access {serviceApplicationName}",
                        Value = "user_impersonation"
                    }
                };

                var serviceApplicationApiApplication = new ApiApplication {
                    Oauth2PermissionScopes = oauth2Permissions
                };

                // ODataType = null is a workaround for a bug:
                // https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/issues/87
                var serviceApplicationWebApplication = new WebApplication {
                    ImplicitGrantSettings = new ImplicitGrantSettings {
                        ODataType             = null,
                        EnableIdTokenIssuance = true
                    }
                };

                var serviceApplicationDefinition = new Application {
                    DisplayName            = serviceApplicationName,
                    IsFallbackPublicClient = false,
                    IdentifierUris         = new List <string> {
                        $"https://{_tenantId.ToString()}/{serviceApplicationName}"
                    },
                    Tags                   = tags,
                    SignInAudience         = "AzureADMyOrg",
                    AppRoles               = serviceApplicationAppRoles,
                    RequiredResourceAccess = serviceApplicationRequiredResourceAccess,
                    Api = serviceApplicationApiApplication,
                    Web = serviceApplicationWebApplication,
                    PasswordCredentials = new List <PasswordCredential> {
                    }
                };

                var serviceApplication = await _msGraphServiceClient
                                         .CreateApplicationAsync(
                    serviceApplicationDefinition,
                    cancellationToken
                    );

                // Add Service Key PasswordCredential
                var serviceKeyName = "Service Key";
                await _msGraphServiceClient
                .AddApplication2YPasswordCredentialAsync(
                    serviceApplication,
                    serviceKeyName,
                    cancellationToken
                    );

                // We need to create ServicePrincipal for this application.
                var serviceApplicationSP = await _msGraphServiceClient
                                           .CreateApplicationServicePrincipalAsync(
                    serviceApplication,
                    tags,
                    cancellationToken
                    );

                // Add app role assignment to owner as Approver, Writer and Administrator.
                string PrincipalType;

                if (owner is User)
                {
                    PrincipalType = "User";
                }
                else if (owner is ServicePrincipal)
                {
                    PrincipalType = "ServicePrincipal";
                }
                else if (owner is Group)
                {
                    PrincipalType = "Group";
                }
                else
                {
                    throw new ArgumentException($"Owner is of unknown type: {owner.GetType()}", "owner");
                }

                var approverAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Approver",
                    Id        = serviceApplicationApproverRoleId.ToString(),
                    AppRoleId = serviceApplicationApproverRoleId
                };

                var writerAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Writer",
                    Id        = serviceApplicationWriterRoleId.ToString(),
                    AppRoleId = serviceApplicationWriterRoleId
                };

                var administratorAppRoleAssignmentDefinition = new AppRoleAssignment {
                    PrincipalType       = PrincipalType,
                    PrincipalId         = new Guid(owner.Id),
                    ResourceId          = new Guid(serviceApplicationSP.Id),
                    ResourceDisplayName = "Administrator",
                    Id        = serviceApplicationAdministratorRoleId.ToString(),
                    AppRoleId = serviceApplicationAdministratorRoleId
                };

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    approverAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    writerAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                await _msGraphServiceClient
                .AddServicePrincipalAppRoleAssignmentAsync(
                    serviceApplicationSP,
                    administratorAppRoleAssignmentDefinition,
                    cancellationToken
                    );

                // Get updated definition
                serviceApplication = await _msGraphServiceClient
                                     .GetApplicationAsync(
                    new Guid(serviceApplication.Id),
                    cancellationToken
                    );

                Log.Information("Created service application registration.");

                return(serviceApplication);
            }
            catch (Exception) {
                Log.Error("Failed to create service application registration.");
                throw;
            }
        }
Example #12
0
        public async Task <Application> RegisterServiceApplicationAsync(
            string servicesApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            tags = tags ?? new List <string>();

            // Setup AppRoles for service application
            var serviceApplicationAppRoles = new List <AppRole>();

            var serviceApplicationApproverRoleIdGuid = Guid.NewGuid();

            serviceApplicationAppRoles.Add(new AppRole {
                DisplayName        = "Approver",
                Value              = "Sign",
                Description        = "Approvers have the ability to issue certificates.",
                AllowedMemberTypes = new List <string> {
                    "User"
                },
                Id = serviceApplicationApproverRoleIdGuid
            });

            var serviceApplicationWriterRoleIdGuid = Guid.NewGuid();

            serviceApplicationAppRoles.Add(new AppRole {
                DisplayName        = "Writer",
                Value              = "Write",
                Description        = "Writers Have the ability to change entities.",
                AllowedMemberTypes = new List <string> {
                    "User"
                },
                Id = serviceApplicationWriterRoleIdGuid
            });

            var serviceApplicationAdministratorRoleIdGuid = Guid.NewGuid();

            serviceApplicationAppRoles.Add(new AppRole {
                DisplayName        = "Administrator",
                Value              = "Admin",
                Description        = "Admins can access advanced features.",
                AllowedMemberTypes = new List <string> {
                    "User"
                },
                Id = serviceApplicationAdministratorRoleIdGuid
            });

            // Setup RequiredResourceAccess for service application

            //// This flow is not supported yet.
            //var keyVaultUserImpersonationRequiredResourceAccess =
            //    await GetRequiredResourceAccessByDisplayNameAsync(
            //        "Azure Key Vault",
            //        new List<string> { "user_impersonation" },
            //        cancellationToken
            //    );

            var keyVaultUserImpersonationRequiredResourceAccess = new RequiredResourceAccess {
                ResourceAppId  = AzureAppsConstants.AzureKeyVault.AppId,
                ResourceAccess = new List <ResourceAccess> {
                    new ResourceAccess {
                        Id   = AzureAppsConstants.AzureKeyVault.ResourceAccess["user_impersonation"],
                        Type = "Scope"
                    }
                }
            };

            //// This flow is not supported yet.
            //var microsoftGraphUserReadRequiredResourceAccess =
            //    await GetRequiredResourceAccessByDisplayNameAsync(
            //        "Microsoft Graph",
            //        new List<string> { "User.Read" },
            //        cancellationToken
            //    );

            var microsoftGraphUserReadRequiredResourceAccess = new RequiredResourceAccess {
                ResourceAppId  = AzureAppsConstants.MicrosoftGraph.AppId,
                ResourceAccess = new List <ResourceAccess> {
                    new ResourceAccess {
                        Id   = AzureAppsConstants.MicrosoftGraph.ResourceAccess["User.Read"],
                        Type = "Scope"
                    }
                }
            };

            var serviceApplicationRequiredResourceAccess = new List <RequiredResourceAccess>()
            {
                keyVaultUserImpersonationRequiredResourceAccess,
                microsoftGraphUserReadRequiredResourceAccess
            };

            // Add OAuth2Permissions
            var oauth2Permissions = new List <PermissionScope> {
                new PermissionScope {
                    AdminConsentDescription = $"Allow the app to access {servicesApplicationName} on behalf of the signed-in user.",
                    AdminConsentDisplayName = $"Access {servicesApplicationName}",
                    Id        = Guid.NewGuid(),
                    IsEnabled = true,
                    Type      = "User",
                    UserConsentDescription = $"Allow the application to access {servicesApplicationName} on your behalf.",
                    UserConsentDisplayName = $"Access {servicesApplicationName}",
                    Value = "user_impersonation"
                }
            };

            var serviceApplicationApiApplication = new ApiApplication {
                Oauth2PermissionScopes = oauth2Permissions
            };

            var serviceApplicationWebApplication = new WebApplication {
                ImplicitGrantSettings = new ImplicitGrantSettings {
                    EnableIdTokenIssuance = true
                }
            };

            var serviceApplicationIdentifierUri = $"https://{_tenantGuid.ToString()}/{servicesApplicationName}";

            var serviceApplicationRequest = new Application {
                DisplayName            = servicesApplicationName,
                IsFallbackPublicClient = false,
                IdentifierUris         = new List <string> {
                    serviceApplicationIdentifierUri
                },
                Tags                   = tags,
                SignInAudience         = "AzureADMyOrg",
                AppRoles               = serviceApplicationAppRoles,
                RequiredResourceAccess = serviceApplicationRequiredResourceAccess,
                Api = serviceApplicationApiApplication,
                Web = serviceApplicationWebApplication,
                PasswordCredentials = new List <PasswordCredential> {
                }
            };

            var serviceApplication = await _graphServiceClient
                                     .Applications
                                     .Request()
                                     .AddAsync(serviceApplicationRequest, cancellationToken);

            // Add Service Key PasswordCredential
            var serviceKeyName = "Service Key";

            var serviceApplicationServiceKeyPasswordCredentialDefinition = new PasswordCredential {
                StartDateTime       = DateTimeOffset.UtcNow,
                EndDateTime         = DateTimeOffset.UtcNow.AddYears(2),
                CustomKeyIdentifier = ToBase64Bytes(serviceKeyName),
                DisplayName         = serviceKeyName
            };

            await _graphServiceClient
            .Applications[serviceApplication.Id]
            .AddPassword(serviceApplicationServiceKeyPasswordCredentialDefinition)
            .Request()
            .PostAsync(cancellationToken);

            // We need to create ServicePrincipal for this application.
            var serviceApplicationSP = await CreateServicePrincipalAsync(
                serviceApplication,
                tags,
                cancellationToken
                );

            var me = Me(cancellationToken);

            var approverAppRoleAssignmentRequest = new AppRoleAssignment {
                //PrincipalDisplayName = "",
                PrincipalType       = "User",
                PrincipalId         = new Guid(me.Id),
                ResourceId          = new Guid(serviceApplicationSP.Id),
                ResourceDisplayName = "Approver",
                Id        = serviceApplicationApproverRoleIdGuid.ToString(),
                AppRoleId = serviceApplicationApproverRoleIdGuid
            };

            var writerAppRoleAssignmentRequest = new AppRoleAssignment {
                //PrincipalDisplayName = "",
                PrincipalType       = "User",
                PrincipalId         = new Guid(me.Id),
                ResourceId          = new Guid(serviceApplicationSP.Id),
                ResourceDisplayName = "Writer",
                Id        = serviceApplicationWriterRoleIdGuid.ToString(),
                AppRoleId = serviceApplicationWriterRoleIdGuid
            };

            var adminAppRoleAssignmentRequest = new AppRoleAssignment {
                //PrincipalDisplayName = "",
                PrincipalType       = "User",
                PrincipalId         = new Guid(me.Id),
                ResourceId          = new Guid(serviceApplicationSP.Id),
                ResourceDisplayName = "Admin",
                Id        = serviceApplicationAdministratorRoleIdGuid.ToString(),
                AppRoleId = serviceApplicationAdministratorRoleIdGuid
            };

            //// ToDo: Use AddAsync() instead of the workaround bellow
            //// when AddAsync() is added.
            //var appRoleAssignment = _graphServiceClient
            //    .ServicePrincipals[serviceApplicationSP.Id]
            //    .AppRoleAssignments
            //    .Request()
            //    .AddAsync(appRoleAssignmentRequest);

            // Workaround using HttpClient
            await AddAppRoleAssignmentAsync(serviceApplicationSP, approverAppRoleAssignmentRequest);
            await AddAppRoleAssignmentAsync(serviceApplicationSP, writerAppRoleAssignmentRequest);
            await AddAppRoleAssignmentAsync(serviceApplicationSP, adminAppRoleAssignmentRequest);

            return(serviceApplication);
        }
Example #13
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var option = ApiApplication.GetService <IOptions <DynamicApiControllerSettingsOptions> >();

            services.AddDynamicApiControllers(option.Value);
        }
Example #14
0
        public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var options = ApiApplication.GetService <IOptions <SwaggerSettingsOptions> >();

            app.UseSwagger(options.Value);
        }
Example #15
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var options = ApiApplication.GetService <IOptions <SwaggerSettingsOptions> >();

            services.AddSwagger(options.Value);
        }
Example #16
0
        public async Task <Tuple <Application, string> > RegisterAKSApplicationAsync(
            string aksApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            tags = tags ?? new List <string>();

            // Add OAuth2Permissions for user impersonation
            var aksOauth2Permissions = new List <PermissionScope> {
                new PermissionScope {
                    AdminConsentDescription = $"Allow the app to access {aksApplicationName} on behalf of the signed-in user.",
                    AdminConsentDisplayName = $"Access {aksApplicationName}",
                    Id        = Guid.NewGuid(),
                    IsEnabled = true,
                    Type      = "User",
                    UserConsentDescription = $"Allow the application to access {aksApplicationName} on your behalf.",
                    UserConsentDisplayName = $"Access {aksApplicationName}",
                    Value = "user_impersonation"
                }
            };

            var aksApplicationApiApplication = new ApiApplication {
                Oauth2PermissionScopes = aksOauth2Permissions
            };

            var aksApplicationWebApplication = new WebApplication {
                ImplicitGrantSettings = new ImplicitGrantSettings {
                    EnableIdTokenIssuance = true
                }
            };

            var aksApplicationIdentifierUri = $"https://{_tenantGuid.ToString()}/{aksApplicationName}";

            var aksApplicationDefinition = new Application {
                DisplayName            = aksApplicationName,
                IsFallbackPublicClient = false,
                IdentifierUris         = new List <string> {
                    aksApplicationIdentifierUri
                },
                Tags                   = tags,
                SignInAudience         = "AzureADMyOrg",
                AppRoles               = new List <AppRole>(),
                RequiredResourceAccess = new List <RequiredResourceAccess>(),
                Api = aksApplicationApiApplication,
                Web = aksApplicationWebApplication,
                PasswordCredentials = new List <PasswordCredential> {
                }
            };

            var aksApplication = await _graphServiceClient
                                 .Applications
                                 .Request()
                                 .AddAsync(aksApplicationDefinition, cancellationToken);

            // Add RBAC Key PasswordCredential
            var rbacKeyName = "rbac";

            var aksApplicationRBACPasswordCredentialDefinition = new PasswordCredential {
                StartDateTime       = DateTimeOffset.UtcNow,
                EndDateTime         = DateTimeOffset.UtcNow.AddYears(2),
                CustomKeyIdentifier = ToBase64Bytes(rbacKeyName),
                DisplayName         = rbacKeyName
            };

            var aksApplicationRBACPasswordCredential = await _graphServiceClient
                                                       .Applications[aksApplication.Id]
                                                       .AddPassword(aksApplicationRBACPasswordCredentialDefinition)
                                                       .Request()
                                                       .PostAsync(cancellationToken);

            if (string.IsNullOrEmpty(aksApplicationRBACPasswordCredential.SecretText))
            {
                throw new Exception($"Failed to retrieve password credentials for AKS Application: {rbacKeyName}");
            }

            var aksApplicationRBACPasswordCredentialSecret = aksApplicationRBACPasswordCredential.SecretText;

            // We need to create ServicePrincipal for this application.
            await CreateServicePrincipalAsync(
                aksApplication,
                tags,
                cancellationToken
                );

            var result = new Tuple <Application, string>(
                aksApplication,
                aksApplicationRBACPasswordCredentialSecret
                );

            return(result);
        }
Example #17
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var option = ApiApplication.GetService <IOptions <CorsAccessorOptions> >();

            services.AddCorsAccessor(option.Value);
        }
Example #18
0
        public override void ConfigureServices(IServiceCollection services)
        {
            var option = ApiApplication.GetService <IOptions <JwtSettingsOptions> >().Value;

            services.AddAuthentication(option);
        }
Example #19
0
        public override void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            var option = ApiApplication.GetService <IOptions <CorsAccessorOptions> >();

            app.UseCorsAccessor(option.Value.Name);
        }
        public async Task <Tuple <Application, string> > RegisterAKSApplicationAsync(
            string aksApplicationName,
            IEnumerable <string> tags           = null,
            CancellationToken cancellationToken = default
            )
        {
            try {
                tags ??= new List <string>();

                Log.Information("Creating AKS application registration ...");

                // Add OAuth2Permissions for user impersonation
                var aksOauth2Permissions = new List <PermissionScope> {
                    new PermissionScope {
                        AdminConsentDescription = $"Allow the app to access {aksApplicationName} on behalf of the signed-in user.",
                        AdminConsentDisplayName = $"Access {aksApplicationName}",
                        Id        = Guid.NewGuid(),
                        IsEnabled = true,
                        Type      = "User",
                        UserConsentDescription = $"Allow the application to access {aksApplicationName} on your behalf.",
                        UserConsentDisplayName = $"Access {aksApplicationName}",
                        Value = "user_impersonation"
                    }
                };

                var aksApplicationApiApplication = new ApiApplication {
                    Oauth2PermissionScopes = aksOauth2Permissions
                };

                // ODataType = null is a workaround for a bug:
                // https://github.com/microsoftgraph/msgraph-beta-sdk-dotnet/issues/87
                var aksApplicationWebApplication = new WebApplication {
                    ImplicitGrantSettings = new ImplicitGrantSettings {
                        ODataType             = null,
                        EnableIdTokenIssuance = true
                    }
                };

                var aksApplicationDefinition = new Application {
                    DisplayName            = aksApplicationName,
                    IsFallbackPublicClient = false,
                    IdentifierUris         = new List <string> {
                        $"https://{_tenantId.ToString()}/{aksApplicationName}"
                    },
                    Tags                   = tags,
                    SignInAudience         = "AzureADMyOrg",
                    AppRoles               = new List <AppRole>(),
                    RequiredResourceAccess = new List <RequiredResourceAccess>(),
                    Api = aksApplicationApiApplication,
                    Web = aksApplicationWebApplication,
                    PasswordCredentials = new List <PasswordCredential> {
                    }
                };

                var aksApplication = await _msGraphServiceClient
                                     .CreateApplicationAsync(
                    aksApplicationDefinition,
                    cancellationToken
                    );

                // Add RBAC Key PasswordCredential
                var rbacKeyName = "rbac";
                var aksApplicationRBACPasswordCredential = await _msGraphServiceClient
                                                           .AddApplication2YPasswordCredentialAsync(
                    aksApplication,
                    rbacKeyName,
                    cancellationToken
                    );

                if (string.IsNullOrEmpty(aksApplicationRBACPasswordCredential.SecretText))
                {
                    throw new Exception($"Failed to get password credentials for AKS Application: {rbacKeyName}");
                }

                var aksApplicationRBACPasswordCredentialSecret = aksApplicationRBACPasswordCredential.SecretText;

                // We need to create ServicePrincipal for this application.
                await _msGraphServiceClient
                .CreateApplicationServicePrincipalAsync(
                    aksApplication,
                    tags,
                    cancellationToken
                    );

                // Get updated definition
                aksApplication = await _msGraphServiceClient
                                 .GetApplicationAsync(
                    new Guid(aksApplication.Id),
                    cancellationToken
                    );

                var result = new Tuple <Application, string>(
                    aksApplication,
                    aksApplicationRBACPasswordCredentialSecret
                    );

                Log.Information("Created AKS application registration.");

                return(result);
            }
            catch (Exception) {
                Log.Error("Failed to create AKS application registration.");
                throw;
            }
        }
Example #21
0
 public CacheTestService(IDistributedCache <BookCacheItem> cache, IJwtTokenHandler jwtTokenHandler)
 {
     _cache           = cache;
     _jwtTokenHandler = jwtTokenHandler;
     _objectMapper    = ApiApplication.GetService <IObjectMapper>();
 }