org.springframework.security.crypto.codec.Base64 Java Examples

The following examples show how to use org.springframework.security.crypto.codec.Base64. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: KerberosService.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
public Authentication validateKerberosTicket(HttpServletRequest request) {
    // Only support Kerberos login when running securely
    if (!request.isSecure()) {
        return null;
    }

    String header = request.getHeader(AUTHORIZATION_HEADER_NAME);

    if (isValidKerberosHeader(header)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(header.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8);
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));

        return kerberosServiceAuthenticationProvider.authenticate(authenticationRequest);
    } else {
        return null;
    }
}
 
Example #2
Source File: KerberosService.java    From nifi with Apache License 2.0 6 votes vote down vote up
public Authentication validateKerberosTicket(HttpServletRequest request) {
    // Only support Kerberos login when running securely
    if (!request.isSecure()) {
        return null;
    }

    String header = request.getHeader(AUTHORIZATION_HEADER_NAME);

    if (isValidKerberosHeader(header)) {
        if (logger.isDebugEnabled()) {
            logger.debug("Received Negotiate Header for request " + request.getRequestURL() + ": " + header);
        }
        byte[] base64Token = header.substring(header.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8);
        byte[] kerberosTicket = Base64.decode(base64Token);
        KerberosServiceRequestToken authenticationRequest = new KerberosServiceRequestToken(kerberosTicket);
        authenticationRequest.setDetails(authenticationDetailsSource.buildDetails(request));

        return kerberosServiceAuthenticationProvider.authenticate(authenticationRequest);
    } else {
        return null;
    }
}
 
Example #3
Source File: DefaultUserService.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Override
public void sendPasswordReminder(User newUser) {
    log.debug("Calling send password change link for user {}", newUser);
    User user = userRepository.getByUserEmail(newUser.getEmail());
    if (user == null) {
        throw new IllegalArgumentException("Could not find user for email " + newUser.getEmail());
    }
    // create user hash:
    String input = user.getEmail() + user.getUsername() + String.valueOf(user.getId()) + System.nanoTime();
    // hash needs to be URL friendly:
    String safeString = new String(Base64.encode(passwordEncoder.encode(input).getBytes()));
    String  hashedInput = safeString.replaceAll("[/=]", "A");
    user.setForgotPasswordHash(hashedInput);
    user.setForgotPasswordTime(Calendar.getInstance().getTime());
    userRepository.save(user);
    String to = user.getUsername() + " <" + user.getEmail() + '>';
    Map<String, Object> templateData = new HashMap<String, Object>();
    templateData.put("user", user);
    templateData.put("reminderUrl", baseUrl + hashedInput);
    emailService.sendEmail(to, passwordReminderSubject, passwordReminderTemplate, templateData);
}
 
Example #4
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void unauthorized(String username, String password, String clientId, String secret) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("username", username);
    params.add("password", password);
    String hash = new String(Base64.encode((clientId + ":" + secret).getBytes()));
    ResultActions result
            = mockMvc.perform(post("/oauth/token")
                    .params(params)
                    .header("Authorization", "Basic " + hash)
                    .accept("application/json;charset=UTF-8"))
            .andExpect(status().isUnauthorized());
    String resultString = result.andReturn().getResponse().getContentAsString();
    Assert.assertTrue(StringUtils.isBlank(resultString));
    if (!StringUtils.isEmpty(username)) {
        Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(0, oauthTokens.size());
    }
}
 
Example #5
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void missingGrant(String username, String password, String clientId, String secret, String grantType) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", grantType);
    params.add("username", username);
    params.add("password", password);
    String hash = new String(Base64.encode((clientId + ":" + secret).getBytes()));
    ResultActions result
            = mockMvc.perform(post("/oauth/token")
                    .params(params)
                    .header("Authorization", "Basic " + hash)
                    .accept("application/json;charset=UTF-8"))
            .andExpect(status().isBadRequest())
            .andExpect(content().contentType("application/json;charset=UTF-8"));
    String resultString = result.andReturn().getResponse().getContentAsString();
    Assert.assertTrue(StringUtils.isNotBlank(resultString));
    result.andExpect(jsonPath("$.error", is("invalid_request")));
    result.andExpect(jsonPath("$.error_description", is("Missing grant type")));
    Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
    Assert.assertEquals(0, oauthTokens.size());
}
 
Example #6
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void invalidClient(String username, String password, String clientId, String secret, String grantType) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", grantType);
    params.add("username", username);
    params.add("password", password);
    String hash = new String(Base64.encode((clientId + ":" + secret).getBytes()));
    ResultActions result
            = mockMvc.perform(post("/oauth/token")
                    .params(params)
                    .header("Authorization", "Basic " + hash)
                    .accept("application/json;charset=UTF-8"))
            .andExpect(status().isUnauthorized())
            .andExpect(content().contentType("application/json;charset=UTF-8"));
    String resultString = result.andReturn().getResponse().getContentAsString();
    Assert.assertTrue(StringUtils.isNotBlank(resultString));
    result.andExpect(jsonPath("$.error", is("invalid_client")));
    String expectedMessage = "Unauthorized grant type: " + grantType;
    result.andExpect(jsonPath("$.error_description", is(expectedMessage)));
    Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
    Assert.assertEquals(0, oauthTokens.size());
}
 
Example #7
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void authenticationFailed(String username, String password) throws Exception {
    MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
    params.add("grant_type", "password");
    params.add("username", username);
    params.add("password", password);
    String hash = new String(Base64.encode("test1_consumer:secret".getBytes()));
    ResultActions result
            = mockMvc.perform(post("/oauth/token")
                    .params(params)
                    .header("Authorization", "Basic " + hash)
                    .accept("application/json;charset=UTF-8"))
            .andExpect(status().isUnauthorized())
            .andExpect(content().contentType("application/json;charset=UTF-8"));
    String resultString = result.andReturn().getResponse().getContentAsString();
    Assert.assertTrue(StringUtils.isNotBlank(resultString));
    result.andExpect(jsonPath("$.error", is("unauthorized")));
    result.andExpect(jsonPath("$.error_description", anything()));
    if (!StringUtils.isEmpty(username)) {
        Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(0, oauthTokens.size());
    }
}
 
Example #8
Source File: HttpAuthInterceptor.java    From haven-platform with Apache License 2.0 6 votes vote down vote up
private void interceptInner(HttpHeaders headers, HttpRequest httpRequest) {
    URI uri = httpRequest.getURI();
    String host = uri.getHost();
    int port = uri.getPort();
    String url = host + (port == -1 ? "" : ":" + port);
    String name = registryName.get();
    log.debug("try to auth request to registry: {}", name);
    RegistryService registry = registryRepository.getByName(name);
    if (registry == null) {
        log.debug("auth : none due to unknown registry \"{}\"", name);
        return;
    }
    RegistryCredentials credentials = registry.getCredentials();
    if (credentials == null || !StringUtils.hasText(credentials.getPassword())) {
        log.debug("auth : none due to unknown registry \"{}\"", name);
        return;
    }
    String result = format("'{'\"username\":\"{0}\",\"password\":\"{1}\",\"email\":\"[email protected]\",\"serveraddress\":\"{2}\",\"auth\":\"\"'}'",
            credentials.getUsername(), credentials.getPassword(), url);
    log.debug("auth : {}", result);
    String xRegistryAuth = new String(Base64.encode(result.getBytes()));
    log.debug("X-Registry-Auth : [{}]", xRegistryAuth);
    headers.add("X-Registry-Auth", xRegistryAuth);
}
 
Example #9
Source File: KonkerBasicAuthenticationFilter.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
private String[] extractAndDecodeHeader(String header, HttpServletRequest request)
		throws IOException {

	byte[] base64Token = header.substring(6).getBytes("UTF-8");
	byte[] decoded;
	try {
		decoded = Base64.decode(base64Token);
	}
	catch (IllegalArgumentException e) {
		throw new BadCredentialsException(
				"Failed to decode basic authentication token");
	}

	String token = new String(decoded, getCredentialsCharset(request));

	int delim = token.indexOf(':');

	if (delim == -1) {
		throw new BadCredentialsException("Invalid basic authentication token");
	}
	return new String[] { token.substring(0, delim), token.substring(delim + 1) };
}
 
Example #10
Source File: KerberosSpnegoIdentityProvider.java    From nifi-registry with Apache License 2.0 6 votes vote down vote up
@Override
public AuthenticationRequest extractCredentials(HttpServletRequest request) {

    // Only support Kerberos authentication when running securely
    if (!request.isSecure()) {
        return null;
    }

    String headerValue = request.getHeader(AUTHORIZATION);

    if (!isValidKerberosHeader(headerValue)) {
        return null;
    }

    logger.debug("Detected 'Authorization: Negotiate header in request {}", request.getRequestURL());
    byte[] base64Token = headerValue.substring(headerValue.indexOf(" ") + 1).getBytes(StandardCharsets.UTF_8);
    byte[] kerberosTicket = Base64.decode(base64Token);
    if (kerberosTicket != null) {
        logger.debug("Successfully decoded SPNEGO/Kerberos ticket passed in Authorization: Negotiate <ticket> header.", request.getRequestURL());
    }

    return new AuthenticationRequest(null, kerberosTicket, authenticationDetailsSource.buildDetails(request));

}
 
Example #11
Source File: CustomAuthenticationSuccessHandler.java    From fast-family-master with Apache License 2.0 6 votes vote down vote up
/**
 * 解码
 *
 * @param header
 * @param request
 * @return
 * @throws IOException
 */
private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
    byte[] base64Token = header.substring(6).getBytes("UTF-8");

    byte[] decoded;
    try {
        decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException var7) {
        throw new BadCredentialsException("Failed to decode basic authentication token");
    }

    String token = new String(decoded, "UTF-8");
    int delim = token.indexOf(":");
    if (delim == -1) {
        throw new BadCredentialsException("Invalid basic authentication token");
    } else {
        return new String[]{token.substring(0, delim), token.substring(delim + 1)};
    }
}
 
Example #12
Source File: AuthUtils.java    From pig with MIT License 6 votes vote down vote up
/**
 * 从header 请求中的clientId/clientsecect
 *
 * @param header header中的参数
 * @throws CheckedException if the Basic header is not present or is not valid
 *                          Base64
 */
public static String[] extractAndDecodeHeader(String header)
        throws IOException {

    byte[] base64Token = header.substring(6).getBytes("UTF-8");
    byte[] decoded;
    try {
        decoded = Base64.decode(base64Token);
    } catch (IllegalArgumentException e) {
        throw new CheckedException(
                "Failed to decode basic authentication token");
    }

    String token = new String(decoded, CommonConstant.UTF8);

    int delim = token.indexOf(":");

    if (delim == -1) {
        throw new CheckedException("Invalid basic authentication token");
    }
    return new String[]{token.substring(0, delim), token.substring(delim + 1)};
}
 
Example #13
Source File: AjaxLoginSuccessHandler.java    From fw-cloud-framework with MIT License 6 votes vote down vote up
private String[] extractAndDecodeHeader(String header) throws IOException {

		byte[] base64Token = header.substring(6)
				.getBytes("UTF-8");
		byte[] decoded;
		try {
			decoded = Base64.decode(base64Token);
		} catch (IllegalArgumentException e) {
			throw new BadCredentialsException("Failed to decode basic authentication token");
		}

		String token = new String(decoded, CommonConstant.UTF8);

		int delim = token.indexOf(":");

		if (delim == -1) { throw new BadCredentialsException("Invalid basic authentication token"); }
		return new String[] { token.substring(0, delim), token.substring(delim + 1) };
	}
 
Example #14
Source File: RequestUtil.java    From paascloud-master with Apache License 2.0 6 votes vote down vote up
public static String[] extractAndDecodeHeader(String header) throws IOException {

		byte[] base64Token = header.substring(6).getBytes("UTF-8");
		byte[] decoded;
		try {
			decoded = Base64.decode(base64Token);
		} catch (IllegalArgumentException e) {
			throw new BadCredentialsException("Failed to decode basic authentication token");
		}

		String token = new String(decoded, "UTF-8");

		int delim = token.indexOf(GlobalConstant.Symbol.MH);

		if (delim == -1) {
			throw new BadCredentialsException("Invalid basic authentication token");
		}
		return new String[]{token.substring(0, delim), token.substring(delim + 1)};
	}
 
Example #15
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private OAuth2AccessToken obtainAccessToken(String username, String password, boolean remove) throws Exception {
    OAuth2AccessToken oauthToken = null;
    try {
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "password");
        params.add("username", username);
        params.add("password", password);
        String hash = new String(Base64.encode("test1_consumer:secret".getBytes()));
        ResultActions result
                = mockMvc.perform(post("/oauth/token")
                        .params(params)
                        .header("Authorization", "Basic " + hash)
                        .accept("application/json;charset=UTF-8"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"));
        String resultString = result.andReturn().getResponse().getContentAsString();
        System.out.println(resultString);
        Assert.assertTrue(StringUtils.isNotBlank(resultString));
        String token = JsonPath.parse(resultString).read("$.access_token");
        Assert.assertTrue(StringUtils.isNotBlank(token));
        Collection<OAuth2AccessToken> oauthTokens = apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(1, oauthTokens.size());
        oauthToken = oauthTokens.stream().findFirst().get();
        Assert.assertEquals(token, oauthToken.getValue());
    } catch (Exception e) {
        throw e;
    } finally {
        if (null != oauthToken && remove) {
            this.apiOAuth2TokenManager.removeAccessToken(oauthToken);
        }
    }
    return oauthToken;
}
 
Example #16
Source File: AuthorizationServerConfigurationTest.java    From entando-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
private void refreshAccessToken(OAuth2AccessToken accessToken, String username) throws Exception {
    String refreshToken = accessToken.getRefreshToken().getValue();
    try {
        Assert.assertNotNull(this.apiOAuth2TokenManager.readRefreshToken(refreshToken));
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", "refresh_token");
        params.add("refresh_token", refreshToken);
        String hash = new String(Base64.encode("test1_consumer:secret".getBytes()));
        ResultActions result
                = mockMvc.perform(post("/oauth/token")
                        .params(params)
                        .header("Authorization", "Basic " + hash)
                        .accept("application/json;charset=UTF-8"))
                .andExpect(status().isOk())
                .andExpect(content().contentType("application/json;charset=UTF-8"));
        String resultString = result.andReturn().getResponse().getContentAsString();
        System.out.println(resultString);
        Assert.assertTrue(StringUtils.isNotBlank(resultString));
        String newAccesstoken = JsonPath.parse(resultString).read("$.access_token");
        Assert.assertFalse(newAccesstoken.equals(accessToken.getValue()));
        String newRefreshtoken = JsonPath.parse(resultString).read("$.refresh_token");
        Assert.assertNotEquals(newRefreshtoken, refreshToken);
        Collection<OAuth2AccessToken> oauthTokens = this.apiOAuth2TokenManager.findTokensByUserName(username);
        Assert.assertEquals(1, oauthTokens.size());
        OAuth2AccessToken newOauthToken = oauthTokens.stream().findFirst().get();
        Assert.assertEquals(newAccesstoken, newOauthToken.getValue());
        Assert.assertEquals(newRefreshtoken, newOauthToken.getRefreshToken().getValue());
        Assert.assertNull(this.apiOAuth2TokenManager.readRefreshToken(refreshToken));
    } catch (Exception e) {
        throw e;
    } finally {
        Collection<OAuth2AccessToken> tokens = this.apiOAuth2TokenManager.findTokensByUserName(username);
        for (OAuth2AccessToken token : tokens) {
            this.apiOAuth2TokenManager.removeAccessToken(token);
        }
    }
}
 
Example #17
Source File: RoomDetailsBackend.java    From unitime with Apache License 2.0 5 votes vote down vote up
public String signRequest(String mapsUrl) throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException, MalformedURLException {
	URL url = new URL(mapsUrl);
	String resource = url.getPath() + "?" + url.getQuery();
	SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");
	Mac mac = Mac.getInstance("HmacSHA1");
	mac.init(sha1Key);
	byte[] sigBytes = mac.doFinal(resource.getBytes());
	String signature = new String(Base64.encode(sigBytes));
	signature = signature.replace('+', '-');
	signature = signature.replace('/', '_');
	return signature;
}
 
Example #18
Source File: AbstractEncryptingService.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected String decrypt(String encrypted) {
    Cipher cipher;
    try {
        cipher = Cipher.getInstance(AES_CYPHER);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, initializationVectorSpec);
        byte[] original = cipher.doFinal(Base64.decode(encrypted.getBytes(UTF8_ENCODING)));
        return new String(original, UTF8_ENCODING);
    } catch (GeneralSecurityException nsae) {
        throw new RuntimeException(nsae);
    } catch (UnsupportedEncodingException usee) {
        throw new RuntimeException(usee);
    }
}
 
Example #19
Source File: AES.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public String decrypt(String encryptedText, SecretKey secretKey)
        throws Exception {
    byte[] encryptedTextByte = Base64.decode(encryptedText.getBytes());
    cipher.init(Cipher.DECRYPT_MODE, secretKey);
    byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
    String decryptedText = new String(decryptedByte);
    return decryptedText;
}
 
Example #20
Source File: AES.java    From bushido-java-core with GNU General Public License v3.0 5 votes vote down vote up
public String encrypt(String plainText, SecretKey secretKey)
        throws Exception {
    byte[] plainTextByte = plainText.getBytes();
    cipher.init(Cipher.ENCRYPT_MODE, secretKey);
    byte[] encryptedByte = cipher.doFinal(plainTextByte);
    byte[] encryptedText = Base64.encode(encryptedByte);
    return new String(encryptedText);
}
 
Example #21
Source File: AccessValve.java    From DataHubSystem with GNU Affero General Public License v3.0 5 votes vote down vote up
private String[] extractAndDecodeHeader(String header) throws IOException
{
   if (header == null || header.isEmpty ())
   {
      return null;
   }
   byte[] base64Token = header.substring(6).getBytes("UTF-8");
   byte[] decoded;
   try
   {
      decoded = Base64.decode(base64Token);
   }
   catch (IllegalArgumentException e)
   {
      throw new BadCredentialsException(
         "Failed to decode basic authentication token.");
   }

   String token = new String(decoded, "UTF-8");

   int delim = token.indexOf(":");

   if (delim == -1)
   {
      throw new BadCredentialsException(
         "Invalid basic authentication token.");
   }
   return new String[]{token.substring(0,delim),token.substring(delim+1)};
}
 
Example #22
Source File: SecurityUtils.java    From spring-backend-boilerplate with Apache License 2.0 5 votes vote down vote up
public static String generatePasswordSalt() {
	byte[] aesKey = new byte[16];
	ranGen.nextBytes(aesKey);
	String salt = new String(Base64.encode(aesKey));
	salt = salt.replace("\r", "");
	salt = salt.replace("\n", "");
	return salt;
}
 
Example #23
Source File: AbstractEncryptingService.java    From activiti6-boot2 with Apache License 2.0 5 votes vote down vote up
protected String encrypt(String value) {
    try {
        Cipher cipher = Cipher.getInstance(AES_CYPHER);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, initializationVectorSpec);
        byte[] encrypted = cipher.doFinal(value.getBytes());
        return new String(Base64.encode(encrypted), UTF8_ENCODING);
    } catch (GeneralSecurityException nsae) {
        throw new RuntimeException(nsae);
    } catch (UnsupportedEncodingException uee) {
        throw new RuntimeException(uee);
    }
}
 
Example #24
Source File: BaseController.java    From spring-mvc-angular-js-hibernate-bootstrap-java-single-page-jwt-auth-rest-api-webapp-framework with MIT License 5 votes vote down vote up
public void decorateUserDTOWithCredsFromAuthHeader(String authHeader, UserDTO userDTO) {
    String[] basicAuth = authHeader.split(" ");
    Validate.isTrue(basicAuth.length == 2, "the auth header is not splittable with space");
    Validate.isTrue(basicAuth[0].equalsIgnoreCase("basic"), "not basic auth: "+basicAuth[0]);
    Validate.isTrue(Base64.isBase64(basicAuth[1].getBytes()), "encoded value not base64");

    String decodedAuthHeader = new String(Base64.decode(basicAuth[1].getBytes()));
    String[] creds = decodedAuthHeader.split(":");
    Validate.isTrue(creds.length == 2, "the creds were not concatenated using ':', could not split the decoded header");

    userDTO.setEmail(creds[0]);
    userDTO.setPassword(creds[1]);
}
 
Example #25
Source File: ApplicationTests.java    From Spring-Microservices with MIT License 5 votes vote down vote up
@Test
public void testSecureService() {	
	String plainCreds = "guest:guest123";
	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", "Basic " + new String(Base64.encode(plainCreds.getBytes())));
	HttpEntity<String> request = new HttpEntity<String>(headers);
	RestTemplate restTemplate = new RestTemplate();
	
	ResponseEntity<Greet> response = restTemplate.exchange("http://localhost:8080", HttpMethod.GET, request, Greet.class);
	Assert.assertEquals("Hello World!", response.getBody().getMessage());
}
 
Example #26
Source File: JwtAccessTokenConverter.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
public void setKeyPair(KeyPair keyPair) {
    PrivateKey privateKey = keyPair.getPrivate();
    Assert.state(privateKey instanceof RSAPrivateKey, "KeyPair must be an RSA ");
    signer = new RsaSigner((RSAPrivateKey) privateKey);
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    verifier = new RsaVerifier(publicKey);
    verifierKey = "-----BEGIN PUBLIC KEY-----\n" + new String(Base64.encode(publicKey.getEncoded()))
            + "\n-----END PUBLIC KEY-----";
}
 
Example #27
Source File: RemoteTokenServices.java    From MaxKey with Apache License 2.0 5 votes vote down vote up
private String getAuthorizationHeader(String clientId, String clientSecret) {
	String creds = String.format("%s:%s", clientId, clientSecret);
	try {
		return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
	}
	catch (UnsupportedEncodingException e) {
		throw new IllegalStateException("Could not convert String");
	}
}
 
Example #28
Source File: ApplicationTests.java    From Microservices-Building-Scalable-Software with MIT License 5 votes vote down vote up
@Test
public void testSecureService() {	
	String plainCreds = "guest:guest123";
	HttpHeaders headers = new HttpHeaders();
	headers.add("Authorization", "Basic " + new String(Base64.encode(plainCreds.getBytes())));
	HttpEntity<String> request = new HttpEntity<String>(headers);
	RestTemplate restTemplate = new RestTemplate();
	
	ResponseEntity<Greet> response = restTemplate.exchange("http://localhost:8080", HttpMethod.GET, request, Greet.class);
	Assert.assertEquals("Hello World!", response.getBody().getMessage());
}
 
Example #29
Source File: CustomRemoteTokenServices.java    From microservice-integration with MIT License 5 votes vote down vote up
private String getAuthorizationHeader(String clientId, String clientSecret) {
    String creds = String.format("%s:%s", clientId, clientSecret);
    try {
        return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Could not convert String");
    }
}
 
Example #30
Source File: CustomRemoteTokenServices.java    From microservice-integration with MIT License 5 votes vote down vote up
private String getAuthorizationHeader(String clientId, String clientSecret) {
    String creds = String.format("%s:%s", clientId, clientSecret);
    try {
        return "Basic " + new String(Base64.encode(creds.getBytes("UTF-8")));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException("Could not convert String");
    }
}