Java Code Examples for org.springframework.util.Base64Utils#encode()

The following examples show how to use org.springframework.util.Base64Utils#encode() . 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: FebsGatewayRequestFilter.java    From FEBS-Cloud with Apache License 2.0 6 votes vote down vote up
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    if (routeEhance) {
        Mono<Void> blackListResult = routeEnhanceService.filterBlackList(exchange);
        if (blackListResult != null) {
            routeEnhanceService.saveBlockLogs(exchange);
            return blackListResult;
        }
        Mono<Void> rateLimitResult = routeEnhanceService.filterRateLimit(exchange);
        if (rateLimitResult != null) {
            routeEnhanceService.saveRateLimitLogs(exchange);
            return rateLimitResult;
        }
        routeEnhanceService.saveRequestLogs(exchange);
    }

    byte[] token = Base64Utils.encode((FebsConstant.GATEWAY_TOKEN_VALUE).getBytes());
    String[] headerValues = {new String(token)};
    ServerHttpRequest build = exchange.getRequest().mutate().header(FebsConstant.GATEWAY_TOKEN_HEADER, headerValues).build();
    ServerWebExchange newExchange = exchange.mutate().request(build).build();
    return chain.filter(newExchange);
}
 
Example 2
Source File: ConfigServicePropertySourceLocator.java    From spring-cloud-config with Apache License 2.0 6 votes vote down vote up
private void addAuthorizationToken(ConfigClientProperties configClientProperties,
		HttpHeaders httpHeaders, String username, String password) {
	String authorization = configClientProperties.getHeaders().get(AUTHORIZATION);

	if (password != null && authorization != null) {
		throw new IllegalStateException(
				"You must set either 'password' or 'authorization'");
	}

	if (password != null) {
		byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
		httpHeaders.add("Authorization", "Basic " + new String(token));
	}
	else if (authorization != null) {
		httpHeaders.add("Authorization", authorization);
	}

}
 
Example 3
Source File: WebTestClientTestBase.java    From spring-auto-restdocs with Apache License 2.0 6 votes vote down vote up
private String getAccessToken(String username, String password) {
    String authorization = "Basic "
            + new String(Base64Utils.encode("app:very_secret".getBytes()));
    String contentType = MediaType.APPLICATION_JSON + ";charset=UTF-8";

    String body = new String(webTestClient.post()
            .uri(uriBuilder -> new DefaultUriBuilderFactory()
                    .uriString("/oauth/token").queryParam("username", username)
                    .queryParam("password", password)
                    .queryParam("grant_type", "password")
                    .queryParam("scope", "read write").queryParam("client_id", "app")
                    .queryParam("client_secret", "very_secret").build())
            .header("Authorization", authorization)
            .contentType(MediaType.APPLICATION_FORM_URLENCODED).exchange()
            .expectStatus().isOk().expectHeader().contentType(contentType)
            .expectBody().jsonPath("$.access_token").isNotEmpty()
            .jsonPath("$.token_type").isEqualTo("bearer").jsonPath("$.refresh_token")
            .isNotEmpty().jsonPath("$.expires_in").isNumber().jsonPath("$.scope")
            .isEqualTo("read write").returnResult().getResponseBody());

    return body.substring(17, 53);
}
 
Example 4
Source File: SentinelRuleLocator.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
private void addAuthorizationToken(ConfigClientProperties configClientProperties,
                                   HttpHeaders httpHeaders, String username, String password) {
    String authorization = configClientProperties.getHeaders().get(AUTHORIZATION);

    if (password != null && authorization != null) {
        throw new IllegalStateException(
            "You must set either 'password' or 'authorization'");
    }

    if (password != null) {
        byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
        httpHeaders.add("Authorization", "Basic " + new String(token));
    } else if (authorization != null) {
        httpHeaders.add("Authorization", authorization);
    }

}
 
Example 5
Source File: AssetLoader.java    From staffjoy with MIT License 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {

    // load image
    InputStream imageFileInputStream = this.getImageFile(IMAGE_FILE_PATH);
    byte[] encodedImage = IOUtils.toByteArray(imageFileInputStream);
    byte[] base64EncodedImage = Base64Utils.encode(encodedImage);
    imageBase64 = new String(base64EncodedImage);

    // load favicon
    InputStream faviconFileInputStream = this.getImageFile(FAVICON_FILE_PATH);
    faviconBytes = IOUtils.toByteArray(faviconFileInputStream);
}
 
Example 6
Source File: GreetingControllerTest.java    From spring-rest-service-oauth with Apache License 2.0 5 votes vote down vote up
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";

	// @formatter:off
	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();

	// @formatter:on

	return content.substring(17, 53);
}
 
Example 7
Source File: MockMvcBase.java    From spring-auto-restdocs with Apache License 2.0 5 votes vote down vote up
private String getAccessToken(String username, String password) throws Exception {
    String authorization = "Basic "
            + new String(Base64Utils.encode("app:very_secret".getBytes()));
    String contentType = MediaType.APPLICATION_JSON + ";charset=UTF-8";

    String body = mockMvc
            .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", "app")
                            .param("client_secret", "very_secret"))
            .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 body.substring(17, 53);
}
 
Example 8
Source File: ControllerIntegrationTest.java    From spring-cloud-open-service-broker with Apache License 2.0 5 votes vote down vote up
protected String buildOriginatingIdentityHeader() throws JsonProcessingException {
	Map<String, Object> propMap = new HashMap<>();
	propMap.put(ORIGINATING_USER_KEY, ORIGINATING_USER_VALUE);
	propMap.put(ORIGINATING_EMAIL_KEY, ORIGINATING_EMAIL_VALUE);
	ObjectMapper mapper = Jackson2ObjectMapperBuilder.json().build();
	String properties = mapper.writeValueAsString(propMap);
	String encodedProperties = new String(Base64Utils.encode(properties.getBytes()));
	return ORIGINATING_IDENTITY_PLATFORM + " " + encodedProperties;
}
 
Example 9
Source File: ConfigClientConfiguration.java    From onetwo with Apache License 2.0 5 votes vote down vote up
/****
 * copy form ConfigServicePropertySourceLocator#getSecureRestTemplate
 * @author weishao zeng
 * @param client
 * @return
 */
private RestTemplate getSecureRestTemplate(ConfigClientProperties client) {
	SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
	requestFactory.setReadTimeout((60 * 1000 * 3) + 5000); //TODO 3m5s, make configurable?
	RestTemplate template = new RestTemplate(requestFactory);
	String username = client.getUsername();
	String password = client.getPassword();
	String authorization = client.getAuthorization();
	Map<String, String> headers = new HashMap<>(client.getHeaders());

	if (password != null && authorization != null) {
		throw new IllegalStateException(
				"You must set either 'password' or 'authorization'");
	}

	if (password != null) {
		byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
		headers.put("Authorization", "Basic " + new String(token));
	}
	else if (authorization != null) {
		headers.put("Authorization", authorization);
	}

	if (!headers.isEmpty()) {
		template.setInterceptors(Arrays.<ClientHttpRequestInterceptor> asList(
				new GenericRequestHeaderInterceptor(headers)));
	}

	return template;
}
 
Example 10
Source File: RSAUtils.java    From danyuan-application with Apache License 2.0 5 votes vote down vote up
/**
 * <p>
 * 用私钥对信息生成数字签名
 * </p>
 * @param data 已加密数据
 * @param privateKey 私钥(BASE64编码)
 * @return
 * @throws Exception
 */
public static byte[] sign(byte[] data, byte[] privateKey) throws Exception {
	byte[] keyBytes = Base64Utils.decode(privateKey);
	PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
	KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
	PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
	Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
	signature.initSign(privateK);
	signature.update(data);
	return Base64Utils.encode(signature.sign());
}
 
Example 11
Source File: JwkSetEndpoint.java    From oauth2-server with MIT License 5 votes vote down vote up
@GetMapping("/.well-known/jwks.json")
@ResponseBody
public Map<String, List<Map<String, Object>>> getKey() {
    Map<String, List<Map<String, Object>>> jwksData = new HashMap<>(16);
    RSAPublicKey publicKey = (RSAPublicKey) this.keyPair.getPublic();

    String n = new String(Base64Utils.encode(BigIntegerUtils.toBytesUnsigned(publicKey.getModulus())));
    String e = new String(Base64Utils.encode(BigIntegerUtils.toBytesUnsigned(publicKey.getPublicExponent())));
    Map<String, Object> jwk = new HashMap<>(16);
    jwk.put("kty", publicKey.getAlgorithm());
    jwk.put("n", n);
    jwk.put("e", e);
    jwksData.put("keys", Arrays.asList(jwk));
    return jwksData;
}
 
Example 12
Source File: MultiModuleConfigServicePropertySourceLocator.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
private void addAuthorizationToken(ConfigClientProperties configClientProperties,
                                   HttpHeaders httpHeaders, String username, String password) {
    String authorization = configClientProperties.getHeaders().get(AUTHORIZATION);

    if (password != null && authorization != null) {
        throw new IllegalStateException("You must set either 'password' or 'authorization'");
    }

    if (password != null) {
        byte[] token = Base64Utils.encode((username + ":" + password).getBytes());
        httpHeaders.add("Authorization", "Basic " + new String(token));
    } else if (authorization != null) {
        httpHeaders.add("Authorization", authorization);
    }
}
 
Example 13
Source File: FebsServerProtectInterceptor.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) throws IOException {
    if (!properties.getOnlyFetchByGateway()) {
        return true;
    }
    String token = request.getHeader(FebsConstant.GATEWAY_TOKEN_HEADER);
    String gatewayToken = new String(Base64Utils.encode(FebsConstant.GATEWAY_TOKEN_VALUE.getBytes()));
    if (StringUtils.equals(gatewayToken, token)) {
        return true;
    } else {
        FebsResponse febsResponse = new FebsResponse();
        FebsUtil.makeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, febsResponse.message("请通过网关获取资源"));
        return false;
    }
}
 
Example 14
Source File: FebsCloudSecurityAutoConfigure.java    From FEBS-Cloud with Apache License 2.0 5 votes vote down vote up
@Bean
public RequestInterceptor oauth2FeignRequestInterceptor() {
    return requestTemplate -> {
        String gatewayToken = new String(Base64Utils.encode(FebsConstant.GATEWAY_TOKEN_VALUE.getBytes()));
        requestTemplate.header(FebsConstant.GATEWAY_TOKEN_HEADER, gatewayToken);
        String authorizationToken = FebsUtil.getCurrentTokenValue();
        if (StringUtils.isNotBlank(authorizationToken)) {
            requestTemplate.header(HttpHeaders.AUTHORIZATION, FebsConstant.OAUTH2_TOKEN_TYPE + authorizationToken);
        }
    };
}
 
Example 15
Source File: AssetLoader.java    From staffjoy with MIT License 5 votes vote down vote up
@PostConstruct
public void init() throws IOException {

    // load image
    InputStream imageFileInputStream = this.getImageFile();
    byte[] encodedImage = IOUtils.toByteArray(imageFileInputStream);
    byte[] base64EncodedImage = Base64Utils.encode(encodedImage);
    imageBase64 = new String(base64EncodedImage);
}
 
Example 16
Source File: RSAUtils.java    From danyuan-application with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * 获取私钥
 * </p>
 * @param keyMap 密钥对
 * @return
 * @throws Exception
 */
public static byte[] getPrivateKey(Map<String, Object> keyMap) throws Exception {
	Key key = (Key) keyMap.get(PRIVATE_KEY);
	return Base64Utils.encode(key.getEncoded());
}
 
Example 17
Source File: RSAUtils.java    From danyuan-application with Apache License 2.0 2 votes vote down vote up
/**
 * <p>
 * 获取公钥
 * </p>
 * @param keyMap 密钥对
 * @return
 * @throws Exception
 */
public static byte[] getPublicKey(Map<String, Object> keyMap) throws Exception {
	Key key = (Key) keyMap.get(PUBLIC_KEY);
	return Base64Utils.encode(key.getEncoded());
}
 
Example 18
Source File: B64Utils.java    From jeesupport with MIT License 2 votes vote down vote up
/**
 * Base64编码
 * 
 * @param _data
 *            待编码数据
 * @return String 编码数据
 */
public static String s_encode( byte[] _data ) {
	byte[] b = Base64Utils.encode( _data );
	return new String( b );
}