简体   繁体   English

如何使用 OAuth2 和 WSO2 ESB 4.9.0 和 WSO2-IS 4.5.0 保护 REST 服务

[英]How to Secure REST Service using OAuth2 with WSO2 ESB 4.9.0 & WSO2-IS 4.5.0

I have got the Error while Securing a REST webservice with OAuth2 using WSO2 IS & WSO2 ESB.使用 WSO2 IS & WSO2 ESB 使用 OAuth2 保护 REST Web 服务时出现错误。 An Exception Occur while validating the token by WSO2 ESB.通过 WSO2 ESB 验证令牌时发生异常。 It Shows the Exception NoSuchMethodError org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;setTokenType(String)它显示异常 NoSuchMethodError org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;setTokenType(String)

Click Here to Show Error Exception Occured in WSO2 ESB单击此处显示在 WSO2 ESB 中发生的错误异常

I have also changed the pom.xml: version of org.wso2.carbon.identity.oauth.stub to 4.2.2 from 4.0.7 but still not Working.我还更改了 pom.xml: version of org.wso2.carbon.identity.oauth.stub 到 4.2..2 到 4.2..2

SimpleOauthHandler.java to validate the Token by WSO2-ESB SimpleOauthHandler.java 通过 WSO2-ESB 验证 Token

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.
}

} }

Exception in WSO2-ESB Server: NoSuchMethodError: setTokenType(String)] Exception Screen Shot WSO2-ESB 服务器中的异常:NoSuchMethodError: setTokenType(String)]异常屏幕截图

Maven pom.xml here 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>

As you can see in this class , OAuth2TokenValidationRequestDTO does not have a method setTokenType . 如您在此类中所见,OAuth2TokenValidationRequestDTO没有方法setTokenType But it's inner class OAuth2AccessToken has. 但这是OAuth2AccessToken的内部类。

Thanks Bhathiya 谢谢Bhathiya

I have found the correct code. 我找到了正确的代码。

 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);
     }

Now its Running.... Thanks once again Bhathiya 现在它正在运行。...再次感谢Bhathiya

is there a way to do this check by calling a rest api instead of a stub?有没有办法通过调用 rest api 而不是存根来进行此检查? similar to what is explained under: https://docs.wso2.com/display/IS570/Invoke+the+OAuth+Introspection+Endpoint类似于下面的解释: https://docs.wso2.com/display/IS570/Invoke+the+OAuth+Introspection+Endpoint

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM