Showing posts with label WSO2API. Show all posts
Showing posts with label WSO2API. Show all posts

Tuesday, June 16, 2015

Custom OAuth Grant-Type Support in APIManager


    According to OAuth 2.0 Spec , there are four main grant-types support is available in an OAuth 2.0 authorization server. It supports custom grant type also. WSO2 IS supports OAuth 2.0 spec and it can act as OAuth 2.0 authorization server.

    WSO2 APIManager uses OAuth tokens for API Security. (APIManager uses IS OAuth component to achieve OAuth support). User can write his own gran-type support for API security.

    For this, he has to write; 

  1. GrantTypeHandler : Write the grant type implementation in the handler class. For this implementation user can use AuthorizationGrantHandler  interface or by extending AbstractAuthorizationGrantHandler
  2. GrantTypeValidator: This implementation will validates all the request which are sent to token endpoint. For this implementation, use the "AbstractValidator" class which is available in Amber library from Apache.

Eg: For example, If i want to authorize the requests based on certificates (e.g.;. Grant-type is "cert-auth",) 
OauthHandler:

package org.test.oauth;

import org.wso2.carbon.identity.oauth2.IdentityOAuth2Exception;

import org.wso2.carbon.identity.oauth2.model.RequestParameter;
import org.wso2.carbon.identity.oauth2.token.OAuthTokenReqMessageContext;
import org.wso2.carbon.identity.oauth2.token.handlers.grant.AbstractAuthorizationGrantHandler;
import org.wso2.carbon.identity.oauth2.dto.OAuth2AccessTokenReqDTO;

public class CertificateGrantHandler extends AbstractAuthorizationGrantHandler{
public static final String CERTIFICATE = "sslclientcertb64";

@Override
    public boolean validateGrant(OAuthTokenReqMessageContext tokReqMsgCtx)
            throws IdentityOAuth2Exception {

        boolean authStatus = false;
        
    OAuth2AccessTokenReqDTO oAuth2AccessTokenReqDTO = tokReqMsgCtx.getOauth2AccessTokenReqDTO();
   
    String clientCert = null;
    // extract request parameters
        RequestParameter[] parameters = oAuth2AccessTokenReqDTO.getRequestParameters();

        // find out client certificate
        for(RequestParameter parameter : parameters){
            if(CERTIFICATE.equals(parameter.getKey())){
                if(parameter.getValue() != null && parameter.getValue().length > 0){
                clientCert = parameter.getValue()[0];
                }
            }
        }        
    return authStatus;
    }
}

Validator:


package org.test.oauth;

import org.apache.amber.oauth2.common.validators.AbstractValidator;
import javax.servlet.http.HttpServletRequest;

public class CertificateGrantValidator  extends AbstractValidator {

    public OauthCertificateGrantValidator() {

        // mobile number must be in the request parameter
        requiredParams.add(OauthCertificateGrantHandler.CERTIFICATE);
    }
}

Add the new grant-type in the identity.xml of the APIManager.

eg:


<SupportedGrantType>
<GrantTypeName>cert_auth</GrantTypeName>
<GrantTypeHandlerImplClass>org.test.oauth.CertificateGrantHandler</GrantTypeHandlerImplClass>
<GrantTypeValidatorImplClass>org.test.oauth.CertificateGrantValidator</GrantTypeValidatorImplClass>
</SupportedGrantType>

Generate token using;
curl -k -d "grant_type=cert_auth&sslclientcertb64=" -H "Authorization: Basic , Content-Type: application/x-www-form-urlencoded" http://localhost:8280/token

Tuesday, January 20, 2015

Adding URL parameters in WSO2 APIManager

It is a common use case, where users might want to add URL parameters  which are evaluated dynamically in their endpoints.
We can use same approach what we do in ESB, but it may confuse users on how to implement it in APIManager.
APIManager supports adding custom sequences for the API mediation logic. There are few ways available to add custom mediation plugins.
One, which we can simply use for this requirement is, store the mediation logic in registry as a sequence and select that in the in/out flow of the API invocation when publishing API.

Eg:
If we want to invoke the API with something like(note: we pass PhoneNumber parameter)
http://localhost:8280/dimtry/1.0?PhoneNumber=+16506697051 and send to the backend: http://ws.cdyne.com/phoneverify/phoneverify.asmx/CheckPhoneNumber? PhoneNumber=+16506697051&LicenseKey=0"

In the above example, backend service expects two URL parameters for the GET call to return proper response. But user will pass only one parameter(i.e.: phone number). We need to extract that user parameter and within api mediation logic we need to add another license key parameter too.

To achieve this, When publish an API define HTTP endpoint with parameters and assign values to those parameters in the custom sequence.

Eg: <http uri-template=" http://ws.cdyne.com/phoneverify/phoneverify.asmx/CheckPhoneNumber?Phonenumber={uri.var.PhoneNumber}&LicenseKey={uri.var.LicenseKey}"/>


Here, you need to pass two parameters, which can be passed through the custom sequence. Edit the existing log-in message sequence like below and save;(you can create new sequence and save it)

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

                <property name="uri.var.LicenseKey" value="0" scope="default" type="STRING"/>
                <property name="uri.var.PhoneNumber" expression="substring-after(get-property('To'),'/dimtry/1.0?PhoneNumber=')" scope="default" type="STRING"/>
</sequence>

If you check above sequence,  phonumber is extracted from incoming request using an xpath and hardcoded a value for licensekey, which user can modify according to his requirement.
Now when  we create and publish the api, select above insequence.

APIConfiguration:


Send a GET request for the API like;


You will get response;


Tuesday, April 15, 2014

Securevault support for credientials used in mediation configuration

Secure vault tool which  is available in carbon servers, helps to encrypt passwords which are configured in plain text in the configuration files. This tool can be directly used for the passwords which are configured in carbon.xml,  axis2.xml, datasources.xml etc..We can not use secure vault tool directly in the mediation configuration , where we might provide passwords to make secured connection  for any basic auth protected endpoints.
In the older versions of ESB/APIM, we provide basic auth header by setting the "Authorization" transport header,where password was in plain text.

Eg: 
&lt;property name="Authorization" expression="fn:concat('Basic ', base64Encode('<Username>:<Password>'))" scope="transport"/>

In the newer versions (AM 1.6.0 / ESB 4.8.0 onwards), user can store the encrypted password in registry and  the 'alias' can be used to refer the stored passwords.

Eg:

<property name="secPassword" expression="wso2:vault-lookup('securedDS.endpoint.password')"/>
  • securedDS.endpoint.password : - Password alias, which is stored in config registry under /repository/components/secure-vault
  • wso2:vault-lookup :- Is a custom xpath implementation for synapse to do lookups. To use this custom xpath, user needs to add following synapse property in the synapse.properties file.
synapse.xpath.func.extensions=org.wso2.carbon.mediation.security.vault.xpath.SecureVaultLookupXPathFunctionProvider 

In APIManager;
  •  If user needs to encrypt the password in the mediation configuration, he has to enable the <EnableSecureVault> property in the api-manager.xml, and needs to run the cipher tool before running the product. 
  • Cipher tool is available in the  /bin folder.
    • # ciphertool.bat/sh -Dconfigure
  • When user enables securevault option and  publishes an API via the publisher UI, created API configuration will have the securevault enabled password protection. User can check the alias configured in the API configuration and can map that with the configuration registry entry. Alias is created with the string merge of  publisherName+apiName+version;
 In ESB, user can use management console to create aliases.


Monday, November 26, 2012

Configuring wso2esb to pass messages through proxy server

Organizations may expose the services over a proxy server for several purposes. In such a case, when user configures ESB, he has to provide proxy server configurations.
In axis2 configuration , at the transport sender configuration two properties has to be provided.
  • http.proxyHost : Proxy server's IP
  • http.proxyPort : Prosy server's port
eg :
 <transportSender name="http" class="org.apache.synapse.transport.nhttp.HttpCoreNIOSender">
        <parameter name="non-blocking" locked="false">true&lt;/parameter>
        <parameter name="http.proxyHost" locked="false">192.168.0.26  </parameter>
        <parameter name="http.proxyPort" locked="false">3128</parameter>
 </transportSender>
And a property (POST_TO_URI) has to be set in the synapse configuration to make ESB's out going URL a complete URL.

eg:
<inSequence>
    <property name="POST_TO_URI" value="true" scope="axis2"/>
    <send>
        <endpoint>
            <address uri="http://192.168.0.26:9000/services/SimpleStockQuoteService"/>
        </endpoint>
    </send>
</inSequence>
Depends on the proxy server's behaviour we may need to set some additional properties.
  • DISABLE_CHUNKING : If the proxy server doesn't support HTTP chunking. 
<property name="DISABLE_CHUNKING" value="true" scope="axis2"/>
  • FORCE_HTTP_1.0 : If proxy server supports only HTTP/1.0 messages.
<property name="FORCE_HTTP_1.0" value="true" scope="axis2"/>
 These properties can be applied to WSO2API Manager as well, since WSO2ESB is used as the gateway for APIManager.