To use secure vault in our custom code, we need to import,
org . wso2. carbon. mediation. security. vault. RegistrySecretRepository;
Dependency -
<dependency > <groupId >org. wso2. carbon</groupId > <artifactId >org. wso2. carbon. mediation. security</artifactId > <version>4.2.0</version> </dependency
Complete source code follows.
package com.wso2.test.Handler;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.apache.synapse.MessageContext;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.core.axis2.Axis2Sender;
import org.apache.synapse.rest.Handler;
import org.wso2.carbon.mediation.security.vault.RegistrySecretRepository;
public class TestHandler implements Handler
{
public void addProperty(String s, Object o) {
}
public Map getProperties() {
return null;
}
public boolean handleRequest(MessageContext messageContext) {
org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) messageContext)
.getAxis2MessageContext();
Object headers = axis2MessageContext.getProperty("TRANSPORT_HEADERS");
if (headers != null && headers instanceof Map) {
Map headersMap = (Map)headers;
if (headersMap.get("Authorization") == null) {
headersMap.clear();
axis2MessageContext.setProperty("HTTP_SC", (Object)"401");
headersMap.put("WWW-Authenticate", "Basic realm=\"WSO2 ESB\"");
axis2MessageContext.setProperty("NO_ENTITY_BODY", (Object)new Boolean("true"));
messageContext.setProperty("RESPONSE", (Object)"true");
messageContext.setTo(null);
Axis2Sender.sendBack((MessageContext)messageContext);
return false;
}
String authHeader = (String)headersMap.get("Authorization");
String credentials = authHeader.substring(6).trim();
if (this.processSecurity(credentials,messageContext)) {
return true;
}
headersMap.clear();
axis2MessageContext.setProperty("HTTP_SC", (Object)"403");
axis2MessageContext.setProperty("NO_ENTITY_BODY", (Object)new Boolean("true"));
messageContext.setProperty("RESPONSE", (Object)"true");
messageContext.setTo(null);
Axis2Sender.sendBack((MessageContext)messageContext);
return false;
}
return true;
}
public boolean handleResponse(MessageContext messageContext) {
return true;
}
public boolean processSecurity(String credentials, MessageContext messageContext) {
String decodedCredentials = new String(new Base64().decode(credentials.getBytes()));
String userName = decodedCredentials.split(":")[0];
String password = decodedCredentials.split(":")[1];
//take the password comes with the “krishan” alias
System.out.println("krishan alias"+" "+"password ="+ getSecretPassword("krishan",messageContext));
if ("admin".equals(userName) && getSecretPassword("krishan",messageContext).equals(password)) {
return true;
}
return false;
}
public String getSecretPassword(String alias, MessageContext messageContext){
RegistrySecretRepository regRepo = new RegistrySecretRepository();
regRepo.setSynCtx(messageContext);
return regRepo.getSecret(alias);
}
}