示例#1
0
        /// <summary>
        /// 禁用角色
        /// </summary>
        /// <param name="rolerequest"></param>
        /// <returns></returns>
        public BasicResponse DisableRole(RolesRequest rolerequest)
        {
            BasicResponse   Result     = new BasicResponse();
            List <RoleInfo> lstRoleDTO = rolerequest.RoleInfo;

            try
            {
                if (lstRoleDTO.Count <= 0)
                {
                    Result.Code    = 1;
                    Result.Message = "传入参数异常";
                    return(Result);
                }
                foreach (RoleInfo tempRoleDTO in lstRoleDTO)
                {
                    tempRoleDTO.RoleFlag = 0;
                    var _request = ObjectConverter.Copy <RoleInfo, RoleModel>(tempRoleDTO);
                    _Repository.Update(_request);
                }
            }
            catch
            {
                Result.Code    = 2;
                Result.Message = "操作失败";
            }
            return(Result);
        }
        /// <summary>
        /// 添加/修改角色
        /// </summary>
        /// <param name="rolesRequest"></param>
        /// <returns></returns>
        public async Task <ResponseMessage> AddRoles(RolesRequest rolesRequest)
        {
            var response = new ResponseMessage();

            if (rolesRequest == null)
            {
                throw new Exception(nameof(rolesRequest));
            }
            try
            {
                var newRoles = _Mapper.Map <Roles>(rolesRequest);
                if (await _IRolesStore.isExistence(newRoles.Id))
                {
                    newRoles.OrganizationId = newRoles.OrganizationId;
                    newRoles.Name           = newRoles.Name;
                    await _IRolesStore.UpdateRoles(newRoles);

                    return(response);
                }
                newRoles.Id             = Guid.NewGuid().ToString();
                newRoles.OrganizationId = newRoles.OrganizationId;
                newRoles.Name           = newRoles.Name;
                await _IRolesStore.InsertRoles(newRoles);
            }
            catch (Exception el)
            {
                throw new Exception(el.Message);
            }
            return(response);
        }
示例#3
0
        public async Task SecretPki_SetUpRootCA_CanIssueCertificatesWithAltNames()
        {
            using (var server = new VaultTestServer())
            {
                var client = server.TestClient();

                var mountPoint = Guid.NewGuid().ToString();
                await client.Sys.Mount(mountPoint, new MountInfo { Type = "pki" });

                var mountConfig = new MountConfig
                {
                    MaxLeaseTtl = "87600h"
                };
                await client.Sys.TuneMount(mountPoint, mountConfig);

                var rootCaConfig = new RootGenerateRequest
                {
                    CommonName = "Vault Testing Root Certificate Authority",
                    Ttl        = "87600h"
                };
                await client.Secret.Write($"{mountPoint}/root/generate/internal", rootCaConfig);

                var roleName = Guid.NewGuid().ToString();
                var role     = new RolesRequest
                {
                    AllowAnyDomain   = true,
                    EnforceHostnames = false,
                    MaxTtl           = "1h"
                };
                await client.Secret.Write($"{mountPoint}/roles/{roleName}", role);

                var commonName  = Guid.NewGuid().ToString();
                var certRequest = new IssueRequest
                {
                    CommonName = commonName,
                    AltNames   = new List <string> {
                        "example.com", "test.example.com"
                    },
                    Format = CertificateFormat.Der
                };
                var cert =
                    await
                    client.Secret.Write <IssueRequest, IssueResponse>($"{mountPoint}/issue/{roleName}",
                                                                      certRequest);

                Assert.NotNull(cert.Data);
                Assert.NotNull(cert.Data.Certificate);
                Assert.NotNull(cert.Data.PrivateKey);

                var x509Cert = new X509Certificate2(Encoding.UTF8.GetBytes(cert.Data.Certificate));
                Assert.Equal($"CN={commonName}", x509Cert.SubjectName.Name);
            }
        }
示例#4
0
        public async Task <bool> AssignRolesASync(string id, RolesRequest roles,
                                                  CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await _client.SetAuthHeaderAsync(cancellationToken);

            var content  = new StringContent(JsonSerializer.Serialize(roles), Encoding.UTF8, "application/json");
            var response = await _client.HttpClient.PostAsync($"api/v2/users/{id}/roles", content, cancellationToken);

            await _client.HandleErrorAsync(response, cancellationToken);

            return(response.IsSuccessStatusCode);
        }
示例#5
0
        public async Task <bool> DeleteRolesAsync(string id, RolesRequest roles, CancellationToken cancellationToken = default)
        {
            cancellationToken.ThrowIfCancellationRequested();
            await _client.SetAuthHeaderAsync(cancellationToken);

            var content = new StringContent(JsonSerializer.Serialize(roles), Encoding.UTF8, "application/json");
            var request = new HttpRequestMessage(HttpMethod.Delete, $"api/v2/users/{id}/roles")
            {
                Content = content
            };
            var response = await _client.HttpClient.SendAsync(request, cancellationToken);

            await _client.HandleErrorAsync(response, cancellationToken);

            return(response.IsSuccessStatusCode);
        }
示例#6
0
        public async Task SecretPki_SetUpRootCA_CanIssueCertificates()
        {
            using (var server = new VaultTestServer())
            {
                var client = server.TestClient();

                var mountPoint = Guid.NewGuid().ToString();
                await client.Sys.Mount(mountPoint, new MountInfo { Type = "pki" });

                var mountConfig = new MountConfig
                {
                    MaxLeaseTtl = "87600h"
                };
                await client.Sys.TuneMount(mountPoint, mountConfig);

                var rootCaConfig = new RootGenerateRequest
                {
                    CommonName = "Vault Testing Root Certificate Authority",
                    Ttl        = "87600h"
                };
                await client.Secret.Write($"{mountPoint}/root/generate/internal", rootCaConfig);

                var roleName = Guid.NewGuid().ToString();
                var role     = new RolesRequest
                {
                    AllowAnyDomain   = true,
                    EnforceHostnames = false,
                    MaxTtl           = "1h"
                };
                await client.Secret.Write($"{mountPoint}/roles/{roleName}", role);

                var certRequest = new IssueRequest
                {
                    CommonName = "Test Cert"
                };
                var cert =
                    await
                    client.Secret.Write <IssueRequest, IssueResponse>($"{mountPoint}/issue/{roleName}",
                                                                      certRequest);

                Assert.NotNull(cert.Data);
                Assert.NotNull(cert.Data.Certificate);
                Assert.NotNull(cert.Data.PrivateKey);
            }
        }
        public async Task <ApiResponse <RolesResponse> > AddRoles(RolesRequest req)
        {
            var roleExist = await roleManager.RoleExistsAsync(req.Role);

            if (roleExist)
            {
                return(new ApiResponse <RolesResponse>()
                {
                    Success = false,
                    Errors = new[] { $"{req.Role} already exist." }
                });
            }
            else
            {
                var appRole = new IdentityRole()
                {
                    Id   = Guid.NewGuid().ToString(),
                    Name = req.Role
                };

                var result = await roleManager.CreateAsync(appRole);

                if (result.Succeeded)
                {
                    return(new ApiResponse <RolesResponse>()
                    {
                        Success = true,
                        Data = new RolesResponse()
                        {
                            ID = appRole.Id, Role = appRole.Name
                        }
                    });
                }
                else
                {
                    return(new ApiResponse <RolesResponse>()
                    {
                        Success = false,
                        Errors = result.Errors.Select(e => e.Description)
                    });
                }
            }
        }
        public async Task <ResponseMessage> PulshRole(RolesRequest rolesRequest)
        {
            var users = DataBaseUser.TokenModel;

            _Logger.LogInformation($"用户{users?.UserName ?? ""},其ID:({users?.Id ?? ""}) 添加/修改角色:\r\n" + (rolesRequest != null ? JsonHelpers.ToJSON(rolesRequest) : ""));
            var response = new ResponseMessage();

            try
            {
                response = await _RolesManager.AddRoles(rolesRequest);
            }
            catch (Exception el)
            {
                _Logger.LogError($"用户{users?.UserName ?? ""}({users?.Id ?? ""})添加/修改角色报错:\r\n{el.ToString()}");
                response.Code    = ResponseCodeDefines.ArgumentNullError;
                response.Message = $"添加角色列表报错:{el.Message}";
            }
            return(response);
        }
        public async Task <ActionResult> CreateRole(RolesRequest req)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ApiResponse <string>()
                {
                    Success = false,
                    Errors = ModelState.Values.SelectMany(s => s.Errors.Select(e => e.ErrorMessage))
                }));
            }

            var response = await accountService.AddRoles(req);

            if (!response.Success)
            {
                return(BadRequest(response));
            }
            return(Ok(response));
        }
示例#10
0
        public async Task SecretPki_SetUpRootCA_ReadCaCertificate()
        {
            using (var server = new VaultTestServer())
            {
                var client = server.TestClient();

                var mountPoint = Guid.NewGuid().ToString();
                await client.Sys.Mount(mountPoint, new MountInfo { Type = "pki" });

                var mountConfig = new MountConfig
                {
                    MaxLeaseTtl = "87600h"
                };
                await client.Sys.TuneMount(mountPoint, mountConfig);

                var rootCaConfig = new RootGenerateRequest
                {
                    CommonName = "Vault Testing Root Certificate Authority",
                    Ttl        = "87600h"
                };
                await client.Secret.Write($"{mountPoint}/root/generate/internal", rootCaConfig);

                var roleName = Guid.NewGuid().ToString();
                var role     = new RolesRequest
                {
                    AllowAnyDomain   = true,
                    EnforceHostnames = false,
                    MaxTtl           = "1h"
                };
                await client.Secret.Write($"{mountPoint}/roles/{roleName}", role);

                var caCert = await client.Secret.ReadRaw($"{mountPoint}/ca/pem");

                Assert.StartsWith("-----", System.Text.Encoding.Default.GetString(caCert));
            }
        }
示例#11
0
 public BasicResponse DisableRole(RolesRequest rolerequest)
 {
     return(_roleService.DisableRole(rolerequest));
 }
示例#12
0
        public async Task SecretPki_BuildIntermediateCAChain_CanIssueCertificatesWithChain()
        {
            using (var server = new VaultTestServer())
            {
                var client = server.TestClient();

                await client.Sys.Mount("pki", new MountInfo { Type = "pki" });

                await client.Sys.Mount("pki1", new MountInfo { Type = "pki" });

                await client.Sys.Mount("pki2", new MountInfo { Type = "pki" });

                await client.Sys.Mount("pki3", new MountInfo { Type = "pki" });

                var mountConfig = new MountConfig
                {
                    MaxLeaseTtl = "87600h"
                };
                await client.Sys.TuneMount("pki", mountConfig);

                await client.Sys.TuneMount("pki1", mountConfig);

                await client.Sys.TuneMount("pki2", mountConfig);

                await client.Sys.TuneMount("pki3", mountConfig);

                // Root CA
                var rootCaConfig = new RootGenerateRequest
                {
                    CommonName = "Vault Testing Root Certificate Authority",
                    Ttl        = "87600h"
                };
                await client.Secret.Write($"pki/root/generate/internal", rootCaConfig);

                // Intermediate CA
                var pki1CaConfig = new IntermediateGenerateRequest
                {
                    CommonName = "Vault Testing Intermediate CA"
                };
                var pki1Request =
                    await
                    client.Secret.Write <IntermediateGenerateRequest, IntermediateGenerateInternalResponse>(
                        "pki1/intermediate/generate/internal", pki1CaConfig);

                var pki1SignRequest = new RootSignIntermediateRequest
                {
                    Csr    = pki1Request.Data.Csr,
                    Format = CertificateFormat.PemBundle,
                    Ttl    = "87500h"
                };
                var pki1SignResponse =
                    await
                    client.Secret.Write <RootSignIntermediateRequest, RootSignIntermediateResponse>(
                        "pki/root/sign-intermediate", pki1SignRequest);

                var pki1SetSigned = new IntermediateSetSignedRequest
                {
                    Certificate = pki1SignResponse.Data.Certificate
                };
                await client.Secret.Write("pki1/intermediate/set-signed", pki1SetSigned);


                // PKI2 - Sub Intermediate CA
                var pki2CaConfig = new IntermediateGenerateRequest
                {
                    CommonName = "Vault Testing Sub Intermediate CA"
                };
                var pki2Request =
                    await
                    client.Secret.Write <IntermediateGenerateRequest, IntermediateGenerateInternalResponse>(
                        "pki2/intermediate/generate/internal", pki2CaConfig);

                var pki2SignRequest = new RootSignIntermediateRequest
                {
                    Csr    = pki2Request.Data.Csr,
                    Format = CertificateFormat.PemBundle,
                    Ttl    = "87400h"
                };
                var pki2SignResponse =
                    await
                    client.Secret.Write <RootSignIntermediateRequest, RootSignIntermediateResponse>(
                        "pki1/root/sign-intermediate", pki2SignRequest);

                var pki2SetSigned = new IntermediateSetSignedRequest
                {
                    Certificate = pki2SignResponse.Data.Certificate
                };
                await client.Secret.Write("pki2/intermediate/set-signed", pki2SetSigned);

                var roleName = Guid.NewGuid().ToString();
                var role     = new RolesRequest
                {
                    AllowAnyDomain   = true,
                    EnforceHostnames = false,
                    MaxTtl           = "1h"
                };
                await client.Secret.Write($"pki2/roles/{roleName}", role);

                var commonName  = Guid.NewGuid().ToString();
                var certRequest = new IssueRequest
                {
                    CommonName = commonName,
                    AltNames   = new List <string> {
                        "example.com", "test.example.com"
                    },
                    Format = CertificateFormat.Der
                };
                var cert =
                    await
                    client.Secret.Write <IssueRequest, IssueResponse>($"pki2/issue/{roleName}",
                                                                      certRequest);

                Assert.NotNull(cert.Data);
                Assert.NotNull(cert.Data.Certificate);
                Assert.NotNull(cert.Data.PrivateKey);
                Assert.Equal(2, cert.Data.CaChain.Count);
            }
        }
示例#13
0
        /// <summary>
        /// 启用角色
        /// </summary>
        /// <param name="rolerequest"></param>
        /// <returns></returns>
        public BasicResponse EnableRole(RolesRequest rolerequest)
        {
            var responseStr = HttpClientHelper.Post(Webapi + "/v1/Role/EnableRole?token=" + Token, JSONHelper.ToJSONString(rolerequest));

            return(JSONHelper.ParseJSONString <BasicResponse>(responseStr));
        }