如何使用 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
我在使用 WSO2 IS 和 WSO2 ESB 通过 OAuth2 保护 REST web 服务时遇到错误。 WSO2 ESB 验证令牌时发生异常。它显示异常 NoSuchMethodError org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;setTokenType(String)
单击此处显示错误Exception Occured in WSO2 ESB
我还更改了 pom.xml : org.wso2.carbon.identity.oauth.stub 的版本从 4.0.7 到 4.2.2 但仍然无法正常工作。
SimpleOauthHandler.java to validate the Token by 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.
}
}
Exception in WSO2-ESB Server : NoSuchMethodError : setTokenType(String)]
Exception Screen Shot
Maven pom.xml here
<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>
如您在 this class 中所见,OAuth2TokenValidationRequestDTO 没有方法 setTokenType
。但是它的内在classOAuth2AccessToken
有。
谢谢 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
我在使用 WSO2 IS 和 WSO2 ESB 通过 OAuth2 保护 REST web 服务时遇到错误。 WSO2 ESB 验证令牌时发生异常。它显示异常 NoSuchMethodError org.wso2.carbon.identity.oauth2.stub.dto.OAuth2TokenValidationRequestDTO;setTokenType(String)
单击此处显示错误Exception Occured in WSO2 ESB
我还更改了 pom.xml : org.wso2.carbon.identity.oauth.stub 的版本从 4.0.7 到 4.2.2 但仍然无法正常工作。
SimpleOauthHandler.java to validate the Token by 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.
}
}
Exception in WSO2-ESB Server : NoSuchMethodError : setTokenType(String)] Exception Screen Shot
Maven pom.xml here
<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>
如您在 this class 中所见,OAuth2TokenValidationRequestDTO 没有方法 setTokenType
。但是它的内在classOAuth2AccessToken
有。
谢谢 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