├── .gitignore ├── src └── main │ └── java │ └── org │ └── apache │ └── amber │ └── oauth2 │ ├── common │ ├── token │ │ ├── OAuthToken.java │ │ └── BasicOAuthToken.java │ ├── domain │ │ ├── credentials │ │ │ ├── Credentials.java │ │ │ ├── BasicCredentialsBuilder.java │ │ │ └── BasicCredentials.java │ │ └── client │ │ │ ├── ClientInfo.java │ │ │ ├── BasicClientInfoBuilder.java │ │ │ └── BasicClientInfo.java │ ├── message │ │ ├── types │ │ │ ├── ResponseType.java │ │ │ ├── TokenType.java │ │ │ ├── ParameterStyle.java │ │ │ └── GrantType.java │ │ ├── OAuthMessage.java │ │ └── OAuthResponse.java │ ├── exception │ │ ├── OAuthRuntimeException.java │ │ ├── OAuthSystemException.java │ │ └── OAuthProblemException.java │ ├── parameters │ │ ├── BodyURLEncodedParametersApplier.java │ │ ├── WWWAuthHeaderParametersApplier.java │ │ ├── JSONBodyParametersApplier.java │ │ ├── OAuthParametersApplier.java │ │ └── QueryParameterApplier.java │ ├── validators │ │ ├── OAuthValidator.java │ │ └── AbstractValidator.java │ ├── utils │ │ ├── JSONUtils.java │ │ └── OAuthUtils.java │ ├── OAuth.java │ └── error │ │ └── OAuthError.java │ └── as │ ├── issuer │ ├── ValueGenerator.java │ ├── OAuthIssuer.java │ ├── UUIDValueGenerator.java │ ├── OAuthIssuerImpl.java │ └── MD5Generator.java │ ├── validator │ ├── ClientCredentialValidator.java │ ├── AssertionValidator.java │ ├── PasswordValidator.java │ ├── RefreshTokenValidator.java │ ├── AuthorizationCodeValidator.java │ ├── CodeValidator.java │ ├── CodeTokenValidator.java │ └── TokenValidator.java │ ├── request │ ├── OAuthAuthzRequest.java │ ├── OAuthTokenRequest.java │ └── OAuthRequest.java │ └── response │ └── OAuthASResponse.java ├── pom.xml ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | target/ 2 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/token/OAuthToken.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.token; 22 | 23 | /** 24 | * 25 | */ 26 | public interface OAuthToken { 27 | 28 | public String getAccessToken(); 29 | 30 | public Long getExpiresIn(); 31 | 32 | public String getRefreshToken(); 33 | 34 | public String getScope(); 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/issuer/ValueGenerator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.issuer; 23 | 24 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 25 | 26 | 27 | /** 28 | * 29 | * 30 | * 31 | */ 32 | public interface ValueGenerator { 33 | public String generateValue() throws OAuthSystemException; 34 | 35 | public String generateValue(String param) throws OAuthSystemException; 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/domain/credentials/Credentials.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.domain.credentials; 22 | 23 | import java.lang.Long;import java.lang.String; /** 24 | * 25 | * 26 | * 27 | */ 28 | public interface Credentials { 29 | 30 | String getClientId(); 31 | 32 | String getClientSecret(); 33 | 34 | Long getIssuedAt(); 35 | 36 | Long getExpiresIn(); 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/message/types/ResponseType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.message.types; 23 | 24 | /** 25 | * 26 | * 27 | * 28 | */ 29 | public enum ResponseType { 30 | 31 | CODE("code"), 32 | TOKEN("token"); 33 | 34 | private String code; 35 | 36 | ResponseType(String code) { 37 | this.code = code; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return code; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/issuer/OAuthIssuer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.issuer; 23 | 24 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 25 | 26 | /** 27 | * 28 | * 29 | * 30 | */ 31 | public interface OAuthIssuer { 32 | public String accessToken() throws OAuthSystemException; 33 | 34 | public String authorizationCode() throws OAuthSystemException; 35 | 36 | public String refreshToken() throws OAuthSystemException; 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/message/types/TokenType.java: -------------------------------------------------------------------------------- 1 | package org.apache.amber.oauth2.common.message.types; 2 | /** 3 | * Copyright 2010 Newcastle University 4 | * 5 | * http://research.ncl.ac.uk/smart/ 6 | * 7 | * Licensed to the Apache Software Foundation (ASF) under one or more 8 | * contributor license agreements. See the NOTICE file distributed with 9 | * this work for additional information regarding copyright ownership. 10 | * The ASF licenses this file to You under the Apache License, Version 2.0 11 | * (the "License"); you may not use this file except in compliance with 12 | * the License. You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | 24 | /** 25 | * 26 | * 27 | * 28 | */ 29 | public enum TokenType { 30 | BEARER("Bearer"), 31 | MAC("MAC"); 32 | 33 | private String tokenType; 34 | 35 | TokenType(String grantType) { 36 | this.tokenType = grantType; 37 | } 38 | 39 | @Override 40 | public String toString() { 41 | return tokenType; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/ClientCredentialValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.common.OAuth; 27 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 28 | 29 | public class ClientCredentialValidator extends AbstractValidator { 30 | public ClientCredentialValidator() { 31 | requiredParams.add(OAuth.OAUTH_GRANT_TYPE); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/message/types/ParameterStyle.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.message.types; 23 | 24 | /** 25 | * 26 | * 27 | * 28 | */ 29 | public enum ParameterStyle { 30 | BODY("body"), 31 | QUERY("query"), 32 | HEADER("header"); 33 | 34 | private String parameterStyle; 35 | 36 | ParameterStyle(String parameterStyle) { 37 | this.parameterStyle = parameterStyle; 38 | } 39 | 40 | @Override 41 | public String toString() { 42 | return parameterStyle; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/domain/client/ClientInfo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.domain.client; 23 | 24 | /** 25 | * 26 | * 27 | * 28 | */ 29 | public interface ClientInfo { 30 | 31 | String getClientId(); 32 | 33 | String getClientSecret(); 34 | 35 | Long getIssuedAt(); 36 | 37 | Long getExpiresIn(); 38 | 39 | String getRedirectUri(); 40 | 41 | String getClientUri(); 42 | 43 | String getDescription(); 44 | 45 | String getName(); 46 | 47 | String getIconUri(); 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/AssertionValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | 25 | import org.apache.amber.oauth2.common.OAuth; 26 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 27 | 28 | /** 29 | * 30 | * 31 | * 32 | */ 33 | public class AssertionValidator extends AbstractValidator { 34 | 35 | public AssertionValidator() { 36 | requiredParams.add(OAuth.OAUTH_GRANT_TYPE); 37 | requiredParams.add(OAuth.OAUTH_ASSERTION_TYPE); 38 | requiredParams.add(OAuth.OAUTH_ASSERTION); 39 | } 40 | 41 | 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/message/OAuthMessage.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.message; 23 | 24 | import java.util.Map; 25 | 26 | /** 27 | * 28 | * 29 | * 30 | */ 31 | public interface OAuthMessage { 32 | 33 | String getLocationUri(); 34 | 35 | void setLocationUri(String uri); 36 | 37 | String getBody(); 38 | 39 | void setBody(String body); 40 | 41 | String getHeader(String name); 42 | 43 | void addHeader(String name, String header); 44 | 45 | Map getHeaders(); 46 | 47 | void setHeaders(Map headers); 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/message/types/GrantType.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.message.types; 23 | 24 | /** 25 | * 26 | * 27 | * 28 | */ 29 | public enum GrantType { 30 | // NONE("none"), 31 | AUTHORIZATION_CODE("authorization_code"), 32 | PASSWORD("password"), 33 | REFRESH_TOKEN("refresh_token"), 34 | CLIENT_CREDENTIALS("client_credentials"); 35 | 36 | private String grantType; 37 | 38 | GrantType(String grantType) { 39 | this.grantType = grantType; 40 | } 41 | 42 | @Override 43 | public String toString() { 44 | return grantType; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/exception/OAuthRuntimeException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2011 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.exception; 22 | 23 | /** 24 | */ 25 | public class OAuthRuntimeException extends RuntimeException { 26 | public OAuthRuntimeException() { 27 | super(); 28 | } 29 | 30 | public OAuthRuntimeException(String message) { 31 | super(message); 32 | } 33 | 34 | public OAuthRuntimeException(String message, Throwable cause) { 35 | super(message, cause); 36 | } 37 | 38 | public OAuthRuntimeException(Throwable cause) { 39 | super(cause); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/PasswordValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.common.OAuth; 27 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 28 | 29 | /** 30 | * 31 | * 32 | * 33 | */ 34 | public class PasswordValidator extends AbstractValidator { 35 | 36 | public PasswordValidator() { 37 | 38 | requiredParams.add(OAuth.OAUTH_GRANT_TYPE); 39 | requiredParams.add(OAuth.OAUTH_CLIENT_ID); 40 | requiredParams.add(OAuth.OAUTH_USERNAME); 41 | requiredParams.add(OAuth.OAUTH_PASSWORD); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/RefreshTokenValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | 25 | import play.api.mvc.Request; 26 | 27 | import org.apache.amber.oauth2.common.OAuth; 28 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 29 | 30 | /** 31 | * 32 | * 33 | * 34 | */ 35 | public class RefreshTokenValidator extends AbstractValidator { 36 | 37 | public RefreshTokenValidator() { 38 | requiredParams.add(OAuth.OAUTH_GRANT_TYPE); 39 | requiredParams.add(OAuth.OAUTH_CLIENT_ID); 40 | requiredParams.add(OAuth.OAUTH_REFRESH_TOKEN); 41 | requiredParams.add(OAuth.OAUTH_CLIENT_SECRET); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/issuer/UUIDValueGenerator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.issuer; 23 | 24 | import java.util.UUID; 25 | 26 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 27 | 28 | /** 29 | * Exemplar OAuth Token Generator 30 | * 31 | * 32 | * 33 | * 34 | */ 35 | public class UUIDValueGenerator implements ValueGenerator { 36 | 37 | @Override 38 | public String generateValue() throws OAuthSystemException { 39 | return generateValue(UUID.randomUUID().toString()); 40 | } 41 | 42 | @Override 43 | public String generateValue(String param) throws OAuthSystemException { 44 | return UUID.fromString(UUID.nameUUIDFromBytes(param.getBytes()).toString()).toString(); 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/AuthorizationCodeValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.common.OAuth; 27 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 28 | 29 | /** 30 | * 31 | * 32 | * 33 | */ 34 | public class AuthorizationCodeValidator extends AbstractValidator { 35 | 36 | public AuthorizationCodeValidator() { 37 | requiredParams.add(OAuth.OAUTH_GRANT_TYPE); 38 | requiredParams.add(OAuth.OAUTH_CLIENT_ID); 39 | requiredParams.add(OAuth.OAUTH_CODE); 40 | requiredParams.add(OAuth.OAUTH_REDIRECT_URI); 41 | requiredParams.add(OAuth.OAUTH_CLIENT_SECRET); 42 | } 43 | 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/issuer/OAuthIssuerImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.issuer; 23 | 24 | 25 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 26 | 27 | /** 28 | * 29 | * 30 | * 31 | */ 32 | public class OAuthIssuerImpl implements OAuthIssuer { 33 | 34 | private ValueGenerator vg; 35 | 36 | public OAuthIssuerImpl(ValueGenerator vg) { 37 | this.vg = vg; 38 | } 39 | 40 | public String accessToken() throws OAuthSystemException { 41 | return vg.generateValue(); 42 | } 43 | 44 | public String refreshToken() throws OAuthSystemException { 45 | return vg.generateValue(); 46 | } 47 | 48 | public String authorizationCode() throws OAuthSystemException { 49 | return vg.generateValue(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/parameters/BodyURLEncodedParametersApplier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.parameters; 23 | 24 | import java.util.Map; 25 | 26 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 27 | import org.apache.amber.oauth2.common.message.OAuthMessage; 28 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 29 | 30 | /** 31 | * 32 | * 33 | * 34 | */ 35 | public class BodyURLEncodedParametersApplier implements OAuthParametersApplier { 36 | 37 | public OAuthMessage applyOAuthParameters(OAuthMessage message, Map params) 38 | throws OAuthSystemException { 39 | 40 | String body = OAuthUtils.format(params.entrySet(), "UTF-8"); 41 | message.setBody(body); 42 | return message; 43 | 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/parameters/WWWAuthHeaderParametersApplier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.parameters; 23 | 24 | import java.util.Map; 25 | 26 | import org.apache.amber.oauth2.common.OAuth; 27 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 28 | import org.apache.amber.oauth2.common.message.OAuthMessage; 29 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 30 | 31 | /** 32 | * 33 | * 34 | * 35 | */ 36 | public class WWWAuthHeaderParametersApplier implements OAuthParametersApplier { 37 | 38 | public OAuthMessage applyOAuthParameters(OAuthMessage message, Map params) 39 | throws OAuthSystemException { 40 | String header = OAuthUtils.encodeOAuthHeader(params); 41 | message.addHeader(OAuth.HeaderType.WWW_AUTHENTICATE, header); 42 | return message; 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/validators/OAuthValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.validators; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 27 | 28 | /** 29 | * 30 | * 31 | * 32 | */ 33 | public interface OAuthValidator { 34 | 35 | public void validateMethod(T request) throws OAuthProblemException; 36 | 37 | public void validateContentType(T request) throws OAuthProblemException; 38 | 39 | public void validateRequiredParameters(T request) throws OAuthProblemException; 40 | 41 | public void validateOptionalParameters(T request) throws OAuthProblemException; 42 | 43 | public void validateNotAllowedParameters(T request) throws OAuthProblemException; 44 | 45 | public void performAllValidations(T request) throws OAuthProblemException; 46 | 47 | } 48 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/exception/OAuthSystemException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.exception; 23 | 24 | /** 25 | * 26 | * 27 | */ 28 | public class OAuthSystemException extends Exception { 29 | 30 | public OAuthSystemException() { 31 | super(); //To change body of overridden methods use File | Settings | File Templates. 32 | } 33 | 34 | public OAuthSystemException(String s) { 35 | super(s); //To change body of overridden methods use File | Settings | File Templates. 36 | } 37 | 38 | public OAuthSystemException(Throwable throwable) { 39 | super(throwable); //To change body of overridden methods use File | Settings | File Templates. 40 | } 41 | 42 | public OAuthSystemException(String s, Throwable throwable) { 43 | super(s, throwable); //To change body of overridden methods use File | Settings | File Templates. 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 4.0.0 3 | org.apache.amber 4 | oauth2play2scala 5 | 0.0.1 6 | 7 | 8 | 9 | typesafe 10 | typesafe-releases 11 | http://repo.typesafe.com/typesafe/repo 12 | 13 | 14 | 15 | 16 | 21 | 22 | 23 | org.codehaus.jettison 24 | jettison 25 | 1.2 26 | 27 | 28 | stax 29 | stax-api 30 | 31 | 32 | 33 | 34 | 35 | org.slf4j 36 | slf4j-api 37 | 1.6.1 38 | 39 | 40 | 41 | org.slf4j 42 | slf4j-log4j12 43 | 1.6.0 44 | test 45 | 46 | 47 | 48 | org.scala-lang 49 | scala-library 50 | 2.10.2 51 | 52 | 53 | 54 | play 55 | play_2.10 56 | 2.1.1 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/parameters/JSONBodyParametersApplier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.parameters; 23 | 24 | import java.util.Map; 25 | 26 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 27 | import org.apache.amber.oauth2.common.message.OAuthMessage; 28 | import org.apache.amber.oauth2.common.utils.JSONUtils; 29 | import org.codehaus.jettison.json.JSONException; 30 | 31 | /** 32 | * 33 | * 34 | * 35 | */ 36 | public class JSONBodyParametersApplier implements OAuthParametersApplier { 37 | public OAuthMessage applyOAuthParameters(OAuthMessage message, Map params) 38 | throws OAuthSystemException { 39 | String json = null; 40 | try { 41 | json = JSONUtils.buildJSON(params); 42 | message.setBody(json); 43 | return message; 44 | } catch (JSONException e) { 45 | throw new OAuthSystemException(e); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/parameters/OAuthParametersApplier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.parameters; 23 | 24 | import java.util.Map; 25 | 26 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 27 | import org.apache.amber.oauth2.common.message.OAuthMessage; 28 | 29 | /** 30 | * Applies given parameters to the OAuth message. 31 | * Provided implementations include OAuth parameters in one of those: 32 | *
    33 | *
  • HTTP request URI Query
  • 34 | *
  • HTTP request entity-body with application/x-www-form-urlencoded encoding
  • 35 | *
  • HTTP request entity-body with application/json encoding
  • 36 | *
  • HTTP request Authorization/WWW-Authenticate header
  • 37 | *
38 | *

39 | * Additional implementations can be provided. 40 | * 41 | * 42 | * 43 | * 44 | */ 45 | public interface OAuthParametersApplier { 46 | 47 | OAuthMessage applyOAuthParameters(OAuthMessage message, Map params) throws 48 | OAuthSystemException; 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/CodeValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.common.OAuth; 27 | import org.apache.amber.oauth2.common.error.OAuthError; 28 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 29 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 30 | 31 | 32 | /** 33 | * 34 | * 35 | * 36 | */ 37 | public class CodeValidator extends AbstractValidator { 38 | 39 | public CodeValidator() { 40 | requiredParams.add(OAuth.OAUTH_RESPONSE_TYPE); 41 | requiredParams.add(OAuth.OAUTH_CLIENT_ID); 42 | } 43 | 44 | @Override 45 | public void validateMethod(Request request) throws OAuthProblemException { 46 | String method = request.method(); 47 | if (!OAuth.HttpMethod.GET.equals(method) && !OAuth.HttpMethod.POST.equals(method)) { 48 | throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) 49 | .description("Method not correct."); 50 | } 51 | } 52 | 53 | @Override 54 | public void validateContentType(Request request) throws OAuthProblemException { 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/domain/credentials/BasicCredentialsBuilder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.domain.credentials; 22 | 23 | /** 24 | */ 25 | public class BasicCredentialsBuilder { 26 | 27 | protected BasicCredentials credentials; 28 | 29 | private BasicCredentialsBuilder() { 30 | credentials = new BasicCredentials(); 31 | } 32 | 33 | public static BasicCredentialsBuilder credentials() { 34 | return new BasicCredentialsBuilder(); 35 | } 36 | 37 | public BasicCredentials build() { 38 | return credentials; 39 | } 40 | 41 | public BasicCredentialsBuilder setClientId(String value) { 42 | credentials.setClientId(value); 43 | return this; 44 | } 45 | 46 | public BasicCredentialsBuilder setClientSecret(String value) { 47 | credentials.setClientSecret(value); 48 | return this; 49 | } 50 | 51 | public BasicCredentialsBuilder setExpiresIn(Long value) { 52 | credentials.setExpiresIn(value); 53 | return this; 54 | } 55 | 56 | public BasicCredentialsBuilder setIssuedAt(Long value) { 57 | credentials.setIssuedAt(value); 58 | return this; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/CodeTokenValidator.java: -------------------------------------------------------------------------------- 1 | 2 | /** 3 | * Copyright 2010 Newcastle University 4 | * 5 | * http://research.ncl.ac.uk/smart/ 6 | * 7 | * Licensed to the Apache Software Foundation (ASF) under one or more 8 | * contributor license agreements. See the NOTICE file distributed with 9 | * this work for additional information regarding copyright ownership. 10 | * The ASF licenses this file to You under the Apache License, Version 2.0 11 | * (the "License"); you may not use this file except in compliance with 12 | * the License. You may obtain a copy of the License at 13 | * 14 | * http://www.apache.org/licenses/LICENSE-2.0 15 | * 16 | * Unless required by applicable law or agreed to in writing, software 17 | * distributed under the License is distributed on an "AS IS" BASIS, 18 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | * See the License for the specific language governing permissions and 20 | * limitations under the License. 21 | */ 22 | 23 | package org.apache.amber.oauth2.as.validator; 24 | 25 | import play.api.mvc.Request; 26 | 27 | import org.apache.amber.oauth2.common.OAuth; 28 | import org.apache.amber.oauth2.common.error.OAuthError; 29 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 30 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 31 | 32 | 33 | /** 34 | * 35 | * 36 | * 37 | */ 38 | public class CodeTokenValidator extends AbstractValidator { 39 | 40 | public CodeTokenValidator() { 41 | requiredParams.add(OAuth.OAUTH_RESPONSE_TYPE); 42 | requiredParams.add(OAuth.OAUTH_CLIENT_ID); 43 | requiredParams.add(OAuth.OAUTH_REDIRECT_URI); 44 | } 45 | 46 | @Override 47 | public void validateMethod(Request request) throws OAuthProblemException { 48 | String method = request.method(); 49 | if (!method.equals(OAuth.HttpMethod.GET) && !method.equals(OAuth.HttpMethod.POST)) { 50 | throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) 51 | .description("Method not correct."); 52 | } 53 | } 54 | 55 | @Override 56 | public void validateContentType(Request request) throws OAuthProblemException { 57 | } 58 | } 59 | 60 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/issuer/MD5Generator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.issuer; 23 | 24 | import java.security.MessageDigest; 25 | import java.util.UUID; 26 | 27 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 28 | 29 | 30 | /** 31 | * Exemplar OAuth Token Generator 32 | * 33 | * 34 | * 35 | */ 36 | public class MD5Generator implements ValueGenerator { 37 | 38 | @Override 39 | public String generateValue() throws OAuthSystemException { 40 | return generateValue(UUID.randomUUID().toString()); 41 | } 42 | 43 | @Override 44 | public String generateValue(String param) throws OAuthSystemException { 45 | try { 46 | MessageDigest algorithm = MessageDigest.getInstance("MD5"); 47 | algorithm.reset(); 48 | algorithm.update(param.getBytes()); 49 | byte[] messageDigest = algorithm.digest(); 50 | StringBuffer hexString = new StringBuffer(); 51 | for (int i = 0; i < messageDigest.length; i++) { 52 | hexString.append(Integer.toHexString(0xFF & messageDigest[i])); 53 | } 54 | 55 | return hexString.toString(); 56 | } catch (Exception e) { 57 | throw new OAuthSystemException("OAuth Token cannot be generated.", e); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/validator/TokenValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.validator; 23 | 24 | //import play.api.mvc.Request; 25 | 26 | import play.api.mvc.Request; 27 | 28 | import org.apache.amber.oauth2.common.OAuth; 29 | import org.apache.amber.oauth2.common.error.OAuthError; 30 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 31 | import org.apache.amber.oauth2.common.validators.AbstractValidator; 32 | 33 | 34 | 35 | /** 36 | * 37 | * 38 | * 39 | */ 40 | public class TokenValidator extends AbstractValidator { 41 | 42 | public TokenValidator() { 43 | requiredParams.add(OAuth.OAUTH_RESPONSE_TYPE); 44 | requiredParams.add(OAuth.OAUTH_CLIENT_ID); 45 | requiredParams.add(OAuth.OAUTH_REDIRECT_URI); 46 | } 47 | 48 | @Override 49 | public void validateMethod(Request request) throws OAuthProblemException { 50 | String method = request.method(); 51 | if (!method.equals(OAuth.HttpMethod.GET) && !method.equals(OAuth.HttpMethod.POST)) { 52 | throw OAuthProblemException.error(OAuthError.CodeResponse.INVALID_REQUEST) 53 | .description("Method not correct."); 54 | } 55 | } 56 | 57 | @Override 58 | public void validateContentType(Request request) throws OAuthProblemException { 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/utils/JSONUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.utils; 23 | 24 | import java.util.HashMap; 25 | import java.util.Iterator; 26 | import java.util.Map; 27 | 28 | import org.codehaus.jettison.json.JSONException; 29 | import org.codehaus.jettison.json.JSONObject; 30 | 31 | /** 32 | * 33 | * 34 | * 35 | */ 36 | public final class JSONUtils { 37 | 38 | public static String buildJSON(Map params) throws JSONException { 39 | JSONObject jsonObject = new JSONObject(); 40 | for (Map.Entry param : params.entrySet()) { 41 | if (param.getKey() != null && !"".equals(param.getKey()) && param.getValue() != null && !"" 42 | .equals(param.getValue())) { 43 | jsonObject.put(param.getKey(), param.getValue()); 44 | } 45 | } 46 | 47 | return jsonObject.toString(); 48 | } 49 | 50 | public static Map parseJSON(String jsonBody) throws JSONException { 51 | 52 | Map params = new HashMap(); 53 | JSONObject obj = new JSONObject(jsonBody); 54 | Iterator it = obj.keys(); 55 | while (it.hasNext()) { 56 | Object o = it.next(); 57 | if (o instanceof String) { 58 | String key = (String)o; 59 | params.put(key, obj.get(key)); 60 | } 61 | } 62 | return params; 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/token/BasicOAuthToken.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.token; 22 | 23 | /** 24 | * 25 | */ 26 | public class BasicOAuthToken implements OAuthToken { 27 | protected String accessToken; 28 | protected Long expiresIn; 29 | protected String refreshToken; 30 | protected String scope; 31 | 32 | public BasicOAuthToken() { 33 | } 34 | 35 | public BasicOAuthToken(String accessToken, Long expiresIn, String refreshToken, String scope) { 36 | this.accessToken = accessToken; 37 | this.expiresIn = expiresIn; 38 | this.refreshToken = refreshToken; 39 | this.scope = scope; 40 | } 41 | 42 | public BasicOAuthToken(String accessToken) { 43 | this(accessToken, null, null, null); 44 | } 45 | 46 | public BasicOAuthToken(String accessToken, Long expiresIn) { 47 | this(accessToken, expiresIn, null, null); 48 | } 49 | 50 | public BasicOAuthToken(String accessToken, Long expiresIn, String scope) { 51 | this(accessToken, expiresIn, null, scope); 52 | } 53 | 54 | public String getAccessToken() { 55 | return accessToken; 56 | } 57 | 58 | public Long getExpiresIn() { 59 | return expiresIn; 60 | } 61 | 62 | public String getRefreshToken() { 63 | return refreshToken; 64 | } 65 | 66 | public String getScope() { 67 | return scope; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/domain/client/BasicClientInfoBuilder.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.domain.client; 22 | 23 | /** 24 | */ 25 | public class BasicClientInfoBuilder { 26 | 27 | private BasicClientInfo info; 28 | 29 | private BasicClientInfoBuilder() { 30 | info = new BasicClientInfo(); 31 | } 32 | 33 | public static BasicClientInfoBuilder clientInfo() { 34 | return new BasicClientInfoBuilder(); 35 | } 36 | 37 | public BasicClientInfo build() { 38 | return info; 39 | } 40 | 41 | public BasicClientInfoBuilder setName(String value) { 42 | info.setName(value); 43 | return this; 44 | } 45 | 46 | public BasicClientInfoBuilder setClientId(String value) { 47 | info.setClientId(value); 48 | return this; 49 | } 50 | 51 | public BasicClientInfoBuilder setClientUrl(String value) { 52 | info.setClientUri(value); 53 | return this; 54 | } 55 | 56 | public BasicClientInfoBuilder setClientSecret(String value) { 57 | info.setClientSecret(value); 58 | return this; 59 | } 60 | 61 | public BasicClientInfoBuilder setIconUri(String value) { 62 | info.setIconUri(value); 63 | return this; 64 | } 65 | 66 | public BasicClientInfoBuilder setRedirectUri(String value) { 67 | info.setRedirectUri(value); 68 | return this; 69 | } 70 | 71 | public BasicClientInfoBuilder setDescription(String value) { 72 | info.setDescription(value); 73 | return this; 74 | } 75 | 76 | public BasicClientInfoBuilder setExpiresIn(Long value) { 77 | info.setExpiresIn(value); 78 | return this; 79 | } 80 | 81 | public BasicClientInfoBuilder setIssuedAt(Long value) { 82 | info.setIssuedAt(value); 83 | return this; 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/request/OAuthAuthzRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.request; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.as.validator.CodeValidator; 27 | import org.apache.amber.oauth2.as.validator.TokenValidator; 28 | import org.apache.amber.oauth2.common.OAuth; 29 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 30 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 31 | import org.apache.amber.oauth2.common.message.types.ResponseType; 32 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 33 | import org.apache.amber.oauth2.common.validators.OAuthValidator; 34 | 35 | /** 36 | * 37 | * 38 | * 39 | */ 40 | public class OAuthAuthzRequest extends OAuthRequest { 41 | 42 | public OAuthAuthzRequest(Request request) throws OAuthSystemException, OAuthProblemException { 43 | super(request); 44 | } 45 | 46 | @Override 47 | protected OAuthValidator initValidator() throws OAuthProblemException, OAuthSystemException { 48 | //end user authorization validators 49 | validators.put(ResponseType.CODE.toString(), CodeValidator.class); 50 | validators.put(ResponseType.TOKEN.toString(), TokenValidator.class); 51 | 52 | String requestTypeValue = getParam(OAuth.OAUTH_RESPONSE_TYPE); 53 | if (OAuthUtils.isEmpty(requestTypeValue)) { 54 | throw OAuthUtils.handleOAuthProblemException("Missing response_type parameter value"); 55 | } 56 | Class> clazz = validators.get(requestTypeValue); 57 | if (clazz == null) { 58 | throw OAuthUtils.handleOAuthProblemException("Invalid response_type parameter value"); 59 | } 60 | return OAuthUtils.instantiateClass(clazz); 61 | 62 | } 63 | 64 | public String getState() { 65 | return getParam(OAuth.OAUTH_STATE); 66 | } 67 | 68 | public String getResponseType() { 69 | return getParam(OAuth.OAUTH_RESPONSE_TYPE); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/request/OAuthTokenRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.request; 23 | 24 | import play.api.mvc.Request; 25 | 26 | import org.apache.amber.oauth2.as.validator.AuthorizationCodeValidator; 27 | import org.apache.amber.oauth2.as.validator.ClientCredentialValidator; 28 | import org.apache.amber.oauth2.as.validator.PasswordValidator; 29 | import org.apache.amber.oauth2.as.validator.RefreshTokenValidator; 30 | import org.apache.amber.oauth2.common.OAuth; 31 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 32 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 33 | import org.apache.amber.oauth2.common.message.types.GrantType; 34 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 35 | import org.apache.amber.oauth2.common.validators.OAuthValidator; 36 | 37 | 38 | /** 39 | * 40 | * 41 | * 42 | */ 43 | public class OAuthTokenRequest extends OAuthRequest { 44 | 45 | 46 | public OAuthTokenRequest(Request request) throws OAuthSystemException, OAuthProblemException { 47 | super(request); 48 | } 49 | 50 | @Override 51 | protected OAuthValidator initValidator() throws OAuthProblemException, OAuthSystemException { 52 | validators.put(GrantType.PASSWORD.toString(), PasswordValidator.class); 53 | validators.put(GrantType.CLIENT_CREDENTIALS.toString(), ClientCredentialValidator.class); 54 | validators.put(GrantType.AUTHORIZATION_CODE.toString(), AuthorizationCodeValidator.class); 55 | validators.put(GrantType.REFRESH_TOKEN.toString(), RefreshTokenValidator.class); 56 | String requestTypeValue = getParam(OAuth.OAUTH_GRANT_TYPE); 57 | if (OAuthUtils.isEmpty(requestTypeValue)) { 58 | throw OAuthUtils.handleOAuthProblemException("Missing grant_type parameter value"); 59 | } 60 | Class> clazz = validators.get(requestTypeValue); 61 | if (clazz == null) { 62 | throw OAuthUtils.handleOAuthProblemException("Invalid grant_type parameter value"); 63 | } 64 | return OAuthUtils.instantiateClass(clazz); 65 | } 66 | 67 | public String getPassword() { 68 | return getParam(OAuth.OAUTH_PASSWORD); 69 | } 70 | 71 | public String getUsername() { 72 | return getParam(OAuth.OAUTH_USERNAME); 73 | } 74 | 75 | public String getRefreshToken() { 76 | return getParam(OAuth.OAUTH_REFRESH_TOKEN); 77 | } 78 | 79 | public String getCode() { 80 | return getParam(OAuth.OAUTH_CODE); 81 | } 82 | 83 | public String getGrantType() { 84 | return getParam(OAuth.OAUTH_GRANT_TYPE); 85 | } 86 | 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/parameters/QueryParameterApplier.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.parameters; 23 | 24 | import java.util.LinkedHashMap; 25 | import java.util.Map; 26 | 27 | import org.apache.amber.oauth2.common.OAuth; 28 | import org.apache.amber.oauth2.common.message.OAuthMessage; 29 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 30 | 31 | /** 32 | * 33 | * 34 | * 35 | */ 36 | public class QueryParameterApplier implements OAuthParametersApplier { 37 | 38 | public OAuthMessage applyOAuthParameters(OAuthMessage message, Map params) { 39 | 40 | String messageUrl = message.getLocationUri(); 41 | if (messageUrl != null) { 42 | boolean containsQuestionMark = messageUrl.contains("?"); 43 | StringBuffer url = new StringBuffer(messageUrl); 44 | 45 | //apply uri fragment component if exist access_toke param 46 | Map fragmentParams = new LinkedHashMap(); 47 | if (params.containsKey(OAuth.OAUTH_ACCESS_TOKEN)) { 48 | fragmentParams.put(OAuth.OAUTH_ACCESS_TOKEN, params.remove(OAuth.OAUTH_ACCESS_TOKEN)); 49 | 50 | // State should be in the fragment too 51 | if (params.containsKey(OAuth.OAUTH_STATE)) { 52 | fragmentParams.put(OAuth.OAUTH_STATE, params.remove(OAuth.OAUTH_STATE)); 53 | } 54 | 55 | if (params.containsKey(OAuth.OAUTH_EXPIRES_IN)) { 56 | fragmentParams.put(OAuth.OAUTH_EXPIRES_IN, params.remove(OAuth.OAUTH_EXPIRES_IN)); 57 | } 58 | 59 | if (params.containsKey(OAuth.OAUTH_TOKEN_TYPE)) { 60 | fragmentParams.put(OAuth.OAUTH_TOKEN_TYPE, params.remove(OAuth.OAUTH_TOKEN_TYPE)); 61 | } 62 | 63 | } 64 | 65 | StringBuffer query = new StringBuffer(OAuthUtils.format(params.entrySet(), "UTF-8")); 66 | String fragmentQuery = ""; 67 | if (fragmentParams.containsKey(OAuth.OAUTH_ACCESS_TOKEN)) { 68 | fragmentQuery = OAuthUtils.format(fragmentParams.entrySet(), "UTF-8"); 69 | } 70 | 71 | if (!OAuthUtils.isEmpty(query.toString())) { 72 | if (containsQuestionMark) { 73 | url.append("&").append(query); 74 | } else { 75 | url.append("?").append(query); 76 | } 77 | } 78 | 79 | if (!OAuthUtils.isEmpty(fragmentQuery)) { 80 | url.append("#").append(fragmentQuery); 81 | } 82 | 83 | message.setLocationUri(url.toString()); 84 | } 85 | return message; 86 | } 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/OAuth.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common; 23 | 24 | import org.apache.amber.oauth2.common.message.types.ParameterStyle; 25 | import org.apache.amber.oauth2.common.message.types.TokenType; 26 | 27 | /** 28 | * 29 | * 30 | * 31 | */ 32 | public final class OAuth { 33 | 34 | public static final class HttpMethod { 35 | public static final String POST = "POST"; 36 | public static final String GET = "GET"; 37 | public static final String DELETE = "DELETE"; 38 | public static final String PUT = "PUT"; 39 | } 40 | 41 | public static final class HeaderType { 42 | public static final String CONTENT_TYPE = "Content-Type"; 43 | public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; 44 | public static final String AUTHORIZATION = "Authorization"; 45 | } 46 | 47 | public static final class WWWAuthHeader { 48 | public static final String REALM = "realm"; 49 | } 50 | 51 | public static final class ContentType { 52 | public static final String URL_ENCODED = "application/x-www-form-urlencoded"; 53 | public static final String JSON = "application/json"; 54 | } 55 | 56 | public static final String OAUTH_RESPONSE_TYPE = "response_type"; 57 | public static final String OAUTH_CLIENT_ID = "client_id"; 58 | public static final String OAUTH_CLIENT_SECRET = "client_secret"; 59 | public static final String OAUTH_REDIRECT_URI = "redirect_uri"; 60 | public static final String OAUTH_USERNAME = "username"; 61 | public static final String OAUTH_PASSWORD = "password"; 62 | public static final String OAUTH_ASSERTION_TYPE = "assertion_type"; 63 | public static final String OAUTH_ASSERTION = "assertion"; 64 | public static final String OAUTH_SCOPE = "scope"; 65 | public static final String OAUTH_STATE = "state"; 66 | public static final String OAUTH_GRANT_TYPE = "grant_type"; 67 | 68 | public static final String OAUTH_HEADER_NAME = "Bearer"; 69 | 70 | //Authorization response params 71 | public static final String OAUTH_CODE = "code"; 72 | public static final String OAUTH_ACCESS_TOKEN = "access_token"; 73 | public static final String OAUTH_EXPIRES_IN = "expires_in"; 74 | public static final String OAUTH_REFRESH_TOKEN = "refresh_token"; 75 | 76 | public static final String OAUTH_TOKEN_TYPE = "token_type"; 77 | 78 | public static final String OAUTH_TOKEN = "oauth_token"; 79 | 80 | public static final String OAUTH_TOKEN_DRAFT_0 = "access_token"; 81 | public static final String OAUTH_BEARER_TOKEN = "access_token"; 82 | 83 | public static final ParameterStyle DEFAULT_PARAMETER_STYLE = ParameterStyle.HEADER; 84 | public static final TokenType DEFAULT_TOKEN_TYPE = TokenType.BEARER; 85 | 86 | public static final String OAUTH_VERSION_DIFFER = "oauth_signature_method"; 87 | } 88 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/domain/credentials/BasicCredentials.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.domain.credentials; 22 | 23 | import java.lang.Long;import java.lang.Object;import java.lang.Override;import java.lang.String; /** 24 | * 25 | * 26 | * 27 | */ 28 | public class BasicCredentials implements Credentials { 29 | 30 | 31 | private String clientId; 32 | private String clientSecret; 33 | private Long issuedAt; 34 | private Long expiresIn; 35 | 36 | BasicCredentials() { 37 | 38 | } 39 | 40 | public BasicCredentials(String clientId, String clientSecret, Long issuedAt, Long expiresIn) { 41 | this.clientId = clientId; 42 | this.clientSecret = clientSecret; 43 | this.issuedAt = issuedAt; 44 | this.expiresIn = expiresIn; 45 | } 46 | 47 | @Override 48 | public String getClientId() { 49 | return clientId; 50 | } 51 | 52 | @Override 53 | public String getClientSecret() { 54 | return clientSecret; 55 | } 56 | 57 | @Override 58 | public Long getIssuedAt() { 59 | return issuedAt; 60 | } 61 | 62 | @Override 63 | public Long getExpiresIn() { 64 | return expiresIn; 65 | } 66 | 67 | public void setClientId(String clientId) { 68 | this.clientId = clientId; 69 | } 70 | 71 | public void setClientSecret(String clientSecret) { 72 | this.clientSecret = clientSecret; 73 | } 74 | 75 | public void setIssuedAt(Long issuedAt) { 76 | this.issuedAt = issuedAt; 77 | } 78 | 79 | public void setExpiresIn(Long expiresIn) { 80 | this.expiresIn = expiresIn; 81 | } 82 | 83 | @Override 84 | public boolean equals(Object o) { 85 | if (this == o) { 86 | return true; 87 | } 88 | if (o == null || getClass() != o.getClass()) { 89 | return false; 90 | } 91 | 92 | BasicCredentials that = (BasicCredentials)o; 93 | 94 | if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) { 95 | return false; 96 | } 97 | if (clientSecret != null ? !clientSecret.equals(that.clientSecret) : that.clientSecret != null) { 98 | return false; 99 | } 100 | if (expiresIn != null ? !expiresIn.equals(that.expiresIn) : that.expiresIn != null) { 101 | return false; 102 | } 103 | if (issuedAt != null ? !issuedAt.equals(that.issuedAt) : that.issuedAt != null) { 104 | return false; 105 | } 106 | 107 | return true; 108 | } 109 | 110 | @Override 111 | public int hashCode() { 112 | int result = clientId != null ? clientId.hashCode() : 0; 113 | result = 31 * result + (clientSecret != null ? clientSecret.hashCode() : 0); 114 | result = 31 * result + (issuedAt != null ? issuedAt.hashCode() : 0); 115 | result = 31 * result + (expiresIn != null ? expiresIn.hashCode() : 0); 116 | return result; 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/exception/OAuthProblemException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.exception; 23 | 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | 27 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 28 | 29 | /** 30 | * 31 | * 32 | * 33 | */ 34 | public final class OAuthProblemException extends Exception { 35 | 36 | private String error; 37 | private String description; 38 | private String uri; 39 | private String state; 40 | private String scope; 41 | private String redirectUri; 42 | 43 | private Map parameters = new HashMap(); 44 | 45 | private OAuthProblemException(String error) { 46 | this(error, ""); 47 | } 48 | 49 | private OAuthProblemException(String error, String description) { 50 | super(error + " " + description); 51 | this.description = description; 52 | this.error = error; 53 | } 54 | 55 | 56 | public static OAuthProblemException error(String error) { 57 | return new OAuthProblemException(error); 58 | } 59 | 60 | public static OAuthProblemException error(String error, String description) { 61 | return new OAuthProblemException(error, description); 62 | } 63 | 64 | public OAuthProblemException description(String description) { 65 | this.description = description; 66 | return this; 67 | } 68 | 69 | public OAuthProblemException uri(String uri) { 70 | this.uri = uri; 71 | return this; 72 | } 73 | 74 | public OAuthProblemException state(String state) { 75 | this.state = state; 76 | return this; 77 | } 78 | 79 | public OAuthProblemException scope(String scope) { 80 | this.scope = scope; 81 | return this; 82 | } 83 | 84 | public OAuthProblemException setParameter(String name, String value) { 85 | parameters.put(name, value); 86 | return this; 87 | } 88 | 89 | public String getError() { 90 | return error; 91 | } 92 | 93 | public String getDescription() { 94 | return description; 95 | } 96 | 97 | public String getUri() { 98 | return uri; 99 | } 100 | 101 | public String getState() { 102 | return state; 103 | } 104 | 105 | public String getScope() { 106 | return scope; 107 | } 108 | 109 | public String get(String name) { 110 | return parameters.get(name); 111 | } 112 | 113 | public Map getParameters() { 114 | return parameters; 115 | } 116 | 117 | public String getRedirectUri() { 118 | return redirectUri; 119 | } 120 | 121 | public void setRedirectUri(String redirectUri) { 122 | this.redirectUri = redirectUri; 123 | } 124 | 125 | @Override 126 | public String getMessage() { 127 | StringBuffer b = new StringBuffer(); 128 | if (!OAuthUtils.isEmpty(error)) { 129 | b.append(error); 130 | } 131 | 132 | if (!OAuthUtils.isEmpty(description)) { 133 | b.append(", ").append(description); 134 | } 135 | 136 | 137 | if (!OAuthUtils.isEmpty(uri)) { 138 | b.append(", ").append(uri); 139 | } 140 | 141 | 142 | if (!OAuthUtils.isEmpty(state)) { 143 | b.append(", ").append(state); 144 | } 145 | 146 | if (!OAuthUtils.isEmpty(scope)) { 147 | b.append(", ").append(scope); 148 | } 149 | 150 | return b.toString(); 151 | } 152 | 153 | @Override 154 | public String toString() { 155 | return "OAuthProblemException{" 156 | + "description='" + description + '\'' 157 | + ", error='" + error + '\'' 158 | + ", uri='" + uri + '\'' 159 | + ", state='" + state + '\'' 160 | + ", scope='" + scope + '\'' 161 | + '}'; 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/request/OAuthRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.request; 23 | 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | import java.util.Set; 27 | 28 | import play.api.mvc.Request; 29 | import scala.Option; 30 | 31 | import org.apache.amber.oauth2.common.OAuth; 32 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 33 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 34 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 35 | import org.apache.amber.oauth2.common.validators.OAuthValidator; 36 | import org.slf4j.Logger; 37 | import org.slf4j.LoggerFactory; 38 | 39 | /** 40 | * 41 | * 42 | * 43 | */ 44 | public abstract class OAuthRequest { 45 | 46 | private Logger log = LoggerFactory.getLogger(OAuthRequest.class); 47 | 48 | protected Request request; 49 | protected OAuthValidator validator; 50 | protected Map>> validators = 51 | new HashMap>>(); 52 | 53 | public OAuthRequest(Request request) throws OAuthSystemException, OAuthProblemException { 54 | this.request = request; 55 | validate(); 56 | } 57 | 58 | public OAuthRequest() { 59 | } 60 | 61 | protected void validate() throws OAuthSystemException, OAuthProblemException { 62 | try { 63 | validator = initValidator(); 64 | validator.validateMethod(request); 65 | validator.validateContentType(request); 66 | validator.validateRequiredParameters(request); 67 | } catch (OAuthProblemException e) { 68 | try { 69 | 70 | Option o = request.getQueryString(OAuth.OAUTH_REDIRECT_URI); 71 | String redirectUri = o.isEmpty()?null:o.get(); 72 | 73 | try{ 74 | if(redirectUri == null){ 75 | play.api.mvc.AnyContent a = (play.api.mvc.AnyContent)(request.body()); 76 | 77 | if (a.asFormUrlEncoded().isDefined()){ 78 | scala.collection.immutable.Map> amap = a.asFormUrlEncoded().get(); 79 | Option> ao = amap.get(OAuth.OAUTH_REDIRECT_URI); 80 | String aos = ao.get().apply(0); 81 | redirectUri = aos; 82 | } 83 | } 84 | }catch(Exception anyE){ 85 | //do nothing 86 | } 87 | 88 | 89 | if (!OAuthUtils.isEmpty(redirectUri)) { 90 | e.setRedirectUri(redirectUri); 91 | } 92 | } catch (Exception ex) { 93 | if (log.isDebugEnabled()) { 94 | log.debug("Cannot read redirect_url from the request: {}", new String[] {ex.getMessage()}); 95 | } 96 | } 97 | 98 | throw e; 99 | } 100 | 101 | } 102 | 103 | protected abstract OAuthValidator initValidator() throws OAuthProblemException, 104 | OAuthSystemException; 105 | 106 | public String getParam(String name) { 107 | Option o = request.getQueryString(name); 108 | String val = o.isEmpty()?null:o.get(); 109 | try { 110 | if (val == null) { 111 | play.api.mvc.AnyContent a = (play.api.mvc.AnyContent) (request.body()); 112 | 113 | if (a.asFormUrlEncoded().isDefined()) { 114 | scala.collection.immutable.Map> amap = a 115 | .asFormUrlEncoded().get(); 116 | Option> ao = amap.get(name); 117 | String aos = ao.get().apply(0); 118 | val = aos; 119 | } 120 | } 121 | } catch (Exception anyE) { 122 | // do nothing 123 | } 124 | 125 | return val; 126 | } 127 | 128 | public String getClientId() { 129 | return getParam(OAuth.OAUTH_CLIENT_ID); 130 | } 131 | 132 | public String getRedirectURI() { 133 | return getParam(OAuth.OAUTH_REDIRECT_URI); 134 | } 135 | 136 | public String getClientSecret() { 137 | return getParam(OAuth.OAUTH_CLIENT_SECRET); 138 | } 139 | 140 | public Set getScopes() { 141 | String scopes = getParam(OAuth.OAUTH_SCOPE); 142 | return OAuthUtils.decodeScopes(scopes); 143 | } 144 | 145 | } 146 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | oauth2play2scala 2 | ================ 3 | 4 | oauth2 auth and token server for Play 2 Scala API. Ported from Apache Amber. 5 | 6 | Why this project? 7 | ----------------- 8 | 9 | As Play2 document mentioned that impl an oauth2 server just piece of cake, so I give it a try, by found out not so easy.Because oauth2 spec is very board. 10 | 11 | Then I try to find the oauth2 impl for Play2. Basic idea is I want an impl that battle tested. 12 | 13 | 1. securesocial is not an oauth2 server 14 | 2. deadbolt is not an oauth2 server 15 | 3. scalatra/oauth2-server is not a Play2 plugin 16 | 4. raibledesigns.com/rd/entry/secure_json_services_with_play is not an oauth2 server 17 | 18 | Because the above solutions not so fit, OK, at least let me try using Apache Amber from Scala/Play2, this one works with changed HttpServletRequest to play.api.mvc.Request ! 19 | 20 | So, everyone wants an oauth2 impl in Play2 Scala API and this project can save you 9 hours! ( I used more then this to port :-) ) 21 | 22 | 23 | Here is the usage: 24 | ------------------ 25 | 26 | * Clone this repo and build the jar with _mvn compile_ and _mvn jar:jar_ 27 | * Copy the jar to Play2 project under lib/ 28 | * put this in your routes: 29 | 30 | ``` 31 | GET /oauth2/auth controllers.Application.auth() 32 | 33 | POST /oauth2/token controllers.Application.token() 34 | ``` 35 | * create the action like this (just the Apache Amber/Oltu wiki example in Scala Play 2): 36 | 37 | ``` 38 | def auth = Action { implicit request => 39 | try { 40 | //dynamically recognize an OAuth profile based on request characteristic (params, 41 | // method, content type etc.), perform validation 42 | val oauthRequest = new OAuthAuthzRequest(request) 43 | 44 | //some code .... 45 | if (oauthRequest.getClientSecret() == null) { 46 | // throw OAuthProblemException.error("404", "no such user") 47 | } 48 | 49 | //build OAuth response 50 | val resp = OAuthASResponse. 51 | authorizationResponse(request, 302). 52 | setCode("hfsfhkjsdf"). 53 | location("http://app-host:9000/authz"). 54 | buildQueryMessage(); 55 | Found(resp.getLocationUri()) 56 | 57 | //if something goes wrong 58 | } catch { 59 | case ex: OAuthProblemException => 60 | 61 | try { 62 | val resp = OAuthResponse. 63 | errorResponse(404).error(ex).location("http://app-host:9000/erro").buildQueryMessage(); 64 | Redirect(resp.getLocationUri()); 65 | 66 | } catch { 67 | case e: OAuthSystemException => 68 | e.printStackTrace(); 69 | InternalServerError(e.getMessage()); 70 | } 71 | case ex: OAuthSystemException => 72 | ex.printStackTrace() 73 | InternalServerError(ex.getMessage()) 74 | 75 | } 76 | 77 | } 78 | 79 | def token = Action { implicit request => 80 | 81 | val oauthIssuerImpl: OAuthIssuer = new OAuthIssuerImpl(new MD5Generator()); 82 | 83 | try { 84 | val oauthRequest: OAuthTokenRequest = new OAuthTokenRequest(request); 85 | 86 | val authzCode = oauthRequest.getCode(); 87 | 88 | // some code 89 | // System.out.println(authzCode); 90 | 91 | val accessToken = oauthIssuerImpl.accessToken(); 92 | val refreshToken = oauthIssuerImpl.refreshToken(); 93 | 94 | // some code 95 | System.out.println(accessToken); 96 | System.out.println(refreshToken); 97 | 98 | val r = OAuthASResponse 99 | .tokenResponse(200) //HttpServletResponse.SC_OK 100 | .setAccessToken(accessToken) 101 | .setExpiresIn("3600") 102 | .setRefreshToken(refreshToken) 103 | .buildJSONMessage(); 104 | 105 | Ok(r.getBody()); 106 | 107 | //if something goes wrong 108 | } catch { 109 | case ex: OAuthProblemException => 110 | var r: OAuthResponse = null; 111 | try { 112 | r = OAuthResponse 113 | .errorResponse(401) 114 | .error(ex) 115 | .buildJSONMessage(); 116 | } catch { 117 | case e: OAuthSystemException => 118 | e.printStackTrace(); 119 | InternalServerError(e.getMessage()); 120 | } 121 | 122 | InternalServerError(r.getBody()); 123 | 124 | case ex: OAuthSystemException => 125 | ex.printStackTrace() 126 | InternalServerError(ex.getMessage()) 127 | 128 | } 129 | 130 | } 131 | ``` 132 | 133 | * test url: 134 | 135 | http://localhost:9000/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile&state=%2Fprofile&redirect_uri=https%3A%2F%2Foauth2-login-demo.appspot.com%2Fcode&response_type=code&client_id=812741506391.apps.googleusercontent.com&approval_prompt=force 136 | 137 | http://localhost:9000/oauth2/token?code=4/P7q7W91a-oMsCeLvIaQm6bTrgtp7&client_id=8819981768.apps.googleusercontent.com&client_secret=skjdfkjsdhfkj&redirect_uri=https://oauth2-login-demo.appspot.com/code&grant_type=authorization_code 138 | 139 | * Please figure out create your KDC and userRealm yourself. Have fun ! 140 | 141 | 142 | 143 | 144 | ------------------------------------------------------------------------------------------ 145 | YourKit is kindly supporting this open source project with its full-featured Java Profiler. 146 | YourKit, LLC is the creator of innovative and intelligent tools for profiling 147 | Java and .NET applications. Take a look at YourKit's leading software products: 148 | YourKit Java Profiler and 149 | YourKit .NET Profiler. 150 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/as/response/OAuthASResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.as.response; 23 | 24 | 25 | import play.api.mvc.Request; 26 | import scala.Option; 27 | 28 | import org.apache.amber.oauth2.common.OAuth; 29 | import org.apache.amber.oauth2.common.message.OAuthResponse; 30 | 31 | /** 32 | * 33 | * 34 | * 35 | */ 36 | public class OAuthASResponse extends OAuthResponse { 37 | 38 | protected OAuthASResponse(String uri, int responseStatus) { 39 | super(uri, responseStatus); 40 | } 41 | 42 | public static OAuthAuthorizationResponseBuilder authorizationResponse(Request request,int code) { 43 | return new OAuthAuthorizationResponseBuilder(request,code); 44 | } 45 | 46 | public static OAuthTokenResponseBuilder tokenResponse(int code) { 47 | return new OAuthTokenResponseBuilder(code); 48 | } 49 | 50 | public static class OAuthAuthorizationResponseBuilder extends OAuthResponseBuilder { 51 | 52 | public OAuthAuthorizationResponseBuilder(Request request,int responseCode) { 53 | super(responseCode); 54 | //AMBER-45 55 | Option o = request.getQueryString(OAuth.OAUTH_STATE); 56 | String state= o.isEmpty()?null:o.get(); 57 | 58 | try{ 59 | if(state == null){ 60 | play.api.mvc.AnyContent a = (play.api.mvc.AnyContent)(request.body()); 61 | 62 | if (a.asFormUrlEncoded().isDefined()){ 63 | scala.collection.immutable.Map> amap = a.asFormUrlEncoded().get(); 64 | Option> ao = amap.get(OAuth.OAUTH_STATE); 65 | String aos = ao.get().apply(0); 66 | state = aos; 67 | } 68 | } 69 | }catch(Exception anyE){ 70 | //do nothing 71 | } 72 | 73 | if (state!=null){ 74 | this.setState(state); 75 | } 76 | } 77 | 78 | OAuthAuthorizationResponseBuilder setState(String state) { 79 | this.parameters.put(OAuth.OAUTH_STATE, state); 80 | return this; 81 | } 82 | 83 | public OAuthAuthorizationResponseBuilder setCode(String code) { 84 | this.parameters.put(OAuth.OAUTH_CODE, code); 85 | return this; 86 | } 87 | 88 | public OAuthAuthorizationResponseBuilder setAccessToken(String token) { 89 | this.parameters.put(OAuth.OAUTH_ACCESS_TOKEN, token); 90 | return this; 91 | } 92 | 93 | public OAuthAuthorizationResponseBuilder setExpiresIn(String expiresIn) { 94 | this.parameters.put(OAuth.OAUTH_EXPIRES_IN, expiresIn == null ? null : Long.valueOf(expiresIn)); 95 | return this; 96 | } 97 | 98 | public OAuthAuthorizationResponseBuilder setExpiresIn(Long expiresIn) { 99 | this.parameters.put(OAuth.OAUTH_EXPIRES_IN, expiresIn); 100 | return this; 101 | } 102 | 103 | public OAuthAuthorizationResponseBuilder location(String location) { 104 | this.location = location; 105 | return this; 106 | } 107 | 108 | public OAuthAuthorizationResponseBuilder setParam(String key, String value) { 109 | this.parameters.put(key, value); 110 | return this; 111 | } 112 | } 113 | 114 | 115 | public static class OAuthTokenResponseBuilder extends OAuthResponseBuilder { 116 | 117 | public OAuthTokenResponseBuilder(int responseCode) { 118 | super(responseCode); 119 | } 120 | 121 | public OAuthTokenResponseBuilder setAccessToken(String token) { 122 | this.parameters.put(OAuth.OAUTH_ACCESS_TOKEN, token); 123 | return this; 124 | } 125 | 126 | public OAuthTokenResponseBuilder setExpiresIn(String expiresIn) { 127 | this.parameters.put(OAuth.OAUTH_EXPIRES_IN, expiresIn == null ? null : Long.valueOf(expiresIn)); 128 | return this; 129 | } 130 | 131 | public OAuthTokenResponseBuilder setRefreshToken(String refreshToken) { 132 | this.parameters.put(OAuth.OAUTH_REFRESH_TOKEN, refreshToken); 133 | return this; 134 | } 135 | 136 | public OAuthTokenResponseBuilder setTokenType(String tokenType) { 137 | this.parameters.put(OAuth.OAUTH_TOKEN_TYPE, tokenType); 138 | return this; 139 | } 140 | 141 | public OAuthTokenResponseBuilder setParam(String key, String value) { 142 | this.parameters.put(key, value); 143 | return this; 144 | } 145 | 146 | public OAuthTokenResponseBuilder location(String location) { 147 | this.location = location; 148 | return this; 149 | } 150 | } 151 | 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/domain/client/BasicClientInfo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | package org.apache.amber.oauth2.common.domain.client; 22 | 23 | /** 24 | * 25 | * 26 | * 27 | */ 28 | public class BasicClientInfo implements ClientInfo { 29 | 30 | protected String name; 31 | protected String clientId; 32 | protected String clientSecret; 33 | protected String redirectUri; 34 | protected String clientUri; 35 | protected String description; 36 | protected String iconUri; 37 | protected Long issuedAt; 38 | protected Long expiresIn; 39 | 40 | public BasicClientInfo() { 41 | } 42 | 43 | @Override 44 | public String getClientId() { 45 | return clientId; 46 | } 47 | 48 | @Override 49 | public String getClientSecret() { 50 | return clientSecret; 51 | } 52 | 53 | @Override 54 | public String getRedirectUri() { 55 | return redirectUri; 56 | } 57 | 58 | @Override 59 | public String getName() { 60 | return name; 61 | } 62 | 63 | @Override 64 | public String getIconUri() { 65 | return iconUri; 66 | } 67 | 68 | @Override 69 | public String getClientUri() { 70 | return clientUri; 71 | } 72 | 73 | @Override 74 | public String getDescription() { 75 | return description; 76 | } 77 | 78 | public void setClientUri(String clientUri) { 79 | this.clientUri = clientUri; 80 | } 81 | 82 | public Long getIssuedAt() { 83 | return issuedAt; 84 | } 85 | 86 | public void setIssuedAt(Long issuedAt) { 87 | this.issuedAt = issuedAt; 88 | } 89 | 90 | public Long getExpiresIn() { 91 | return expiresIn; 92 | } 93 | 94 | public void setExpiresIn(Long expiresIn) { 95 | this.expiresIn = expiresIn; 96 | } 97 | 98 | public void setName(String name) { 99 | this.name = name; 100 | } 101 | 102 | public void setClientId(String clientId) { 103 | this.clientId = clientId; 104 | } 105 | 106 | public void setClientSecret(String clientSecret) { 107 | this.clientSecret = clientSecret; 108 | } 109 | 110 | public void setRedirectUri(String redirectUri) { 111 | this.redirectUri = redirectUri; 112 | } 113 | 114 | public void setIconUri(String iconUri) { 115 | this.iconUri = iconUri; 116 | } 117 | 118 | public void setDescription(String description) { 119 | this.description = description; 120 | } 121 | 122 | @Override 123 | public boolean equals(Object o) { 124 | if (this == o) { 125 | return true; 126 | } 127 | if (o == null || getClass() != o.getClass()) { 128 | return false; 129 | } 130 | 131 | BasicClientInfo that = (BasicClientInfo)o; 132 | 133 | if (clientId != null ? !clientId.equals(that.clientId) : that.clientId != null) { 134 | return false; 135 | } 136 | if (clientSecret != null ? !clientSecret.equals(that.clientSecret) : that.clientSecret != null) { 137 | return false; 138 | } 139 | if (clientUri != null ? !clientUri.equals(that.clientUri) : that.clientUri != null) { 140 | return false; 141 | } 142 | if (description != null ? !description.equals(that.description) : that.description != null) { 143 | return false; 144 | } 145 | if (expiresIn != null ? !expiresIn.equals(that.expiresIn) : that.expiresIn != null) { 146 | return false; 147 | } 148 | if (iconUri != null ? !iconUri.equals(that.iconUri) : that.iconUri != null) { 149 | return false; 150 | } 151 | if (issuedAt != null ? !issuedAt.equals(that.issuedAt) : that.issuedAt != null) { 152 | return false; 153 | } 154 | if (name != null ? !name.equals(that.name) : that.name != null) { 155 | return false; 156 | } 157 | if (redirectUri != null ? !redirectUri.equals(that.redirectUri) : that.redirectUri != null) { 158 | return false; 159 | } 160 | 161 | return true; 162 | } 163 | 164 | @Override 165 | public int hashCode() { 166 | int result = name != null ? name.hashCode() : 0; 167 | result = 31 * result + (clientId != null ? clientId.hashCode() : 0); 168 | result = 31 * result + (clientSecret != null ? clientSecret.hashCode() : 0); 169 | result = 31 * result + (redirectUri != null ? redirectUri.hashCode() : 0); 170 | result = 31 * result + (clientUri != null ? clientUri.hashCode() : 0); 171 | result = 31 * result + (description != null ? description.hashCode() : 0); 172 | result = 31 * result + (iconUri != null ? iconUri.hashCode() : 0); 173 | result = 31 * result + (issuedAt != null ? issuedAt.hashCode() : 0); 174 | result = 31 * result + (expiresIn != null ? expiresIn.hashCode() : 0); 175 | return result; 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/validators/AbstractValidator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.validators; 23 | 24 | import java.util.ArrayList; 25 | import java.util.HashMap; 26 | import java.util.HashSet; 27 | import java.util.List; 28 | import java.util.Map; 29 | import java.util.Set; 30 | import play.api.mvc.Request; 31 | import scala.Option; 32 | 33 | 34 | 35 | import org.apache.amber.oauth2.common.OAuth; 36 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 37 | import org.apache.amber.oauth2.common.utils.OAuthUtils; 38 | 39 | /** 40 | * 41 | * 42 | * 43 | */ 44 | //todo add client secret in header, sect 2.1 45 | public abstract class AbstractValidator implements OAuthValidator { 46 | 47 | protected List requiredParams = new ArrayList(); 48 | protected Map optionalParams = new HashMap(); 49 | protected List notAllowedParams = new ArrayList(); 50 | 51 | 52 | @Override 53 | public void validateMethod(T request) throws OAuthProblemException { 54 | if (!request.method().equals(OAuth.HttpMethod.POST)) { 55 | throw OAuthUtils.handleOAuthProblemException("Method not set to POST."); 56 | } 57 | } 58 | 59 | @Override 60 | public void validateContentType(T request) throws OAuthProblemException { 61 | 62 | 63 | Option o = request.headers().get(OAuth.HeaderType.CONTENT_TYPE); 64 | String contentType = o.isEmpty()?null:o.get(); 65 | 66 | final String expectedContentType = OAuth.ContentType.URL_ENCODED; 67 | if (!OAuthUtils.hasContentType(contentType, expectedContentType)) { 68 | throw OAuthUtils.handleBadContentTypeException(expectedContentType); 69 | } 70 | } 71 | 72 | @Override 73 | public void validateRequiredParameters(T request) throws OAuthProblemException { 74 | Set missingParameters = new HashSet(); 75 | for (String requiredParam : requiredParams) { 76 | Option o = request.getQueryString(requiredParam); 77 | String val = o.isEmpty()?null:o.get(); 78 | 79 | try { 80 | if (val == null) { 81 | play.api.mvc.AnyContent a = (play.api.mvc.AnyContent) (request 82 | .body()); 83 | 84 | if (a.asFormUrlEncoded().isDefined()) { 85 | scala.collection.immutable.Map> amap = a 86 | .asFormUrlEncoded().get(); 87 | Option> ao = amap 88 | .get(requiredParam); 89 | String aos = ao.get().apply(0); 90 | val = aos; 91 | } 92 | } 93 | } catch (Exception anyE) { 94 | // do nothing 95 | } 96 | 97 | 98 | 99 | if (OAuthUtils.isEmpty(val)) { 100 | missingParameters.add(requiredParam); 101 | } 102 | } 103 | if (!missingParameters.isEmpty()) { 104 | throw OAuthUtils.handleMissingParameters(missingParameters); 105 | } 106 | } 107 | 108 | @Override 109 | public void validateOptionalParameters(T request) throws OAuthProblemException { 110 | 111 | Set missingParameters = new HashSet(); 112 | 113 | for (Map.Entry requiredParam : optionalParams.entrySet()) { 114 | String paramName = requiredParam.getKey(); 115 | Option o = request.getQueryString(paramName); 116 | String val = o.isEmpty()?null:o.get(); 117 | if (!OAuthUtils.isEmpty(val)) { 118 | String[] dependentParams = requiredParam.getValue(); 119 | if (!OAuthUtils.hasEmptyValues(dependentParams)) { 120 | for (String dependentParam : dependentParams) { 121 | val = o.isEmpty()?null:o.get(); 122 | if (OAuthUtils.isEmpty(val)) { 123 | missingParameters.add(dependentParam); 124 | } 125 | } 126 | } 127 | } 128 | } 129 | 130 | if (!missingParameters.isEmpty()) { 131 | throw OAuthUtils.handleMissingParameters(missingParameters); 132 | } 133 | } 134 | 135 | @Override 136 | public void validateNotAllowedParameters(T request) throws OAuthProblemException { 137 | List notAllowedParameters = new ArrayList(); 138 | for (String requiredParam : notAllowedParams) { 139 | Option o = request.getQueryString(requiredParam); 140 | String val = o.isEmpty()?null:o.get(); 141 | if (!OAuthUtils.isEmpty(val)) { 142 | notAllowedParameters.add(requiredParam); 143 | } 144 | } 145 | if (!notAllowedParameters.isEmpty()) { 146 | throw OAuthUtils.handleNotAllowedParametersOAuthException(notAllowedParameters); 147 | } 148 | } 149 | 150 | @Override 151 | public void performAllValidations(T request) throws OAuthProblemException { 152 | this.validateContentType(request); 153 | this.validateMethod(request); 154 | this.validateRequiredParameters(request); 155 | this.validateOptionalParameters(request); 156 | this.validateNotAllowedParameters(request); 157 | } 158 | } 159 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/error/OAuthError.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.error; 23 | 24 | /** 25 | * 26 | * 27 | * 28 | */ 29 | public abstract class OAuthError { 30 | 31 | //error response params 32 | public static final String OAUTH_ERROR = "error"; 33 | public static final String OAUTH_ERROR_DESCRIPTION = "error_description"; 34 | public static final String OAUTH_ERROR_URI = "error_uri"; 35 | 36 | public static final class CodeResponse { 37 | /** 38 | * The request is missing a required parameter, includes an 39 | unsupported parameter value, or is otherwise malformed. 40 | */ 41 | public static final String INVALID_REQUEST = "invalid_request"; 42 | 43 | /** 44 | * The client is not authorized to request an authorization 45 | code using this method. 46 | */ 47 | public static final String UNAUTHORIZED_CLIENT = "unauthorized_client"; 48 | 49 | /** 50 | * The resource owner or authorization server denied the 51 | request. 52 | */ 53 | public static final String ACCESS_DENIED = "access_denied"; 54 | 55 | /** 56 | * The authorization server does not support obtaining an 57 | authorization code using this method. 58 | */ 59 | public static final String UNSUPPORTED_RESPONSE_TYPE = "unsupported_response_type"; 60 | 61 | /** 62 | * The requested scope is invalid, unknown, or malformed. 63 | */ 64 | public static final String INVALID_SCOPE = "invalid_scope"; 65 | 66 | /** 67 | * The authorization server encountered an unexpected 68 | condition which prevented it from fulfilling the request. 69 | */ 70 | public static final String SERVER_ERROR = "server_error"; 71 | 72 | /** 73 | * The authorization server is currently unable to handle 74 | the request due to a temporary overloading or maintenance 75 | of the server. 76 | */ 77 | public static final String TEMPORARILY_UNAVAILABLE = "temporarily_unavailable"; 78 | 79 | } 80 | 81 | public static final class TokenResponse { 82 | /** 83 | The request is missing a required parameter, includes an 84 | unsupported parameter value, repeats a parameter, 85 | includes multiple credentials, utilizes more than one 86 | mechanism for authenticating the client, or is otherwise 87 | malformed. 88 | */ 89 | public static final String INVALID_REQUEST = "invalid_request"; 90 | /** 91 | Client authentication failed (e.g. unknown client, no 92 | client authentication included, or unsupported 93 | authentication method). The authorization server MAY 94 | return an HTTP 401 (Unauthorized) status code to indicate 95 | which HTTP authentication schemes are supported. If the 96 | client attempted to authenticate via the "Authorization" 97 | request header field, the authorization server MUST 98 | respond with an HTTP 401 (Unauthorized) status code, and 99 | include the "WWW-Authenticate" response header field 100 | matching the authentication scheme used by the client. 101 | */ 102 | public static final String INVALID_CLIENT = "invalid_client"; 103 | 104 | /** 105 | The provided authorization grant (e.g. authorization 106 | code, resource owner credentials, client credentials) is 107 | invalid, expired, revoked, does not match the redirection 108 | URI used in the authorization request, or was issued to 109 | another client. 110 | */ 111 | public static final String INVALID_GRANT = "invalid_grant"; 112 | 113 | /** 114 | The authenticated client is not authorized to use this 115 | authorization grant type. 116 | */ 117 | public static final String UNAUTHORIZED_CLIENT = "unauthorized_client"; 118 | 119 | /** 120 | The authorization grant type is not supported by the 121 | authorization server. 122 | */ 123 | public static final String UNSUPPORTED_GRANT_TYPE = "unsupported_grant_type"; 124 | 125 | /** 126 | * The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner. 127 | */ 128 | public static final String INVALID_SCOPE = "invalid_scope"; 129 | } 130 | 131 | public static final class ResourceResponse { 132 | /** 133 | The request is missing a required parameter, includes an 134 | unsupported parameter value, repeats a parameter, 135 | includes multiple credentials, utilizes more than one 136 | mechanism for authenticating the client, or is otherwise 137 | malformed. 138 | */ 139 | public static final String INVALID_REQUEST = "invalid_request"; 140 | 141 | 142 | public static final String EXPIRED_TOKEN = "expired_token"; 143 | 144 | /** 145 | * The request requires higher privileges than provided by the 146 | * access token. 147 | */ 148 | public static final String INSUFFICIENT_SCOPE = "insufficient_scope"; 149 | 150 | /** 151 | * The access token provided is expired, revoked, malformed, or 152 | * invalid for other reasons. 153 | */ 154 | public static final String INVALID_TOKEN = "invalid_token"; 155 | } 156 | 157 | } 158 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/message/OAuthResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.message; 23 | 24 | import java.util.HashMap; 25 | import java.util.Map; 26 | 27 | import org.apache.amber.oauth2.common.OAuth; 28 | import org.apache.amber.oauth2.common.error.OAuthError; 29 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 30 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 31 | import org.apache.amber.oauth2.common.parameters.BodyURLEncodedParametersApplier; 32 | import org.apache.amber.oauth2.common.parameters.JSONBodyParametersApplier; 33 | import org.apache.amber.oauth2.common.parameters.OAuthParametersApplier; 34 | import org.apache.amber.oauth2.common.parameters.QueryParameterApplier; 35 | import org.apache.amber.oauth2.common.parameters.WWWAuthHeaderParametersApplier; 36 | 37 | /** 38 | * 39 | * 40 | * 41 | */ 42 | public class OAuthResponse implements OAuthMessage { 43 | 44 | protected int responseStatus; 45 | protected String uri; 46 | protected String body; 47 | 48 | protected Map headers = new HashMap(); 49 | 50 | protected OAuthResponse(String uri, int responseStatus) { 51 | this.uri = uri; 52 | this.responseStatus = responseStatus; 53 | } 54 | 55 | public static OAuthResponseBuilder status(int code) { 56 | return new OAuthResponseBuilder(code); 57 | } 58 | 59 | public static OAuthErrorResponseBuilder errorResponse(int code) { 60 | return new OAuthErrorResponseBuilder(code); 61 | } 62 | 63 | @Override 64 | public String getLocationUri() { 65 | return uri; 66 | } 67 | 68 | @Override 69 | public void setLocationUri(String uri) { 70 | this.uri = uri; 71 | } 72 | 73 | @Override 74 | public String getBody() { 75 | return body; 76 | } 77 | 78 | @Override 79 | public void setBody(String body) { 80 | this.body = body; 81 | } 82 | 83 | @Override 84 | public String getHeader(String name) { 85 | return headers.get(name); 86 | } 87 | 88 | @Override 89 | public Map getHeaders() { 90 | return headers; 91 | } 92 | 93 | @Override 94 | public void setHeaders(Map headers) { 95 | this.headers = headers; 96 | } 97 | 98 | public int getResponseStatus() { 99 | return responseStatus; 100 | } 101 | 102 | @Override 103 | public void addHeader(String name, String header) { 104 | headers.put(name, header); 105 | } 106 | 107 | public static class OAuthResponseBuilder { 108 | 109 | protected OAuthParametersApplier applier; 110 | protected Map parameters = new HashMap(); 111 | protected int responseCode; 112 | protected String location; 113 | 114 | public OAuthResponseBuilder(int responseCode) { 115 | this.responseCode = responseCode; 116 | } 117 | 118 | public OAuthResponseBuilder location(String location) { 119 | this.location = location; 120 | return this; 121 | } 122 | 123 | public OAuthResponseBuilder setScope(String value) { 124 | this.parameters.put(OAuth.OAUTH_SCOPE, value); 125 | return this; 126 | } 127 | 128 | public OAuthResponseBuilder setParam(String key, String value) { 129 | this.parameters.put(key, value); 130 | return this; 131 | } 132 | 133 | public OAuthResponse buildQueryMessage() throws OAuthSystemException { 134 | OAuthResponse msg = new OAuthResponse(location, responseCode); 135 | this.applier = new QueryParameterApplier(); 136 | return (OAuthResponse)applier.applyOAuthParameters(msg, parameters); 137 | } 138 | 139 | public OAuthResponse buildBodyMessage() throws OAuthSystemException { 140 | OAuthResponse msg = new OAuthResponse(location, responseCode); 141 | this.applier = new BodyURLEncodedParametersApplier(); 142 | return (OAuthResponse)applier.applyOAuthParameters(msg, parameters); 143 | } 144 | 145 | public OAuthResponse buildJSONMessage() throws OAuthSystemException { 146 | OAuthResponse msg = new OAuthResponse(location, responseCode); 147 | this.applier = new JSONBodyParametersApplier(); 148 | return (OAuthResponse)applier.applyOAuthParameters(msg, parameters); 149 | } 150 | 151 | public OAuthResponse buildHeaderMessage() throws OAuthSystemException { 152 | OAuthResponse msg = new OAuthResponse(location, responseCode); 153 | this.applier = new WWWAuthHeaderParametersApplier(); 154 | return (OAuthResponse)applier.applyOAuthParameters(msg, parameters); 155 | } 156 | } 157 | 158 | public static class OAuthErrorResponseBuilder extends OAuthResponseBuilder { 159 | 160 | public OAuthErrorResponseBuilder(int responseCode) { 161 | super(responseCode); 162 | } 163 | 164 | public OAuthErrorResponseBuilder error(OAuthProblemException ex) { 165 | this.parameters.put(OAuthError.OAUTH_ERROR, ex.getError()); 166 | this.parameters.put(OAuthError.OAUTH_ERROR_DESCRIPTION, ex.getDescription()); 167 | this.parameters.put(OAuthError.OAUTH_ERROR_URI, ex.getUri()); 168 | this.parameters.put(OAuth.OAUTH_STATE, ex.getState()); 169 | return this; 170 | } 171 | 172 | public OAuthErrorResponseBuilder setError(String error) { 173 | this.parameters.put(OAuthError.OAUTH_ERROR, error); 174 | return this; 175 | } 176 | 177 | public OAuthErrorResponseBuilder setErrorDescription(String desc) { 178 | this.parameters.put(OAuthError.OAUTH_ERROR_DESCRIPTION, desc); 179 | return this; 180 | } 181 | 182 | public OAuthErrorResponseBuilder setErrorUri(String state) { 183 | this.parameters.put(OAuthError.OAUTH_ERROR_URI, state); 184 | return this; 185 | } 186 | 187 | public OAuthErrorResponseBuilder setState(String state) { 188 | this.parameters.put(OAuth.OAUTH_STATE, state); 189 | return this; 190 | } 191 | 192 | public OAuthErrorResponseBuilder setRealm(String realm) { 193 | this.parameters.put(OAuth.WWWAuthHeader.REALM, realm); 194 | return this; 195 | } 196 | 197 | public OAuthErrorResponseBuilder location(String location) { 198 | this.location = location; 199 | return this; 200 | } 201 | } 202 | 203 | } 204 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, and 10 | distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by the copyright 13 | owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all other entities 16 | that control, are controlled by, or are under common control with that entity. 17 | For the purposes of this definition, "control" means (i) the power, direct or 18 | indirect, to cause the direction or management of such entity, whether by 19 | contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the 20 | outstanding shares, or (iii) beneficial ownership of such entity. 21 | 22 | "You" (or "Your") shall mean an individual or Legal Entity exercising 23 | permissions granted by this License. 24 | 25 | "Source" form shall mean the preferred form for making modifications, including 26 | but not limited to software source code, documentation source, and configuration 27 | files. 28 | 29 | "Object" form shall mean any form resulting from mechanical transformation or 30 | translation of a Source form, including but not limited to compiled object code, 31 | generated documentation, and conversions to other media types. 32 | 33 | "Work" shall mean the work of authorship, whether in Source or Object form, made 34 | available under the License, as indicated by a copyright notice that is included 35 | in or attached to the work (an example is provided in the Appendix below). 36 | 37 | "Derivative Works" shall mean any work, whether in Source or Object form, that 38 | is based on (or derived from) the Work and for which the editorial revisions, 39 | annotations, elaborations, or other modifications represent, as a whole, an 40 | original work of authorship. For the purposes of this License, Derivative Works 41 | shall not include works that remain separable from, or merely link (or bind by 42 | name) to the interfaces of, the Work and Derivative Works thereof. 43 | 44 | "Contribution" shall mean any work of authorship, including the original version 45 | of the Work and any modifications or additions to that Work or Derivative Works 46 | thereof, that is intentionally submitted to Licensor for inclusion in the Work 47 | by the copyright owner or by an individual or Legal Entity authorized to submit 48 | on behalf of the copyright owner. For the purposes of this definition, 49 | "submitted" means any form of electronic, verbal, or written communication sent 50 | to the Licensor or its representatives, including but not limited to 51 | communication on electronic mailing lists, source code control systems, and 52 | issue tracking systems that are managed by, or on behalf of, the Licensor for 53 | the purpose of discussing and improving the Work, but excluding communication 54 | that is conspicuously marked or otherwise designated in writing by the copyright 55 | owner as "Not a Contribution." 56 | 57 | "Contributor" shall mean Licensor and any individual or Legal Entity on behalf 58 | of whom a Contribution has been received by Licensor and subsequently 59 | incorporated within the Work. 60 | 61 | 2. Grant of Copyright License. 62 | 63 | Subject to the terms and conditions of this License, each Contributor hereby 64 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 65 | irrevocable copyright license to reproduce, prepare Derivative Works of, 66 | publicly display, publicly perform, sublicense, and distribute the Work and such 67 | Derivative Works in Source or Object form. 68 | 69 | 3. Grant of Patent License. 70 | 71 | Subject to the terms and conditions of this License, each Contributor hereby 72 | grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, 73 | irrevocable (except as stated in this section) patent license to make, have 74 | made, use, offer to sell, sell, import, and otherwise transfer the Work, where 75 | such license applies only to those patent claims licensable by such Contributor 76 | that are necessarily infringed by their Contribution(s) alone or by combination 77 | of their Contribution(s) with the Work to which such Contribution(s) was 78 | submitted. If You institute patent litigation against any entity (including a 79 | cross-claim or counterclaim in a lawsuit) alleging that the Work or a 80 | Contribution incorporated within the Work constitutes direct or contributory 81 | patent infringement, then any patent licenses granted to You under this License 82 | for that Work shall terminate as of the date such litigation is filed. 83 | 84 | 4. Redistribution. 85 | 86 | You may reproduce and distribute copies of the Work or Derivative Works thereof 87 | in any medium, with or without modifications, and in Source or Object form, 88 | provided that You meet the following conditions: 89 | 90 | You must give any other recipients of the Work or Derivative Works a copy of 91 | this License; and 92 | You must cause any modified files to carry prominent notices stating that You 93 | changed the files; and 94 | You must retain, in the Source form of any Derivative Works that You distribute, 95 | all copyright, patent, trademark, and attribution notices from the Source form 96 | of the Work, excluding those notices that do not pertain to any part of the 97 | Derivative Works; and 98 | If the Work includes a "NOTICE" text file as part of its distribution, then any 99 | Derivative Works that You distribute must include a readable copy of the 100 | attribution notices contained within such NOTICE file, excluding those notices 101 | that do not pertain to any part of the Derivative Works, in at least one of the 102 | following places: within a NOTICE text file distributed as part of the 103 | Derivative Works; within the Source form or documentation, if provided along 104 | with the Derivative Works; or, within a display generated by the Derivative 105 | Works, if and wherever such third-party notices normally appear. The contents of 106 | the NOTICE file are for informational purposes only and do not modify the 107 | License. You may add Your own attribution notices within Derivative Works that 108 | You distribute, alongside or as an addendum to the NOTICE text from the Work, 109 | provided that such additional attribution notices cannot be construed as 110 | modifying the License. 111 | You may add Your own copyright statement to Your modifications and may provide 112 | additional or different license terms and conditions for use, reproduction, or 113 | distribution of Your modifications, or for any such Derivative Works as a whole, 114 | provided Your use, reproduction, and distribution of the Work otherwise complies 115 | with the conditions stated in this License. 116 | 117 | 5. Submission of Contributions. 118 | 119 | Unless You explicitly state otherwise, any Contribution intentionally submitted 120 | for inclusion in the Work by You to the Licensor shall be under the terms and 121 | conditions of this License, without any additional terms or conditions. 122 | Notwithstanding the above, nothing herein shall supersede or modify the terms of 123 | any separate license agreement you may have executed with Licensor regarding 124 | such Contributions. 125 | 126 | 6. Trademarks. 127 | 128 | This License does not grant permission to use the trade names, trademarks, 129 | service marks, or product names of the Licensor, except as required for 130 | reasonable and customary use in describing the origin of the Work and 131 | reproducing the content of the NOTICE file. 132 | 133 | 7. Disclaimer of Warranty. 134 | 135 | Unless required by applicable law or agreed to in writing, Licensor provides the 136 | Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, 137 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, 138 | including, without limitation, any warranties or conditions of TITLE, 139 | NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are 140 | solely responsible for determining the appropriateness of using or 141 | redistributing the Work and assume any risks associated with Your exercise of 142 | permissions under this License. 143 | 144 | 8. Limitation of Liability. 145 | 146 | In no event and under no legal theory, whether in tort (including negligence), 147 | contract, or otherwise, unless required by applicable law (such as deliberate 148 | and grossly negligent acts) or agreed to in writing, shall any Contributor be 149 | liable to You for damages, including any direct, indirect, special, incidental, 150 | or consequential damages of any character arising as a result of this License or 151 | out of the use or inability to use the Work (including but not limited to 152 | damages for loss of goodwill, work stoppage, computer failure or malfunction, or 153 | any and all other commercial damages or losses), even if such Contributor has 154 | been advised of the possibility of such damages. 155 | 156 | 9. Accepting Warranty or Additional Liability. 157 | 158 | While redistributing the Work or Derivative Works thereof, You may choose to 159 | offer, and charge a fee for, acceptance of support, warranty, indemnity, or 160 | other liability obligations and/or rights consistent with this License. However, 161 | in accepting such obligations, You may act only on Your own behalf and on Your 162 | sole responsibility, not on behalf of any other Contributor, and only if You 163 | agree to indemnify, defend, and hold each Contributor harmless for any liability 164 | incurred by, or claims asserted against, such Contributor by reason of your 165 | accepting any such warranty or additional liability. 166 | 167 | END OF TERMS AND CONDITIONS 168 | 169 | APPENDIX: How to apply the Apache License to your work 170 | 171 | To apply the Apache License to your work, attach the following boilerplate 172 | notice, with the fields enclosed by brackets "[]" replaced with your own 173 | identifying information. (Don't include the brackets!) The text should be 174 | enclosed in the appropriate comment syntax for the file format. We also 175 | recommend that a file or class name and description of purpose be included on 176 | the same "printed page" as the copyright notice for easier identification within 177 | third-party archives. 178 | 179 | Copyright [yyyy] [name of copyright owner] 180 | 181 | Licensed under the Apache License, Version 2.0 (the "License"); 182 | you may not use this file except in compliance with the License. 183 | You may obtain a copy of the License at 184 | 185 | http://www.apache.org/licenses/LICENSE-2.0 186 | 187 | Unless required by applicable law or agreed to in writing, software 188 | distributed under the License is distributed on an "AS IS" BASIS, 189 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 190 | See the License for the specific language governing permissions and 191 | limitations under the License. 192 | -------------------------------------------------------------------------------- /src/main/java/org/apache/amber/oauth2/common/utils/OAuthUtils.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2010 Newcastle University 3 | * 4 | * http://research.ncl.ac.uk/smart/ 5 | * 6 | * Licensed to the Apache Software Foundation (ASF) under one or more 7 | * contributor license agreements. See the NOTICE file distributed with 8 | * this work for additional information regarding copyright ownership. 9 | * The ASF licenses this file to You under the Apache License, Version 2.0 10 | * (the "License"); you may not use this file except in compliance with 11 | * the License. You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, 17 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | */ 21 | 22 | package org.apache.amber.oauth2.common.utils; 23 | 24 | import java.io.IOException; 25 | import java.io.InputStream; 26 | import java.io.InputStreamReader; 27 | import java.io.Reader; 28 | import java.io.UnsupportedEncodingException; 29 | import java.lang.reflect.Constructor; 30 | import java.lang.reflect.InvocationTargetException; 31 | import java.net.URLDecoder; 32 | import java.net.URLEncoder; 33 | import java.util.Collection; 34 | import java.util.HashMap; 35 | import java.util.HashSet; 36 | import java.util.List; 37 | import java.util.Map; 38 | import java.util.Set; 39 | import java.util.StringTokenizer; 40 | import java.util.regex.Matcher; 41 | import java.util.regex.Pattern; 42 | 43 | import play.api.mvc.Request; 44 | import scala.Option; 45 | 46 | import org.apache.amber.oauth2.common.OAuth; 47 | import org.apache.amber.oauth2.common.error.OAuthError; 48 | import org.apache.amber.oauth2.common.exception.OAuthProblemException; 49 | import org.apache.amber.oauth2.common.exception.OAuthSystemException; 50 | 51 | /** 52 | * Common OAuth Utils class. 53 | *

54 | * Some methods based on the Utils class from OAuth V1.0a library available at: 55 | * http://oauth.googlecode.com/svn/code/java/core/ 56 | * 57 | * 58 | * 59 | * 60 | */ 61 | public final class OAuthUtils { 62 | 63 | private static final String ENCODING = "UTF-8"; 64 | private static final String PARAMETER_SEPARATOR = "&"; 65 | private static final String NAME_VALUE_SEPARATOR = "="; 66 | 67 | public static final String AUTH_SCHEME = OAuth.OAUTH_HEADER_NAME; 68 | 69 | private static final Pattern OAUTH_HEADER = Pattern.compile("\\s*(\\w*)\\s+(.*)"); 70 | private static final Pattern NVP = Pattern.compile("(\\S*)\\s*\\=\\s*\"([^\"]*)\""); 71 | 72 | public static final String MULTIPART = "multipart/"; 73 | 74 | private static final String DEFAULT_CONTENT_CHARSET = ENCODING; 75 | 76 | /** 77 | * Translates parameters into application/x-www-form-urlencoded String 78 | * 79 | * @param parameters parameters to encode 80 | * @param encoding The name of a supported 81 | * character 82 | * encoding. 83 | * @return Translated string 84 | */ 85 | public static String format( 86 | final Collection> parameters, 87 | final String encoding) { 88 | final StringBuilder result = new StringBuilder(); 89 | for (final Map.Entry parameter : parameters) { 90 | String value = parameter.getValue() == null? null : String.valueOf(parameter.getValue()); 91 | if (!OAuthUtils.isEmpty(parameter.getKey()) 92 | && !OAuthUtils.isEmpty(value)) { 93 | final String encodedName = encode(parameter.getKey(), encoding); 94 | final String encodedValue = value != null ? encode(value, encoding) : ""; 95 | if (result.length() > 0) { 96 | result.append(PARAMETER_SEPARATOR); 97 | } 98 | result.append(encodedName); 99 | result.append(NAME_VALUE_SEPARATOR); 100 | result.append(encodedValue); 101 | } 102 | } 103 | return result.toString(); 104 | } 105 | 106 | private static String encode(final String content, final String encoding) { 107 | try { 108 | return URLEncoder.encode(content, 109 | encoding != null ? encoding : "UTF-8"); 110 | } catch (UnsupportedEncodingException problem) { 111 | throw new IllegalArgumentException(problem); 112 | } 113 | } 114 | 115 | /** 116 | * Read data from Input Stream and save it as a String. 117 | * 118 | * @param is InputStream to be read 119 | * @return String that was read from the stream 120 | */ 121 | public static String saveStreamAsString(InputStream is) throws IOException { 122 | return toString(is, ENCODING); 123 | } 124 | 125 | /** 126 | * Get the entity content as a String, using the provided default character set 127 | * if none is found in the entity. 128 | * If defaultCharset is null, the default "UTF-8" is used. 129 | * 130 | * @param is input stream to be saved as string 131 | * @param defaultCharset character set to be applied if none found in the entity 132 | * @return the entity content as a String 133 | * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE 134 | * @throws IOException if an error occurs reading the input stream 135 | */ 136 | public static String toString( 137 | final InputStream is, final String defaultCharset) throws IOException { 138 | if (is == null) { 139 | throw new IllegalArgumentException("InputStream may not be null"); 140 | } 141 | 142 | String charset = defaultCharset; 143 | if (charset == null) { 144 | charset = DEFAULT_CONTENT_CHARSET; 145 | } 146 | Reader reader = new InputStreamReader(is, charset); 147 | StringBuilder sb = new StringBuilder(); 148 | int l; 149 | try { 150 | char[] tmp = new char[4096]; 151 | while ((l = reader.read(tmp)) != -1) { 152 | sb.append(tmp, 0, l); 153 | } 154 | } finally { 155 | reader.close(); 156 | } 157 | return sb.toString(); 158 | } 159 | 160 | /** 161 | * Creates invalid_request exception with given message 162 | * 163 | * @param message error message 164 | * @return OAuthException 165 | */ 166 | public static OAuthProblemException handleOAuthProblemException(String message) { 167 | return OAuthProblemException.error(OAuthError.TokenResponse.INVALID_REQUEST) 168 | .description(message); 169 | } 170 | 171 | /** 172 | * Creates OAuthProblemException that contains set of missing oauth parameters 173 | * 174 | * @param missingParams missing oauth parameters 175 | * @return OAuthProblemException with user friendly message about missing oauth parameters 176 | */ 177 | 178 | public static OAuthProblemException handleMissingParameters(Set missingParams) { 179 | StringBuffer sb = new StringBuffer("Missing parameters: "); 180 | if (!OAuthUtils.isEmpty(missingParams)) { 181 | for (String missingParam : missingParams) { 182 | sb.append(missingParam).append(" "); 183 | } 184 | } 185 | return handleOAuthProblemException(sb.toString().trim()); 186 | } 187 | 188 | public static OAuthProblemException handleBadContentTypeException(String expectedContentType) { 189 | StringBuilder errorMsg = new StringBuilder("Bad request content type. Expecting: ").append( 190 | expectedContentType); 191 | return handleOAuthProblemException(errorMsg.toString()); 192 | } 193 | 194 | public static OAuthProblemException handleNotAllowedParametersOAuthException( 195 | List notAllowedParams) { 196 | StringBuffer sb = new StringBuffer("Not allowed parameters: "); 197 | if (notAllowedParams != null) { 198 | for (String notAllowed : notAllowedParams) { 199 | sb.append(notAllowed).append(" "); 200 | } 201 | } 202 | return handleOAuthProblemException(sb.toString().trim()); 203 | } 204 | 205 | /** 206 | * Parse a form-urlencoded document. 207 | */ 208 | public static Map decodeForm(String form) { 209 | Map params = new HashMap(); 210 | if (!OAuthUtils.isEmpty(form)) { 211 | for (String nvp : form.split("\\&")) { 212 | int equals = nvp.indexOf('='); 213 | String name; 214 | String value; 215 | if (equals < 0) { 216 | name = decodePercent(nvp); 217 | value = null; 218 | } else { 219 | name = decodePercent(nvp.substring(0, equals)); 220 | value = decodePercent(nvp.substring(equals + 1)); 221 | } 222 | params.put(name, value); 223 | } 224 | } 225 | return params; 226 | } 227 | 228 | /** 229 | * Return true if the given Content-Type header means FORM_ENCODED. 230 | */ 231 | public static boolean isFormEncoded(String contentType) { 232 | if (contentType == null) { 233 | return false; 234 | } 235 | int semi = contentType.indexOf(";"); 236 | if (semi >= 0) { 237 | contentType = contentType.substring(0, semi); 238 | } 239 | return OAuth.ContentType.URL_ENCODED.equalsIgnoreCase(contentType.trim()); 240 | } 241 | 242 | public static String decodePercent(String s) { 243 | try { 244 | return URLDecoder.decode(s, ENCODING); 245 | // This implements http://oauth.pbwiki.com/FlexibleDecoding 246 | } catch (java.io.UnsupportedEncodingException wow) { 247 | throw new RuntimeException(wow.getMessage(), wow); 248 | } 249 | } 250 | 251 | /** 252 | * Construct a &-separated list of the given values, percentEncoded. 253 | */ 254 | public static String percentEncode(Iterable values) { 255 | StringBuilder p = new StringBuilder(); 256 | for (Object v : values) { 257 | String stringValue = toString(v); 258 | if (!isEmpty(stringValue)) { 259 | if (p.length() > 0) { 260 | p.append("&"); 261 | } 262 | p.append(OAuthUtils.percentEncode(toString(v))); 263 | } 264 | } 265 | return p.toString(); 266 | } 267 | 268 | public static String percentEncode(String s) { 269 | if (s == null) { 270 | return ""; 271 | } 272 | try { 273 | return URLEncoder.encode(s, ENCODING) 274 | // OAuth encodes some characters differently: 275 | .replace("+", "%20").replace("*", "%2A") 276 | .replace("%7E", "~"); 277 | // This could be done faster with more hand-crafted code. 278 | } catch (UnsupportedEncodingException wow) { 279 | throw new RuntimeException(wow.getMessage(), wow); 280 | } 281 | } 282 | 283 | private static final String toString(Object from) { 284 | return (from == null) ? null : from.toString(); 285 | } 286 | 287 | private static boolean isEmpty(Set missingParams) { 288 | if (missingParams == null || missingParams.size() == 0) { 289 | return true; 290 | } 291 | return false; 292 | } 293 | 294 | public static T instantiateClass(Class clazz) throws OAuthSystemException { 295 | try { 296 | return (T)clazz.newInstance(); 297 | } catch (Exception e) { 298 | throw new OAuthSystemException(e); 299 | } 300 | } 301 | 302 | public static Object instantiateClassWithParameters(Class clazz, Class[] paramsTypes, 303 | Object[] paramValues) throws OAuthSystemException { 304 | 305 | try { 306 | if (paramsTypes != null && paramValues != null) { 307 | if (!(paramsTypes.length == paramValues.length)) { 308 | throw new IllegalArgumentException("Number of types and values must be equal"); 309 | } 310 | 311 | if (paramsTypes.length == 0 && paramValues.length == 0) { 312 | return clazz.newInstance(); 313 | } 314 | Constructor clazzConstructor = clazz.getConstructor(paramsTypes); 315 | return clazzConstructor.newInstance(paramValues); 316 | } 317 | return clazz.newInstance(); 318 | 319 | } catch (NoSuchMethodException e) { 320 | throw new OAuthSystemException(e); 321 | } catch (InstantiationException e) { 322 | throw new OAuthSystemException(e); 323 | } catch (IllegalAccessException e) { 324 | throw new OAuthSystemException(e); 325 | } catch (InvocationTargetException e) { 326 | throw new OAuthSystemException(e); 327 | } 328 | 329 | } 330 | 331 | 332 | public static String getAuthHeaderField(String authHeader) { 333 | 334 | if (authHeader != null) { 335 | Matcher m = OAUTH_HEADER.matcher(authHeader); 336 | if (m.matches()) { 337 | if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) { 338 | return m.group(2); 339 | } 340 | } 341 | } 342 | return null; 343 | } 344 | 345 | public static Map decodeOAuthHeader(String header) { 346 | Map headerValues = new HashMap(); 347 | if (header != null) { 348 | Matcher m = OAUTH_HEADER.matcher(header); 349 | if (m.matches()) { 350 | if (AUTH_SCHEME.equalsIgnoreCase(m.group(1))) { 351 | for (String nvp : m.group(2).split("\\s*,\\s*")) { 352 | m = NVP.matcher(nvp); 353 | if (m.matches()) { 354 | String name = decodePercent(m.group(1)); 355 | String value = decodePercent(m.group(2)); 356 | headerValues.put(name, value); 357 | } 358 | } 359 | } 360 | } 361 | } 362 | return headerValues; 363 | } 364 | 365 | // todo: implement method to decode header form (with no challenge) 366 | 367 | /** 368 | * Construct a WWW-Authenticate or Authorization header with the OAuth challenge/credentials 369 | */ 370 | public static String encodeOAuthHeader(Map entries) { 371 | StringBuffer sb = new StringBuffer(); 372 | sb.append(OAuth.OAUTH_HEADER_NAME).append(" "); 373 | for (Map.Entry entry : entries.entrySet()) { 374 | String value = entry.getValue() == null? null: String.valueOf(entry.getValue()); 375 | if (!OAuthUtils.isEmpty(entry.getKey()) && !OAuthUtils.isEmpty(value)) { 376 | sb.append(entry.getKey()); 377 | sb.append("=\""); 378 | sb.append(value); 379 | sb.append("\","); 380 | } 381 | } 382 | 383 | return sb.substring(0, sb.length() - 1); 384 | } 385 | 386 | public static boolean isEmpty(String value) { 387 | return value == null || "".equals(value); 388 | } 389 | 390 | public static boolean hasEmptyValues(String[] array) { 391 | if (array == null || array.length == 0) { 392 | return true; 393 | } 394 | for (String s : array) { 395 | if (isEmpty(s)) { 396 | return true; 397 | } 398 | } 399 | return false; 400 | } 401 | 402 | public static String getAuthzMethod(String header) { 403 | if (header != null) { 404 | Matcher m = OAUTH_HEADER.matcher(header); 405 | if (m.matches()) { 406 | return m.group(1); 407 | 408 | } 409 | } 410 | return null; 411 | } 412 | 413 | public static Set decodeScopes(String s) { 414 | Set scopes = new HashSet(); 415 | if (!OAuthUtils.isEmpty(s)) { 416 | StringTokenizer tokenizer = new StringTokenizer(s, " "); 417 | 418 | while (tokenizer.hasMoreElements()) { 419 | scopes.add(tokenizer.nextToken()); 420 | } 421 | } 422 | return scopes; 423 | 424 | } 425 | 426 | public static String encodeScopes(Set s) { 427 | StringBuffer scopes = new StringBuffer(); 428 | for (String scope : s) { 429 | scopes.append(scope).append(" "); 430 | } 431 | return scopes.toString().trim(); 432 | 433 | } 434 | 435 | public static boolean isMultipart(Request request) { 436 | 437 | if (!"post".equals(request.method().toLowerCase())) { 438 | return false; 439 | } 440 | 441 | Option o = request.headers().get(OAuth.HeaderType.CONTENT_TYPE); 442 | String contentType = o.isEmpty()?null:o.get(); 443 | if (contentType == null) { 444 | return false; 445 | } 446 | if (contentType.toLowerCase().startsWith(MULTIPART)) { 447 | return true; 448 | } 449 | return false; 450 | } 451 | 452 | 453 | public static boolean hasContentType(String requestContentType, String requiredContentType) { 454 | if (OAuthUtils.isEmpty(requiredContentType) || OAuthUtils.isEmpty(requestContentType)) { 455 | return false; 456 | } 457 | StringTokenizer tokenizer = new StringTokenizer(requestContentType, ";"); 458 | while (tokenizer.hasMoreTokens()) { 459 | if (requiredContentType.equals(tokenizer.nextToken())) { 460 | return true; 461 | } 462 | } 463 | 464 | return false; 465 | } 466 | 467 | } 468 | 469 | 470 | --------------------------------------------------------------------------------