【问题标题】:REST TO REST using WSO2 ESBREST TO REST 使用 WSO2 ESB
【发布时间】:2016-01-14 23:22:59
【问题描述】:

我在服务器上部署了一个 REST 服务,并希望通过 WSO2 ESB 公开它(代理它)并使用 ESB 安全性来保护对服务的访问(可能是通过用户名和密码查看的 HTTP BASIC 身份验证) ESB 用户数据库)。我找不到描述如何做的好文档。这可以使用 WSO2 ESB 来完成吗?如何实现?

【问题讨论】:

    标签: wso2 wso2esb


    【解决方案1】:

    您可以参考this 博客文章为 REST 服务创建代理。为了保护服务,有关于如何保护服务的文章。这是one 这样的。

    我正在添加一个新的link 以保护 REST 服务。

    【讨论】:

    • 感谢您的回答。关于安全性的博客文章描述了适用于 WS 但不适用于 REST 服务的 UsernameToken 安全配置文件。
    • 我希望“使用 XACML 对 RESTful 服务进行细粒度授权”的新链接能给您一些有用的提示。
    • 新链接中的示例是否适用于 usernameToken 安全性,或者我必须使用 XACML?
    【解决方案2】:

    您可以为此目的使用 REST API,从 wso2 ESB 4.0.2 开始,它附带 REST API,您可以在其中轻松调用它们,您可以全面了解 REST API 如何在 WSO2 ESB ref REST API Article 中调用

    【讨论】:

      【解决方案3】:

      对于带有 wso2-esb 用户的 http 基本身份验证,我使用这些序列。

      <sequence xmlns="http://ws.apache.org/ns/synapse" name="ValidacionHttpBasica">
      <property name="isAuthorized" value="0" scope="default" type="STRING"/>
      <class name="org.wso2.security.HttpBasicAuthOpMediator"/>
      <switch source="get-property('isAuthorized')">
          <case regex="0">
              <property name="HTTP_SC" value="401" scope="axis2" type="STRING"/>
              <makefault version="soap11">
                  <code xmlns:soap11Env="http://schemas.xmlsoap.org/soap/envelope/" value="soap11Env:Server"/>
                  <reason value="Not Authorized"/>
                  <role/>
              </makefault>
              <respond/>
          </case>
          <default/>
      </switch>
      </sequence>
      

      org.wso2.security.HttpBasicAuthOpMediator (wso2-esb 4.9.0)的代码

      package org.wso2.security;
      
      import java.util.HashMap;
      import java.util.Map;
      
      import org.apache.commons.codec.binary.Base64;
      import org.apache.log4j.Logger;
      import org.apache.synapse.MessageContext;
      import org.apache.synapse.core.axis2.Axis2MessageContext;
      import org.apache.synapse.mediators.AbstractMediator;
      import org.wso2.carbon.context.CarbonContext;
      import org.wso2.carbon.user.api.UserStoreException;
      
      public class HttpBasicAuthOpMediator extends AbstractMediator {
      
      private static final Logger LOGGER = Logger.getLogger(HttpBasicAuthOpMediator.class);
      
      
      /* (non-Javadoc)
       * @see org.apache.synapse.Mediator#mediate(org.apache.synapse.MessageContext)
       */
      public boolean mediate(MessageContext msgctx) {
      
          boolean isOK = true;
      
          try {
      
              //trazearDatos(msgctx);
              org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) msgctx)
                      .getAxis2MessageContext();
              Map<String,String> mHeaders = (Map<String,String>)axis2MessageContext.getProperty("TRANSPORT_HEADERS");
      
      
              // 1 - Validacion de cabeceras de seguridad
              String securityHeader = mHeaders.get("Authorization");
              if ( securityHeader==null || securityHeader.trim().length()<7 ) {
                  throw new RuntimeException ("Request sin cabecera de Autorizacion");
              }
      
              // 2 - Validacion de usuario-contrasenya
              String user = validarUsuario(securityHeader);
      
              // 3 - validacion de operacion asociada a un rol
              if (msgctx.getProperty("SECURITY_OPERATION")!=null && msgctx.getProperty("SECURITY_OPERATION").toString().equalsIgnoreCase("1")) {
                  validarOperacion(user,  mHeaders.get("SOAPAction"), msgctx);
              }
      
              // todo ha ido bien, esta autorizado
              msgctx.setProperty("isAuthorized", "1");
      
          } catch (Exception e) {
              LOGGER.info("ERROR VALIDACION USUARIO ..." + e.getMessage() );
              //isOK = false;
          }
      
          return isOK;
      }
      
      
      
      /**
       * Comprueba que el usuario tiene los roles asociados a la operacion.
       * Si el usuario no tiene los roles, lanza un runtimeExcpetion
       * @param operacion, que se obtiene del soapAction de la cabecera http
       * @param messageContext 
       */
      private void validarOperacion(String user, String operacion, MessageContext messageContext) {
      
          operacion = operacion.replaceAll("\"", "");
          operacion = operacion.replaceAll("'", "");
          //obtener los roles asociados a la operacion
          if ( messageContext.getProperty("SECURITY_OPERATION_" + operacion)!= null ) {
              boolean existeRol = false;
              try {
                  String[] rolesOperation =  messageContext.getProperty("SECURITY_OPERATION_" + operacion).toString().split(",");
                  Map<String,String> mRolesUser = toMap( CarbonContext.getThreadLocalCarbonContext().getUserRealm().getUserStoreManager().getRoleListOfUser(user) );
      
                  for (String rol : rolesOperation) {
                      if (mRolesUser.containsKey(rol)) {
                          existeRol = true;
                          break;
                      }
                  }
                  if (!existeRol) {
                      throw new RuntimeException("Usuario sin role para ejecutar operacion");
                  }
              } catch (Exception e) {
                  throw new RuntimeException("ValidaRoleOperacion:" + e.getMessage() );
              }
          }
      
      
      }
      
      
      
      /**
       * Valida si la cabecera contiene un usuario-contrsenya valido en wso2.
       * Si no lo encuentra lanza un RuntimeExpception.
       * @param cabecera http-header que contiene el usuario-contrsenya en base64.
       */
      private String validarUsuario(String cabecera) {
      
          String credentials = cabecera.substring(6).trim();
          String decodedCredentials = new String(new Base64().decode(credentials.getBytes()));
          String userName = decodedCredentials.split(":")[0];
          String password = decodedCredentials.split(":")[1];
      
          //CarbonContext ctx = CarbonContext.getCurrentContext();
          CarbonContext ctx = CarbonContext.getThreadLocalCarbonContext();
      
          try {
              if ( !ctx.getUserRealm().getUserStoreManager().authenticate(userName, password) )  {
                  throw new RuntimeException("Usuario-contrasenya incorrecto");
              }
          } catch (UserStoreException e) {
              throw new RuntimeException("UserStoreException:" + e.getMessage() );
          }
          return userName;
      }
      
      
      
      public void trazearDatos(MessageContext msgctx ) {
      
          try {
      
          System.out.println("....INICIO_TRAZEO DATOS...............");
          // CABECERAS HTTP para pbtener operacion, user-password. Es un Map<String, String>
          if ( msgctx.getProperty("TRANSPORT_HEADERS") != null ) {
              Map<String,String> mHeaders = (Map<String,String>)msgctx.getProperty("TRANSPORT_HEADERS");
              for (String key:mHeaders.keySet() ) {
                  System.out.println("HEADER_HTTP..." + key + "==" + mHeaders.get(key) );
              }
          } else {
              System.out.println("Es nulo TRANSJPPORT_HEADER, casteamos");
              org.apache.axis2.context.MessageContext axis2MessageContext = ((Axis2MessageContext) msgctx)
                      .getAxis2MessageContext();
              Map<String,String> mHeaders = (Map<String,String>)axis2MessageContext.getProperty("TRANSPORT_HEADERS");
              for (String key:mHeaders.keySet() ) {
                  System.out.println("(cast) HEADER_HTTP..." + key + "==" + mHeaders.get(key) );
              }
          }
      
          // PROPERTIES DEL MESSAGE_CONTEXT
          String keyMC;
          for (Object keyObject : msgctx.getPropertyKeySet() ) {
              keyMC = (String)keyObject;
              System.out.println("PROPERTIES_CONTEXT..." + keyMC + "==" + msgctx.getProperty(keyMC));
          }
      
      
          // pintamos los roles que tiene asignado el usuario
          CarbonContext carbonctx = CarbonContext.getThreadLocalCarbonContext();
      
          String[] roles = carbonctx.getUserRealm().getUserStoreManager().getRoleNames();
          for(String role:roles) {
              System.out.println("ROLE_WSO2..." + role);
          }
          System.out.println("....FIN_TRAZEO DATOS...............");
      
          } catch (Exception e) {
              LOGGER.debug("ERROR TRAZEANDO DATOS VALIDACION USER:" + e.getMessage() );
          }
      
      }
      
      private Map<String,String> toMap(String[] array) {
          Map<String,String> mapa = new HashMap<String,String>();
          if ( array!=null) {
              for (String val : array) {
                  mapa.put(val, val);
              }
          }
          return mapa;
      } 
      

      }

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-13
        • 2017-04-25
        • 2012-05-11
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多