@HystrixCommand(fallbackMethod = "defaultComments") public List<Comment> getComments(Image image, String sessionId) { ResponseEntity<List<Comment>> results = restTemplate.exchange( "http://COMMENTS/comments/{imageId}", HttpMethod.GET, new HttpEntity<>(new HttpHeaders() {{ String credentials = imagesConfiguration.getCommentsUser() + ":" + imagesConfiguration.getCommentsPassword(); String token = new String(Base64Utils.encode(credentials.getBytes())); set(AUTHORIZATION, "Basic " + token); set("Cookie", "SESSION=" + sessionId); }}), new ParameterizedTypeReference<List<Comment>>() {}, image.getId()); return results.getBody(); }
@HystrixCommand(fallbackMethod = "defaultComments") public List<Comment> getComments(Image image, String sessionId) { ResponseEntity<List<Comment>> results = restTemplate.exchange( "http://COMMENTS/comments/{imageId}", HttpMethod.GET, new HttpEntity<>(new HttpHeaders() {{ String credentials = imagesConfiguration.getCommentsUser() + ":" + imagesConfiguration.getCommentsPassword(); String token = new String(Base64Utils.encode(credentials.getBytes())); set(AUTHORIZATION, "Basic " + token); set("SESSION", sessionId); }}), new ParameterizedTypeReference<List<Comment>>() {}, image.getId()); return results.getBody(); }
@Test @Transactional public void getAllUserProfiles() throws Exception { // Initialize the database userProfileRepository.saveAndFlush(userProfile); // Get all the userProfiles restUserProfileMockMvc.perform(get("/api/userProfiles")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(userProfile.getId().intValue()))) .andExpect(jsonPath("$.[*].phones").value(hasItem(DEFAULT_PHONES.toString()))) .andExpect(jsonPath("$.[*].address").value(hasItem(DEFAULT_ADDRESS.toString()))) .andExpect(jsonPath("$.[*].pictureContentType").value(hasItem(DEFAULT_PICTURE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].picture").value(hasItem(Base64Utils.encodeToString(DEFAULT_PICTURE)))); }
@Test @Transactional public void getUserProfile() throws Exception { // Initialize the database userProfileRepository.saveAndFlush(userProfile); // Get the userProfile restUserProfileMockMvc.perform(get("/api/userProfiles/{id}", userProfile.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(userProfile.getId().intValue())) .andExpect(jsonPath("$.phones").value(DEFAULT_PHONES.toString())) .andExpect(jsonPath("$.address").value(DEFAULT_ADDRESS.toString())) .andExpect(jsonPath("$.pictureContentType").value(DEFAULT_PICTURE_CONTENT_TYPE)) .andExpect(jsonPath("$.picture").value(Base64Utils.encodeToString(DEFAULT_PICTURE))); }
@Test @Transactional public void getAllImageResources() throws Exception { // Initialize the database imageResourceRepository.saveAndFlush(imageResource); // Get all the imageResources restImageResourceMockMvc.perform(get("/api/imageResources")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(imageResource.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].loResImageContentType").value(hasItem(DEFAULT_LO_RES_IMAGE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].loResImage").value(hasItem(Base64Utils.encodeToString(DEFAULT_LO_RES_IMAGE)))) .andExpect(jsonPath("$.[*].hiResImageContentType").value(hasItem(DEFAULT_HI_RES_IMAGE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].hiResImage").value(hasItem(Base64Utils.encodeToString(DEFAULT_HI_RES_IMAGE)))); }
@Test @Transactional public void getImageResource() throws Exception { // Initialize the database imageResourceRepository.saveAndFlush(imageResource); // Get the imageResource restImageResourceMockMvc.perform(get("/api/imageResources/{id}", imageResource.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(imageResource.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.loResImageContentType").value(DEFAULT_LO_RES_IMAGE_CONTENT_TYPE)) .andExpect(jsonPath("$.loResImage").value(Base64Utils.encodeToString(DEFAULT_LO_RES_IMAGE))) .andExpect(jsonPath("$.hiResImageContentType").value(DEFAULT_HI_RES_IMAGE_CONTENT_TYPE)) .andExpect(jsonPath("$.hiResImage").value(Base64Utils.encodeToString(DEFAULT_HI_RES_IMAGE))); }
public void setSigningKey(String key) throws Exception { this.signingKey = key; key = key.trim(); key = key.replace("-----BEGIN RSA PRIVATE KEY-----\n", "") .replace("-----END RSA PRIVATE KEY-----", "").trim().replace("\n", ""); byte[] encoded = Base64Utils.decodeFromString(key); DerInputStream derInputStream = new DerInputStream(encoded); DerValue[] seq = derInputStream.getSequence(0); BigInteger modulus = seq[1].getBigInteger(); BigInteger publicExp = seq[2].getBigInteger(); BigInteger privateExp = seq[3].getBigInteger(); BigInteger prime1 = seq[4].getBigInteger(); BigInteger prime2 = seq[5].getBigInteger(); BigInteger exp1 = seq[6].getBigInteger(); BigInteger exp2 = seq[7].getBigInteger(); BigInteger crtCoef = seq[8].getBigInteger(); RSAPrivateCrtKeySpec keySpec = new RSAPrivateCrtKeySpec(modulus, publicExp, privateExp, prime1, prime2, exp1, exp2, crtCoef); KeyFactory kf = KeyFactory.getInstance("RSA"); this.signer = new RSASSASigner(kf.generatePrivate(keySpec)); }
public void exceptionHandler(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) throws Throwable { logger.debug("exceptionHandler->" + e + ",handler->" + handler); logger.debug("getAttribute -> " + request.getAttribute(Constants.defaultResponseHeader)); if (Constants.defaultResponseHeader.equals(request.getAttribute(Constants.defaultResponseHeader))) { response.setHeader(Constants.defaultResponseHeader, Constants.defaultResponseHeader); } else { logger.debug(e.getMessage()); String localizedMessage = e.getLocalizedMessage(); String msg = e.getMessage(); String className = e.getClass().getName(); ExcepModel excepModel = new ExcepModel(localizedMessage, msg, className); response.setHeader(Constants.exceptionHeader, Base64Utils.encodeToString(excepModel.toJsonString().getBytes())); } }
@Test @Transactional public void getAllProducts() throws Exception { // Initialize the database productRepository.saveAndFlush(product); // Get all the productList restProductMockMvc.perform(get("/api/products?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(product.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString()))) .andExpect(jsonPath("$.[*].imageContentType").value(hasItem(DEFAULT_IMAGE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].image").value(hasItem(Base64Utils.encodeToString(DEFAULT_IMAGE)))) .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.intValue()))) .andExpect(jsonPath("$.[*].size").value(hasItem(DEFAULT_SIZE.toString()))) .andExpect(jsonPath("$.[*].availableUntil").value(hasItem(DEFAULT_AVAILABLE_UNTIL.toString()))); }
@Test @Transactional public void getProduct() throws Exception { // Initialize the database productRepository.saveAndFlush(product); // Get the product restProductMockMvc.perform(get("/api/products/{id}", product.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.id").value(product.getId().intValue())) .andExpect(jsonPath("$.name").value(DEFAULT_NAME.toString())) .andExpect(jsonPath("$.description").value(DEFAULT_DESCRIPTION.toString())) .andExpect(jsonPath("$.imageContentType").value(DEFAULT_IMAGE_CONTENT_TYPE)) .andExpect(jsonPath("$.image").value(Base64Utils.encodeToString(DEFAULT_IMAGE))) .andExpect(jsonPath("$.price").value(DEFAULT_PRICE.intValue())) .andExpect(jsonPath("$.size").value(DEFAULT_SIZE.toString())) .andExpect(jsonPath("$.availableUntil").value(DEFAULT_AVAILABLE_UNTIL.toString())); }
@Test @Transactional public void searchProduct() throws Exception { // Initialize the database productService.save(product); // Search the product restProductMockMvc.perform(get("/api/_search/products?query=id:" + product.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE)) .andExpect(jsonPath("$.[*].id").value(hasItem(product.getId().intValue()))) .andExpect(jsonPath("$.[*].name").value(hasItem(DEFAULT_NAME.toString()))) .andExpect(jsonPath("$.[*].description").value(hasItem(DEFAULT_DESCRIPTION.toString()))) .andExpect(jsonPath("$.[*].imageContentType").value(hasItem(DEFAULT_IMAGE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].image").value(hasItem(Base64Utils.encodeToString(DEFAULT_IMAGE)))) .andExpect(jsonPath("$.[*].price").value(hasItem(DEFAULT_PRICE.intValue()))) .andExpect(jsonPath("$.[*].size").value(hasItem(DEFAULT_SIZE.toString()))) .andExpect(jsonPath("$.[*].availableUntil").value(hasItem(DEFAULT_AVAILABLE_UNTIL.toString()))); }
@Override @Transactional public JsonResult executeSignUp(String account, String email, String cipher) throws Exception { account = new String(Base64Utils.decodeFromString(account), AppConstants.CHARSET_UTF8); email = new String(Base64Utils.decodeFromString(email), AppConstants.CHARSET_UTF8); cipher = new String(Base64Utils.decodeFromString(cipher), AppConstants.CHARSET_UTF8); SystemUserModel userModel = systemUserRepository.findByAccount(account); if (userModel != null && userModel.getId() != null) { return new JsonResult(400, "此用户账号已被注册!"); } userModel = systemUserRepository.findByEmail(email); if (userModel != null && userModel.getId() != null) { return new JsonResult(400, "此邮箱地址已被注册!"); } userModel = new SystemUserModel(IdWorker.INSTANCE.nextId(), account, cipher, email); systemUserRepository.save(userModel); return new JsonResult(); }
public static HashMap<String, String> getKeys() { try { HashMap<String, String> map = new HashMap<>(); KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(SIGN_ALGORITHM); keyPairGen.initialize(1024); KeyPair keyPair = keyPairGen.generateKeyPair(); RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic(); RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate(); map.put(PUBLIC_KEY, new String(Base64Utils.encode(publicKey.getEncoded()))); map.put(PRIVATE_KEY, new String(Base64Utils.encode(privateKey.getEncoded()))); return map; } catch (Exception e) { e.printStackTrace(); throw new CustomException("生成秘钥对失败"); } }
private List<MessageEntity> findGroupMessageList(List<? extends IMGroupMessageEntity> messageList) { List<MessageEntity> resultList = new ArrayList<>(); for (IMGroupMessageEntity message : messageList) { MessageEntity messageEntity = new MessageEntity(); messageEntity.setId(message.getId()); messageEntity.setMsgId(message.getMsgId()); if (message.getType() == IMBaseDefine.MsgType.MSG_TYPE_GROUP_AUDIO_VALUE) { // 语音Base64 byte[] audioData = audioInternalService.readAudioInfo(Long.valueOf(message.getContent())); messageEntity.setContent(Base64Utils.encodeToString(audioData)); } else { messageEntity.setContent(message.getContent()); } messageEntity.setFromId(message.getUserId()); messageEntity.setCreated(message.getCreated()); messageEntity.setStatus(message.getStatus()); messageEntity.setMsgType(message.getType()); resultList.add(messageEntity); } return resultList; }
private List<MessageEntity> findMessageList(List<? extends IMMessageEntity> messageList) { List<MessageEntity> resultList = new ArrayList<>(); for (IMMessageEntity message : messageList) { MessageEntity messageEntity = new MessageEntity(); messageEntity.setId(message.getId()); messageEntity.setMsgId(message.getMsgId()); if (message.getType() == IMBaseDefine.MsgType.MSG_TYPE_SINGLE_AUDIO_VALUE) { // 语音Base64 byte[] audioData = audioInternalService.readAudioInfo(Long.valueOf(message.getContent())); messageEntity.setContent(Base64Utils.encodeToString(audioData)); } else { messageEntity.setContent(message.getContent()); } messageEntity.setFromId(message.getUserId()); messageEntity.setCreated(message.getCreated()); messageEntity.setStatus(message.getStatus()); messageEntity.setMsgType(message.getType()); resultList.add(messageEntity); } return resultList; }
@PostMapping @ResponseStatus(HttpStatus.OK) public Authorization login(@RequestHeader(HttpHeaders.AUTHORIZATION) final String authorization) { if (authorization.isEmpty()) { log.warn("Authorization header is empty"); throw new EmptyAuthorizationHeaderException(); } if (authorization.startsWith("Basic ")) { final byte[] bytes = Base64Utils.decodeFromString(authorization.substring(6)); final String decoded = new String(bytes); final String[] split = decoded.split(":"); if (split.length == 2) { final String username = split[0]; final String password = split[1]; return authenticationService.login(username, password); } log.warn("Invalid basic authentication: {}", authorization); throw new InvalidBasicAuthenticationException(authorization); } log.warn("Unknown authorization scheme: {}", authorization); throw new UnknownAuthorizationSchemeException(authorization); }
@Test public void testLoginGood() throws Exception { final List<Role> roles = Arrays.asList(Role.USER); final String username = "username"; final String password = "password"; final String s = Base64Utils.encodeToString((username + ":" + password).getBytes()); when(authenticationService.login(eq(username), eq(password))).thenReturn(new AuthorizationInfo("id", "jwt token", roles)); mockMvc.perform(post(PATH).header(HttpHeaders.AUTHORIZATION, "Basic " + s)) .andExpect(status().isOk()) .andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id", is(equalTo("id")))) .andExpect(jsonPath("$.token", is(equalTo("jwt token")))) .andExpect(jsonPath("$.roles", hasSize(1))) .andExpect(jsonPath("$.roles[0]", is(equalTo("USER")))); }
public Base64MultipartFile(String content) { if (StringUtils.isEmpty(content)) { throw new NullPointerException("图片内容不能为空."); } if (!content.startsWith("data:image")) { throw new IllegalArgumentException("非法图片格式."); } else if (content.startsWith("data:image/png;base64,")) { this.data = Base64Utils.decodeFromString(content.substring(22)); this.extName = "png"; } else if (content.startsWith("data:image/gif;base64,")) { this.data = Base64Utils.decodeFromString(content.substring(22)); this.extName = "gif"; } else if (content.startsWith("data:image/jpeg;base64,")) { this.data = Base64Utils.decodeFromString(content.substring(23)); this.extName = "jpg"; } else { throw new IllegalArgumentException("未知图片类型[" + StringUtils.substring(content, 0, 30) + "]."); } }
public static byte[] decodeFromString(String str) { if (StringUtils.isEmpty(str)) { return null; } if (!str.startsWith("data:image")) { return null; } if (str.startsWith("data:image/png;base64,")) { return Base64Utils.decodeFromString(str.substring(22)); } else if (str.startsWith("data:image/jpeg;base64,")) { return Base64Utils.decodeFromString(str.substring(23)); } else { throw new IllegalArgumentException("未知图片类型."); } }
/** * Create the request body to perform a Vault login using the AWS-IAM authentication * method. * * @param options must not be {@literal null}. * @return the map containing body key-value pairs. */ protected static Map<String, String> createRequestBody( AwsIamAuthenticationOptions options) { Map<String, String> login = new HashMap<>(); login.put("iam_http_request_method", "POST"); login.put("iam_request_url", Base64Utils.encodeToString(options.getEndpointUri() .toString().getBytes())); login.put("iam_request_body", REQUEST_BODY_BASE64_ENCODED); String headerJson = getSignedHeaders(options); login.put("iam_request_headers", Base64Utils.encodeToString(headerJson.getBytes())); if (!StringUtils.isEmpty(options.getRole())) { login.put("role", options.getRole()); } return login; }
@Override public String encrypt(String keyName, byte[] plaintext, VaultTransitContext transitContext) { Assert.hasText(keyName, "KeyName must not be empty"); Assert.notNull(plaintext, "Plaintext must not be null"); Assert.notNull(transitContext, "VaultTransitContext must not be null"); Map<String, String> request = new LinkedHashMap<>(); request.put("plaintext", Base64Utils.encodeToString(plaintext)); applyTransitOptions(transitContext, request); return (String) vaultOperations .write(String.format("%s/encrypt/%s", path, keyName), request) .getRequiredData().get("ciphertext"); }
@Override public byte[] decrypt(String keyName, String ciphertext, VaultTransitContext transitContext) { Assert.hasText(keyName, "KeyName must not be empty"); Assert.hasText(ciphertext, "Cipher text must not be empty"); Assert.notNull(transitContext, "VaultTransitContext must not be null"); Map<String, String> request = new LinkedHashMap<>(); request.put("ciphertext", ciphertext); applyTransitOptions(transitContext, request); String plaintext = (String) vaultOperations .write(String.format("%s/decrypt/%s", path, keyName), request) .getRequiredData().get("plaintext"); return Base64Utils.decodeFromString(plaintext); }
@Override public Hmac getHmac(String keyName, VaultHmacRequest hmacRequest) { Assert.hasText(keyName, "KeyName must not be empty"); Assert.notNull(hmacRequest, "HMAC request must not be null"); Map<String, Object> request = new LinkedHashMap<>(); request.put("input", Base64Utils.encodeToString(hmacRequest.getPlaintext().getPlaintext())); if (StringUtils.hasText(hmacRequest.getAlgorithm())) { request.put("algorithm", hmacRequest.getAlgorithm()); } if (hmacRequest.getKeyVersion() != null) { request.put("key_version ", hmacRequest.getKeyVersion()); } String hmac = (String) vaultOperations .write(String.format("%s/hmac/%s", path, keyName), request) .getRequiredData().get("hmac"); return Hmac.of(hmac); }
@Override public Signature sign(String keyName, VaultSignRequest signRequest) { Assert.hasText(keyName, "KeyName must not be empty"); Assert.notNull(signRequest, "Sign request must not be null"); Map<String, Object> request = new LinkedHashMap<>(); request.put("input", Base64Utils.encodeToString(signRequest.getPlaintext().getPlaintext())); if (StringUtils.hasText(signRequest.getAlgorithm())) { request.put("algorithm", signRequest.getAlgorithm()); } String signature = (String) vaultOperations .write(String.format("%s/sign/%s", path, keyName), request) .getRequiredData().get("signature"); return Signature.of(signature); }
public static String getAccessToken(MockMvc mockMvc, String username, String password) throws Exception { String authorizationHeaderValue = "Basic " + new String(Base64Utils.encode("trusted-sw360-client:sw360-secret".getBytes())); MockHttpServletResponse response = mockMvc .perform(post("/oauth/token") .header("Authorization", authorizationHeaderValue) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("client_id", "trusted-sw360-client") .param("client_secret", "sw360-secret") .param("username", username) .param("password", password) .param("grant_type", "password") .param("scope", "sw360.read")) .andReturn().getResponse(); return new ObjectMapper() .readValue(response.getContentAsByteArray(), OAuthToken.class) .accessToken; }
@Test public void getAllDocumentRTS() throws Exception { // Initialize the database documentRTS.setAuthor(DEFAULT_AUTHOR); documentRTSRepository.save(documentRTS); // Get all the documentRTS restDocumentRTSMockMvc.perform(get("/api/document-rts?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(documentRTS.getId()))) .andExpect(jsonPath("$.[*].title").value(hasItem(DEFAULT_TITLE.toString()))) .andExpect(jsonPath("$.[*].author.userName").value(hasItem(DEFAULT_AUTHOR_NAME))) .andExpect(jsonPath("$.[*].content.[*].id").value(hasItem(DEFAULT_CONTENT_ID))) .andExpect(jsonPath("$.[*].content.[*].content").value(hasItem(DEFAULT_CONTENT_CONTENT))) .andExpect(jsonPath("$.[*].type").value(hasItem(DEFAULT_TYPE.toString()))) .andExpect(jsonPath("$.[*].thumpContentType").value(hasItem(DEFAULT_THUMP_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].thump").value(hasItem(Base64Utils.encodeToString(DEFAULT_THUMP)))) .andExpect(jsonPath("$.[*].publicationDate").value(hasItem(DEFAULT_PUBLICATION_DATE.toString()))) .andExpect(jsonPath("$.[*].isPublic").value(hasItem(DEFAULT_IS_PUBLIC.booleanValue()))) .andExpect(jsonPath("$.[*].clicks").value(hasItem(DEFAULT_CLICKS))); }
@Test public void getDocumentRTS() throws Exception { // Initialize the database documentRTS.setAuthor(DEFAULT_AUTHOR); documentRTSRepository.save(documentRTS); // Get the documentRTS restDocumentRTSMockMvc.perform(get("/api/document-rts/{id}", documentRTS.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(documentRTS.getId())) .andExpect(jsonPath("$.title").value(DEFAULT_TITLE.toString())) .andExpect(jsonPath("$.author.userName").value(DEFAULT_AUTHOR_NAME)) .andExpect(jsonPath("$.content.[*].id").value(DEFAULT_CONTENT_ID)) .andExpect(jsonPath("$.content.[*].content").value(DEFAULT_CONTENT_CONTENT)) .andExpect(jsonPath("$.type").value(DEFAULT_TYPE.toString())) .andExpect(jsonPath("$.thumpContentType").value(DEFAULT_THUMP_CONTENT_TYPE)) .andExpect(jsonPath("$.thump").value(Base64Utils.encodeToString(DEFAULT_THUMP))) .andExpect(jsonPath("$.publicationDate").value(DEFAULT_PUBLICATION_DATE.toString())) .andExpect(jsonPath("$.isPublic").value(DEFAULT_IS_PUBLIC.booleanValue())) .andExpect(jsonPath("$.clicks").value(DEFAULT_CLICKS)); }
@Test public void getAllAuthors() throws Exception { // Initialize the database authorRepository.save(author); // Get all the authors restAuthorMockMvc.perform(get("/api/authors?sort=id,desc")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.[*].id").value(hasItem(author.getId()))) .andExpect(jsonPath("$.[*].firstName").value(hasItem(DEFAULT_FIRST_NAME.toString()))) .andExpect(jsonPath("$.[*].lastName").value(hasItem(DEFAULT_LAST_NAME.toString()))) .andExpect(jsonPath("$.[*].userName").value(hasItem(DEFAULT_USERNAME.toString()))) .andExpect(jsonPath("$.[*].imageContentType").value(hasItem(DEFAULT_IMAGE_CONTENT_TYPE))) .andExpect(jsonPath("$.[*].image").value(hasItem(Base64Utils.encodeToString(DEFAULT_IMAGE)))); }
@Test public void getAuthor() throws Exception { // Initialize the database authorRepository.save(author); // Get the author restAuthorMockMvc.perform(get("/api/authors/{id}", author.getId())) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.id").value(author.getId())) .andExpect(jsonPath("$.firstName").value(DEFAULT_FIRST_NAME.toString())) .andExpect(jsonPath("$.lastName").value(DEFAULT_LAST_NAME.toString())) .andExpect(jsonPath("$.userName").value(DEFAULT_USERNAME.toString())) .andExpect(jsonPath("$.imageContentType").value(DEFAULT_IMAGE_CONTENT_TYPE)) .andExpect(jsonPath("$.image").value(Base64Utils.encodeToString(DEFAULT_IMAGE))); }
@Test public void testLoginHandlerSuccess() throws InvalidKeyException, NoSuchAlgorithmException, SignatureException { register.unregister("sample"); List<LSPayload> payloads = new LinkedList<>(); DefaultLSSession.createSession("sample"); WebSocket socket = new MockWebSocket(); LoginHandler handler = new LoginHandler(userDB, register); byte[] macKey = TestUtils.generateMACKey(); LSRequest req = new LSRequest("sample", new HashMap<>(), new Date(), LSRequest.LS_LOGIN, Base64Utils.encodeToString(macKey), socket); req.getAttributes().put("signature", AuthenticationUtils.INSTANCE.signMessage(req.getData(), req.getTimeStamp(), testKey.getPrivate())); LSResponse resp = handler.handleRequest(req, payloads); Assert.assertEquals(LSResponse.SUCCESS, resp.getStatus()); Assert.assertNotEquals(null, register.getSocket("sample")); Assert.assertArrayEquals(macKey, DefaultLSSession.getSession("sample").getAttribute("macKey", byte[].class)); Assert.assertEquals(0, payloads.size()); }
private String getAccessToken(String username, String password) throws Exception { String authorization = "Basic " + new String(Base64Utils.encode("clientapp:123456".getBytes())); String contentType = MediaType.APPLICATION_JSON + ";charset=UTF-8"; String content = mvc .perform(post("/oauth/token") .header("Authorization", authorization) .contentType(MediaType.APPLICATION_FORM_URLENCODED) .param("username", username) .param("password", password) .param("grant_type", "password") .param("scope", "read write") .param("client_id", "clientapp") .param("client_secret", "123456")) .andExpect(status().isOk()) .andExpect(content().contentType(contentType)) .andExpect(jsonPath("$.access_token", is(notNullValue()))) .andExpect(jsonPath("$.token_type", is(equalTo("bearer")))) .andExpect(jsonPath("$.refresh_token", is(notNullValue()))) .andExpect(jsonPath("$.expires_in", is(greaterThan(4000)))) .andExpect(jsonPath("$.scope", is(equalTo("read write")))) .andReturn().getResponse().getContentAsString(); return content.substring(17, 53); }
@Test public void shouldReturnAuthenticatedUser() { // given final UserProvider userProvider = new TogglzConfiguration().userProvider(); HttpServletRequest mockRequest = mock(HttpServletRequest.class); when(mockRequest.getHeader("Authorization")).thenReturn("Basic " + Base64Utils.encodeToString("testuser:passwd".getBytes())); HttpServletRequestHolder.bind(mockRequest); // when FeatureUser currentUser = userProvider.getCurrentUser(); // then assertThat(currentUser.getName(), is("testuser")); }
@Override public CredentialsDto provideCredentials(String applicationId, CredentialsDto credentials) throws CredentialsServiceException { Validate.notBlank(applicationId, "Invalid application ID provided!"); Validate.notNull(credentials, "Invalid credentials provided!"); try { byte[] credentialsBody = credentials.getCredentialsBody(); credentials.setId(Base64Utils.encodeToString(Sha1HashUtils.hashToBytes(credentialsBody))); return this.credentialsDao.save(applicationId, credentials).toDto(); } catch (Exception cause) { String message = MessageFormat.format("[{0}] An unexpected exception occured while saving " + "credentials!", applicationId); LOG.error(message, cause); throw new CredentialsServiceException(cause); } }
@Override public CredentialsDto provisionCredentials(String applicationId, String credentialsBody) throws ControlServiceException { CredentialsDto credentials = new CredentialsDto( Base64Utils.decodeFromString(credentialsBody), CredentialsStatus.AVAILABLE); try { return this.credentialsServiceLocator .getCredentialsService(applicationId) .provideCredentials(credentials); } catch (CredentialsServiceException cause) { String message = MessageFormat .format("An unexpected exception occured while saving credentials [{0}]", credentials); LOG.error(message, cause); throw new ControlServiceException(cause); } }
@Override public SignatureVerifier getSignatureVerifier() throws Exception { String publicKeyEndpointUri = getTokenEndpoint().replace("/token", "/certs"); HttpEntity<Void> request = new HttpEntity<Void>(new HttpHeaders()); LinkedHashMap<String, List<Map<String, Object>>> result = restTemplate.getForObject(publicKeyEndpointUri, LinkedHashMap.class); Map<String, Object> properties = result.get("keys").get(0); BigInteger modulus = new BigInteger(1, Base64Utils.decodeFromUrlSafeString((String) properties.get("n"))); BigInteger publicExponent = new BigInteger(1, Base64Utils.decodeFromString((String) properties.get("e"))); try { PublicKey publicKey = KeyFactory.getInstance("RSA").generatePublic(new RSAPublicKeySpec(modulus, publicExponent)); RSAPublicKey rsaKey = (RSAPublicKey) RSAKeyFactory.toRSAKey(publicKey); return new RsaVerifier(rsaKey); } catch (GeneralSecurityException ex) { log.error("could not create key verifier", ex); throw ex; } }
private String sha256(byte[] data) { try { MessageDigest md = MessageDigest.getInstance("SHA-256"); md.update(data); return Base64Utils.encodeToString(md.digest()); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } }