Saturday, June 24, 2017

WSO2 API Manager: Access user attributes from a custom sequence


For some use cases, API developer may want to access the API invoker's user information (such as his email address, roles etc). Easiest method to access these information is by getting the user claims for that user. Following method describes how to access user claims and extract a selected claim using a custom sequence

1. Enable JWT token as mentioned in here. This token contains the user related claims and it is set to the X-JWT-Assertion header during the authentication process.

2. Create a custom mediator sequence using Mediation extension feature. Following is a sample mediation sequence that can be used to extract the claim from jwt token.


<sequence xmlns="http://ws.apache.org/ns/synapse" name="jwt_decoder">

<property name="jwt-header" expression="get-property('transport','X-JWT-Assertion')"/>

<script language="js">
var jwt = mc.getProperty('jwt-header').trim();
var jwtPayload = jwt.split("\\.")[1];
var jsonStr = Packages.java.lang.String(Packages.org.apache.commons.codec.binary.Base64.decodeBase64(jwtPayload));

var jwtJson = JSON.parse(jsonStr);

var roles = jwtJson['http://wso2.org/claims/role'];
mc.setProperty("roles",JSON.stringify(roles));
</script>

<log level="custom">
  <property name="USER_ROLES" expression="$ctx:roles"/>
</log>

</sequence>

No comments:

Post a Comment