2016-02-02 5 views
0

У меня есть Ошибка при обеспечении безопасности веб-службы REST с помощью OAuth2 с использованием WSO2 IS & WSO2 ESB. Исключение возникает при проверке маркера с помощью WSO2 ESB. Это показывает исключение NoSuchMethodError org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; setTokenType (String)Как защитить службу REST с помощью OAuth2 с помощью WSO2 ESB 4.9.0 и WSO2-IS 4.5.0

Нажмите здесь, чтобы показать ошибку Exception Occured in WSO2 ESB

Я также изменил pom.xml: версию org.wso2.carbon.identity.oauth.stub до 4.2.2 из 4.0.7, но все еще не работает.

SimpleOauthHandler.java для проверки Знак по WSO2-ESB

import java.util.Map; 
import org.apache.axis2.client.Options; 
import org.apache.axis2.client.ServiceClient; 
import org.apache.axis2.context.ConfigurationContext; 
import org.apache.axis2.context.ConfigurationContextFactory; 
import org.apache.axis2.transport.http.HTTPConstants; 
import org.apache.axis2.transport.http.HttpTransportProperties; 
import org.apache.http.HttpHeaders; 
import org.apache.synapse.ManagedLifecycle; 
import org.apache.synapse.MessageContext; 
import org.apache.synapse.core.SynapseEnvironment; 
import org.apache.synapse.core.axis2.Axis2MessageContext; 
import org.apache.synapse.rest.AbstractHandler; 
import  
org.wso2.carbon.identity.oauth2.stub.OAuth2TokenValidationServiceStub; 
import 
org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO; 

public class SimpleOauthHandler extends AbstractHandler implements ManagedLifecycle { 

private String securityHeader = HttpHeaders.AUTHORIZATION; 
private String consumerKeyHeaderSegment = "Bearer"; 
private String oauthHeaderSplitter = ","; 
private String consumerKeySegmentDelimiter = " "; 
private String oauth2TokenValidationService = "oauth2TokenValidationService"; 
private String identityServerUserName = "identityServerUserName"; 
private String identityServerPw = "identityServerPw"; 


public boolean handleRequest(MessageContext messageContext) { 
    try{ 
     ConfigurationContext configCtx = ConfigurationContextFactory.createConfigurationContextFromFileSystem(null, null); 
     //Read parameters from axis2.xml 
     String identityServerUrl = messageContext.getConfiguration().getAxisConfiguration().getParameter(oauth2TokenValidationService).getValue().toString(); 
     String username = messageContext.getConfiguration().getAxisConfiguration().getParameter(identityServerUserName).getValue().toString(); 
     String password = messageContext.getConfiguration().getAxisConfiguration().getParameter(identityServerPw).getValue().toString(); 

     OAuth2TokenValidationServiceStub stub = new OAuth2TokenValidationServiceStub(configCtx,identityServerUrl); 
     ServiceClient client = stub._getServiceClient(); 
     Options options = client.getOptions(); 
     HttpTransportProperties.Authenticator authenticator = new HttpTransportProperties.Authenticator(); 
     authenticator.setUsername(username); 
     authenticator.setPassword(password); 
     authenticator.setPreemptiveAuthentication(true); 

     options.setProperty(HTTPConstants.AUTHENTICATE, authenticator); 
     client.setOptions(options); 
     OAuth2TokenValidationRequestDTO dto = new OAuth2TokenValidationRequestDTO(); 
     dto.setTokenType("bearer"); 
     Map headers = (Map) ((Axis2MessageContext) messageContext).getAxis2MessageContext(). 
       getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS); 
     String apiKey = null; 
     if (headers != null) { 
      apiKey = extractCustomerKeyFromAuthHeader(headers); 
     } 
     dto.setAccessToken(apiKey); 
     //validate passed apiKey(token) 
     if(stub.validate(dto).getValid()){ 
      return true; 
     }else{ 
      return false; 
     } 
    }catch(Exception e){ 
     e.printStackTrace(); 
     return false; 
    } 
} 

public String extractCustomerKeyFromAuthHeader(Map headersMap) { 

    //From 1.0.7 version of this component onwards remove the OAuth authorization header from 
    // the message is configurable. So we dont need to remove headers at this point. 
    String authHeader = (String) headersMap.get(securityHeader); 
    if (authHeader == null) { 
     return null; 
    } 

    if (authHeader.startsWith("OAuth ") || authHeader.startsWith("oauth ")) { 
     authHeader = authHeader.substring(authHeader.indexOf("o")); 
    } 

    String[] headers = authHeader.split(oauthHeaderSplitter); 
    if (headers != null) { 
     for (int i = 0; i < headers.length; i++) { 
      String[] elements = headers[i].split(consumerKeySegmentDelimiter); 
      if (elements != null && elements.length > 1) { 
       int j = 0; 
       boolean isConsumerKeyHeaderAvailable = false; 
       for (String element : elements) { 
        if (!"".equals(element.trim())) { 
         if (consumerKeyHeaderSegment.equals(elements[j].trim())) { 
          isConsumerKeyHeaderAvailable = true; 
         } else if (isConsumerKeyHeaderAvailable) { 
          return removeLeadingAndTrailing(elements[j].trim()); 
         } 
        } 
        j++; 
       } 
      } 
     } 
    } 
    return null; 
} 

private String removeLeadingAndTrailing(String base) { 
    String result = base; 

    if (base.startsWith("\"") || base.endsWith("\"")) { 
     result = base.replace("\"", ""); 
    } 
    return result.trim(); 
} 


public boolean handleResponse(MessageContext messageContext) { 
    return true; 
} 

public void init(SynapseEnvironment synapseEnvironment) { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 


public void destroy() { 
    //To change body of implemented methods use File | Settings | File Templates. 
} 

}

исключений в WSO2-ESB сервер: NoSuchMethodError: setTokenType (строка) ] Exception Screen Shot

Maven pom.xml здесь

<project xmlns="http://maven.apache.org/POM/4.0.0" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0  
http://maven.apache.org/xsd/maven-4.0.0.xsd"> 
<modelVersion>4.0.0</modelVersion> 

<groupId>handler</groupId> 
<artifactId>handler</artifactId> 
<version>1.0</version> 
<repositories> 
<repository> 
<id>wso2-nexus</id> 
<name>WSO2 internal Repository</name> 
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url> 
<releases> 
<enabled>true</enabled> 
<updatePolicy>daily</updatePolicy> 
<checksumPolicy>ignore</checksumPolicy> 
</releases> 
</repository> 
</repositories> 
<dependencies> 
<dependency> 
<groupId>org.apache.synapse</groupId> 
<artifactId>synapse-core</artifactId> 
<version>2.1.1-wso2v1</version> 
</dependency> 
<dependency> 
    <groupId>org.apache.axis2.wso2</groupId> 
    <artifactId>axis2</artifactId> 
    <version>1.6.1.wso2v7</version> 
</dependency> 
<dependency> 
    <groupId>org.wso2.carbon</groupId> 
    <artifactId>org.wso2.carbon.identity.oauth.stub</artifactId> 
    <version>4.0.7</version> 
</dependency> 
</dependencies> 
</project> 

ответ

0

Как вы можете видеть в this class, OAuth2TokenValidationRequestDTO не метод setTokenType. Но это внутренний класс OAuth2AccessToken имеет.

0

Благодаря Bhathiya

Я нашел правильный код.

OAuth2TokenValidationRequestDTO oauthReq = new  
            OAuth2TokenValidationRequestDTO(); 
OAuth2TokenValidationRequestDTO_OAuth2AccessToken accessToken= new 
        OAuth2TokenValidationRequestDTO_OAuth2AccessToken(); 
accessToken.setTokenType(BEARER_TOKEN_TYPE); 
accessToken.setIdentifier(apiKey); 
oauthReq.setAccessToken(accessToken); 
try { 
      return stub.validate(oauthReq).getValid(); 
    } 
catch (RemoteException e) { 
      throw new Exception("Error while validating OAuth2 request", e); 
    } 

Теперь его Выполняемые .... Еще раз спасибо Bhathiya

+0

Да это Corect путь. – Bee

Смежные вопросы