Base64 encoding in an Apigee Edge policy

馋奶兔 提交于 2020-01-03 17:13:31

问题


What's the easiest way to do Base64 encoding within an Apigee policy? I need to encode the text of an SMS to be sent programmatically.

I know I could include the code explicitly, but I'd much prefer to use a capability that is built in if available.


回答1:


The most efficient way to accomplish this is to create a python script policy, then use python's built-in base64 module to build a simple function that base64-encodes or -decodes an argument.

If you snag the sample proxies from here: http://apigee.com/docs/api-services/content/api-proxy-samples you'll find a python example in /simpleProxy/apiproxy/resources/py.

The policy XML is like this:

<Script name="Script-GenerateAuthHeader">
  <ResourceURL>py://Authheader.py</ResourceURL>
</Script>

The python code would look like this:

import base64

username = flow.getVariable("request.formparam.client_id")
password = flow.getVariable("request.formparam.client_secret")

base64string = base64.encodestring('%s:%s' % (username, password))[:-1]

flow.setVariable("my.base64.blob", base64string)

Alternatively, if python isn't your style, you could do this in javascript using a js resource, or even directly in a Node.js proxy.




回答2:


The capability to simply inject a HTTP Basic Auth header, or to generate the base64 encoding of a string, is not built in, currently.

You can do it with a Javascript callout, like this.

policy XML:

<Javascript name='JavaScript-SetAuthz'>
  <ResourceURL>jsc://nameOfTheJavaScriptFileHere.js</ResourceURL>
</Javascript>

and the JavaScript




回答3:


We also added a sample that shows how to do this in JavaScript:

https://github.com/apigee/api-platform-samples/tree/master/sample-proxies/base64encoder




回答4:


-- Lack the reputation to comment (such shame) so adding an answer --

Since you asked specifically about encoding text and not binary content, you can make a minor improvement to Cheeso's answer by using b64encode instead of encodestring:

base64string = base64.b64encode('%s:%s' % (username, password))

This is also a tiny bit quicker in my testing.



来源:https://stackoverflow.com/questions/21056816/base64-encoding-in-an-apigee-edge-policy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!