├── .gitignore
├── LICENSE
├── README.md
├── pom.xml
└── src
├── main
└── java
│ └── jp
│ └── eisbahn
│ └── oauth2
│ └── server
│ ├── data
│ ├── DataHandler.java
│ ├── DataHandlerFactory.java
│ └── package-info.java
│ ├── endpoint
│ ├── ProtectedResource.java
│ ├── Token.java
│ └── package-info.java
│ ├── exceptions
│ ├── OAuthError.java
│ └── package-info.java
│ ├── fetcher
│ ├── accesstoken
│ │ ├── AccessTokenFetcher.java
│ │ ├── AccessTokenFetcherProvider.java
│ │ ├── impl
│ │ │ ├── AuthHeader.java
│ │ │ ├── DefaultAccessTokenFetcherProvider.java
│ │ │ ├── RequestParameter.java
│ │ │ └── package-info.java
│ │ └── package-info.java
│ └── clientcredential
│ │ ├── ClientCredentialFetcher.java
│ │ ├── ClientCredentialFetcherImpl.java
│ │ └── package-info.java
│ ├── granttype
│ ├── GrantHandler.java
│ ├── GrantHandlerProvider.java
│ ├── impl
│ │ ├── AbstractGrantHandler.java
│ │ ├── AuthorizationCode.java
│ │ ├── ClientCredentials.java
│ │ ├── DefaultGrantHandlerProvider.java
│ │ ├── Password.java
│ │ ├── RefreshToken.java
│ │ └── package-info.java
│ └── package-info.java
│ ├── models
│ ├── AccessToken.java
│ ├── AuthInfo.java
│ ├── ClientCredential.java
│ ├── Request.java
│ └── package-info.java
│ ├── package-info.java
│ ├── spi
│ └── servlet
│ │ ├── HttpServletRequestAdapter.java
│ │ ├── ProtectedResourceFilter.java
│ │ ├── TokenServlet.java
│ │ └── package-info.java
│ └── utils
│ ├── Util.java
│ └── package-info.java
└── test
├── java
└── jp
│ └── eisbahn
│ └── oauth2
│ └── server
│ ├── data
│ └── DataHandlerTest.java
│ ├── endpoint
│ ├── ProtectedResourceResponseTest.java
│ ├── ProtectedResourceTest.java
│ ├── TokenResponseTest.java
│ └── TokenTest.java
│ ├── exceptions
│ └── OAuthErrorTest.java
│ ├── fetcher
│ ├── accesstoken
│ │ ├── AccessTokenFetcherProviderTest.java
│ │ ├── FetchResultTest.java
│ │ └── impl
│ │ │ ├── AuthHeaderTest.java
│ │ │ ├── DefaultAccessTokenFetcherProviderTest.java
│ │ │ └── RequestParameterTest.java
│ └── clientcredential
│ │ └── ClientCredentialFetcherImplTest.java
│ ├── granttype
│ ├── GrantHandlerProviderTest.java
│ ├── GrantHandlerResultTest.java
│ └── impl
│ │ ├── AuthorizationCodeTest.java
│ │ ├── ClientCredentialsTest.java
│ │ ├── DefaultGrantHandlerProviderTest.java
│ │ ├── PasswordTest.java
│ │ └── RefreshTokenTest.java
│ ├── integration
│ ├── DummyDataHandlerFactoryImpl.java
│ ├── ProtectedResourceScenarioTest.java
│ └── TokenScenarioTest.java
│ ├── models
│ ├── AccessTokenTest.java
│ ├── AuthInfoTest.java
│ └── ClientCredentialTest.java
│ ├── spi
│ └── servlet
│ │ ├── DummyDataHandlerFactoryImpl.java
│ │ ├── HttpServletRequestAdapterTest.java
│ │ ├── ProtectedResourceFilterTest.java
│ │ └── TokenServletTest.java
│ └── utils
│ └── UtilTest.java
└── resources
├── applicationContext-protectedresource-scenario.xml
└── applicationContext-token-scenario.xml
/.gitignore:
--------------------------------------------------------------------------------
1 | .project
2 | .classpath
3 | target/
4 | .DS_Store
5 | *~
6 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | oauth2-server
2 | ===================
3 |
4 | This project is an implementation for [OAuth 2.0 Specification](http://tools.ietf.org/html/rfc6749).
5 | Especially, the protocol of the server area is covered by this project.
6 |
7 | Current supported Grant types
8 | -----------------------------
9 |
10 | * Authorization Code Grant
11 | * Resource Owner Password Credentials Grant
12 | * Client Credentials Grant
13 |
14 | Current supported token types
15 | -----------------------------
16 |
17 | * Bearer(http://tools.ietf.org/html/rfc6750)
18 |
19 | How to use
20 | ----------
21 |
22 | This project is supporting some common processes to issue tokens.
23 | To use this framework, you have to provide an implementation of a
24 | DataHandler interface. The implementation class connects this framework
25 | to your databases or such storages.
26 |
27 | Also, you have to implement a DataHandlerFactory interface to
28 | create your DataHandler instance.
29 |
30 | Classes you have to implement are only above.
31 |
32 | A class to handle a request to issue an access token is Token class.
33 | But, the Token class needs some helper classes. Therefore, you have to
34 | provide their instances to the Token instance. If you're using Spring Framework
35 | DI Container, you can inject them to the Token instance.
36 | Refer the applicationContext-token-schenario.xml file.
37 |
38 | The way to use the Token class is simple. You can use it as the following snippet:
39 |
40 | ```java
41 | HttpServletRequest request = ...; // Provided by Servlet Container
42 | HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(request);
43 | Token token = ...; // Injected
44 | Token.Response response = token.handleRequest(adapter);
45 | int code = response.getCode(); // 200, 400, 401, ...
46 | String body = response.getBody(); // {"token_type":"Bearer","access_token":"...", ...}
47 | ```
48 |
49 | An code for an integration test has the request and response contents of each grant type.
50 | Refer the test code TokenScenarioTest.
51 |
52 | To check the request to access to each API endpoints, you can use
53 | ProtectedResource class. The following code snippet represents how to use its
54 | class:
55 |
56 | ```java
57 | HttpServletRequest request = ...; // Provided by Servlet Container
58 | HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(request);
59 | ProtectedResource protectedResource = ...; // Injected
60 | try {
61 | ProtectedResource.Response response = protectedResource.handleRequest(adapter);
62 | String remoteUser = response.getRemoteUser(); // User ID
63 | String clientId = response.getClientId(); // Client ID
64 | String scope = response.getScope(); // Scope string delimited by whitespace
65 | // do something
66 | } catch(OAuthError e) {
67 | int httpStatusCode = e.getCode();
68 | String errorType = e.getType();
69 | String description = e.getDescription();
70 | // do something
71 | }
72 | ```
73 |
74 | If you build your application with Servlet API, then you can use the code above
75 | in your Filter class.
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
4 | 4.0.0
5 |
6 | jp.eisbahn
7 | oauth2-server
8 | 1.0-SNAPSHOT
9 | jar
10 |
11 | ${project.groupId}.${project.artifactId}
12 | http://maven.apache.org
13 | OAuth2 Server implementation
14 |
15 |
16 | UTF-8
17 |
18 |
19 |
20 |
21 |
22 | src/main/resources
23 |
24 |
25 |
26 |
27 |
28 |
29 | org.apache.commons
30 | commons-lang3
31 | 3.1
32 |
33 |
34 | commons-codec
35 | commons-codec
36 | 1.7
37 |
38 |
39 | org.codehaus.jackson
40 | jackson-mapper-lgpl
41 | 1.9.9
42 |
43 |
44 | commons-collections
45 | commons-collections
46 | 3.2.2
47 | test
48 |
49 |
50 | commons-io
51 | commons-io
52 | 2.4
53 | test
54 |
55 |
56 | junit
57 | junit
58 | 4.11
59 | test
60 |
61 |
62 | org.easymock
63 | easymock
64 | 3.0
65 | test
66 |
67 |
68 | org.springframework
69 | spring-context
70 | 3.2.1.RELEASE
71 | test
72 |
73 |
74 | org.springframework
75 | spring-test
76 | 3.2.1.RELEASE
77 | test
78 |
79 |
80 | javax.servlet
81 | servlet-api
82 | 2.4
83 | provided
84 |
85 |
86 |
87 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/data/DataHandlerFactory.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.data;
20 |
21 | import jp.eisbahn.oauth2.server.models.Request;
22 |
23 | /**
24 | * This class provides the ability to create a concrete instance of DataHandler.
25 | * When you use the implementation class of DataHandler, you must also
26 | * implement this sub class to create the instance of your concrete
27 | * Data Handler class.
28 | *
29 | * DataHandler instance should be create per request. Therefore, the request
30 | * instance is passed to this create() method. Or, you might be able to keep
31 | * the DataHandler instance(s) in this factory instance to cache for performance.
32 | *
33 | * @author Yoichiro Tanaka
34 | *
35 | */
36 | public interface DataHandlerFactory {
37 |
38 | /**
39 | * Create a DataHandler instance and return it.
40 | * This implementation method must create the instance based on a concrete
41 | * class of the DataHandler abstract class.
42 | * @param request The request object to provide some information passed from
43 | * client.
44 | * @return The DataHandler instance.
45 | */
46 | public DataHandler create(Request request);
47 |
48 | }
49 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/data/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package defines two classes to provide an ability to store and retrieve
21 | * data between this framework and your database. To use this framework, you
22 | * must create an implementation of the DataHandler abstract class.
23 | */
24 | package jp.eisbahn.oauth2.server.data;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/endpoint/ProtectedResource.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.endpoint;
20 |
21 | import jp.eisbahn.oauth2.server.data.DataHandler;
22 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
23 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
24 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
25 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
26 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcherProvider;
27 | import jp.eisbahn.oauth2.server.models.AccessToken;
28 | import jp.eisbahn.oauth2.server.models.AuthInfo;
29 | import jp.eisbahn.oauth2.server.models.Request;
30 |
31 | /**
32 | * This class provides the function to judge whether an access to protected
33 | * resources can be applied or not.
34 | *
35 | * For instance, this instance validates an access token sent to each end points
36 | * of API. If the access token is valid, this handleResponse() method returns
37 | * the information (a client ID, an ID of a remote user and a scope value).
38 | * If the access token is invalid, OAuthError will be thrown. The exception
39 | * has the reason why the token was judged as invalid.
40 | *
41 | * @author Yoichiro Tanaka
42 | *
43 | */
44 | public class ProtectedResource {
45 |
46 | private AccessTokenFetcherProvider accessTokenFetcherProvider;
47 | private DataHandlerFactory dataHandlerFactory;
48 |
49 | /**
50 | * This method handles a request and judges whether the request can be
51 | * applied or not.
52 | *
53 | * @param request This argument value has the information of the request.
54 | * @return If the request is valid, this result has three informations (
55 | * Client ID, Scope and User ID).
56 | * @throws OAuthError If the request is invalid. This exception has a reason
57 | * why this request was judged as invalid.
58 | */
59 | public Response handleRequest(Request request) throws OAuthError {
60 | AccessTokenFetcher accessTokenFetcher = accessTokenFetcherProvider.getFetcher(request);
61 | if (accessTokenFetcher == null) {
62 | throw new OAuthError.InvalidRequest("Access token was not specified.");
63 | }
64 | FetchResult fetchResult = accessTokenFetcher.fetch(request);
65 | String token = fetchResult.getToken();
66 | DataHandler dataHandler = dataHandlerFactory.create(request);
67 | AccessToken accessToken = dataHandler.getAccessToken(token);
68 | if (accessToken == null) {
69 | throw new OAuthError.InvalidToken("Invalid access token.");
70 | }
71 | long now = System.currentTimeMillis();
72 | if (accessToken.getCreatedOn().getTime() + accessToken.getExpiresIn() * 1000 <= now) {
73 | throw new OAuthError.ExpiredToken();
74 | }
75 | AuthInfo authInfo = dataHandler.getAuthInfoById(accessToken.getAuthId());
76 | if (authInfo == null) {
77 | throw new OAuthError.InvalidToken("Invalid access token.");
78 | }
79 | if (!dataHandler.validateClientById(authInfo.getClientId())) {
80 | throw new OAuthError.InvalidToken("Invalid client.");
81 | }
82 | if (!dataHandler.validateUserById(authInfo.getUserId())) {
83 | throw new OAuthError.InvalidToken("Invalid user.");
84 | }
85 | return new Response(
86 | authInfo.getUserId(),
87 | authInfo.getClientId(),
88 | authInfo.getScope());
89 | }
90 |
91 | /**
92 | * Set a provider of fetchers to fetch an access token from a request.
93 | * @param accessTokenFetcherProvider The instance of the provider.
94 | */
95 | public void setAccessTokenFetcherProvider(AccessTokenFetcherProvider accessTokenFetcherProvider) {
96 | this.accessTokenFetcherProvider = accessTokenFetcherProvider;
97 | }
98 |
99 | /**
100 | * Set a factory of DataHandler.
101 | * @param dataHandlerFactory The instance of the factory.
102 | */
103 | public void setDataHandlerFactory(DataHandlerFactory dataHandlerFactory) {
104 | this.dataHandlerFactory = dataHandlerFactory;
105 | }
106 |
107 | /**
108 | * This class has the information about an OAuth2.0 request.
109 | *
110 | * If a check of the request is passed by {@link ProtectedResource},
111 | * this instance will be created. Each endpoint of API supported by
112 | * {@link ProtectedResource} can know the user ID, the client ID and
113 | * the authorized scopes.
114 | *
115 | * @author Yoichiro Tanaka
116 | *
117 | */
118 | public static class Response {
119 |
120 | private String remoteUser;
121 | private String clientId;
122 | private String scope;
123 |
124 | /**
125 | * This constructor initializes this instance.
126 | * @param remoteUser The remote user's ID.
127 | * @param clientId The client ID.
128 | * @param scope The scope string authorized by the remote user.
129 | */
130 | public Response(String remoteUser, String clientId, String scope) {
131 | this.remoteUser = remoteUser;
132 | this.clientId = clientId;
133 | this.scope = scope;
134 | }
135 |
136 | /**
137 | * Retrieve the remote user's ID.
138 | * @return The user ID.
139 | */
140 | public String getRemoteUser() {
141 | return remoteUser;
142 | }
143 |
144 | /**
145 | * Retrieve the client ID.
146 | * @return The client ID.
147 | */
148 | public String getClientId() {
149 | return clientId;
150 | }
151 |
152 | /**
153 | * Retrieve the scope string.
154 | * @return The scope string authorized by the remote user.
155 | */
156 | public String getScope() {
157 | return scope;
158 | }
159 |
160 | }
161 |
162 | }
163 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/endpoint/Token.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.endpoint;
20 |
21 | import jp.eisbahn.oauth2.server.data.DataHandler;
22 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
23 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
24 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcher;
25 | import jp.eisbahn.oauth2.server.granttype.GrantHandler;
26 | import jp.eisbahn.oauth2.server.granttype.GrantHandlerProvider;
27 | import jp.eisbahn.oauth2.server.granttype.GrantHandler.GrantHandlerResult;
28 | import jp.eisbahn.oauth2.server.models.ClientCredential;
29 | import jp.eisbahn.oauth2.server.models.Request;
30 | import jp.eisbahn.oauth2.server.utils.Util;
31 |
32 | import org.apache.commons.lang3.StringUtils;
33 |
34 | /**
35 | * This class provides the ability to issue a token with each grant flow.
36 | * The actual procedure to issue the token is in charge of a GrantHandler
37 | * specified by a grant_type parameter value. This handleRequest() method
38 | * fetches a client credential from the request, checks whether it is valid or
39 | * not, and delegates issuing the token to the GrantHandler instance.
40 | * As the result, a HTTP status code and a JSON string which has the token
41 | * information.
42 | *
43 | * @author Yoichiro Tanaka
44 | *
45 | */
46 | public class Token {
47 |
48 | private DataHandlerFactory dataHandlerFactory;
49 | private GrantHandlerProvider grantHandlerProvider;
50 | private ClientCredentialFetcher clientCredentialFetcher;
51 |
52 | /**
53 | * Set the DataHandlerFactory instance.
54 | * This class gets a DataHandler instance using this factory object.
55 | * The factory instance must be passed using this method before calling
56 | * the handlerRequest() method.
57 | * @param dataHandlerFactory The DataHandlerFactory instance.
58 | */
59 | public void setDataHandlerFactory(DataHandlerFactory dataHandlerFactory) {
60 | this.dataHandlerFactory = dataHandlerFactory;
61 | }
62 |
63 | /**
64 | * Set the GrantHandlerProvider instance.
65 | * This class gets a GrantHandler instance using this provider object.
66 | * The GrantHandlerProvider can determine what handler should be used
67 | * to issue the token. The provider instance must be passed using this method
68 | * before calling the handlerRequest() method.
69 | * @param grantHandlerProvider The GrantHandlerProvider instance.
70 | */
71 | public void setGrantHandlerProvider(GrantHandlerProvider grantHandlerProvider) {
72 | this.grantHandlerProvider = grantHandlerProvider;
73 | }
74 |
75 | /**
76 | * Set the ClientCredentialFetcher instance.
77 | * This class doesn't have an ability to fetch a client credential information
78 | * from the request, instead delegates this ClientCredentialFetcher instance.
79 | * The fetcher instance must be passed using this method before calling the
80 | * handlerRequest() method.
81 | * @param clientCredentialFetcher The ClientCredentialFetcher instance.
82 | */
83 | public void setClientCredentialFetcher(ClientCredentialFetcher clientCredentialFetcher) {
84 | this.clientCredentialFetcher = clientCredentialFetcher;
85 | }
86 |
87 | /**
88 | * Handle the request and issue a token.
89 | * This class is an entry point to issue the token. When this method receives
90 | * the request, then this checks the request, determines the grant type,
91 | * fetches the client credential information, and issues the token based
92 | * on the content of the request. The result is composed of the status code
93 | * and the JSON string. The status code will be 200 when the issuing token
94 | * is succeeded. If an error occurs, the code will be the 300 series value.
95 | * The JSON string has the access token, refresh token, expires_in value and
96 | * the scope string.
97 | * @param request The request instance.
98 | * @return The response object which has the status code and JSON string.
99 | */
100 | public Response handleRequest(Request request) {
101 | try {
102 | String type = request.getParameter("grant_type");
103 | if (StringUtils.isEmpty(type)) {
104 | throw new OAuthError.InvalidRequest("'grant_type' not found");
105 | }
106 | GrantHandler handler = grantHandlerProvider.getHandler(type);
107 | if (handler == null) {
108 | throw new OAuthError.UnsupportedGrantType("");
109 | }
110 | DataHandler dataHandler = dataHandlerFactory.create(request);
111 | ClientCredential clientCredential =
112 | clientCredentialFetcher.fetch(request);
113 | String clientId = clientCredential.getClientId();
114 | if (StringUtils.isEmpty(clientId)) {
115 | throw new OAuthError.InvalidRequest("'client_id' not found");
116 | }
117 | String clientSecret = clientCredential.getClientSecret();
118 | if (StringUtils.isEmpty(clientSecret)) {
119 | throw new OAuthError.InvalidRequest("'client_secret' not found");
120 | }
121 | if (!dataHandler.validateClient(clientId, clientSecret, type)) {
122 | throw new OAuthError.InvalidClient("");
123 | }
124 | GrantHandlerResult handlerResult = handler.handleRequest(dataHandler);
125 | return new Response(200, Util.toJson(handlerResult));
126 | } catch (OAuthError e) {
127 | return new Response(e.getCode(), Util.toJson(e));
128 | }
129 | }
130 |
131 | /**
132 | * This class has two properties: A status code and JSON string as the result
133 | * of issuing a token.
134 | *
135 | * @author Yoichiro Tanaka
136 | *
137 | */
138 | public static class Response {
139 |
140 | private int code;
141 | private String body;
142 |
143 | /**
144 | * Initialize this instance with arguments passed.
145 | * @param code The status code as the result of issuing a token.
146 | * @param body The JSON string which has a token information.
147 | */
148 | public Response(int code, String body) {
149 | super();
150 | this.code = code;
151 | this.body = body;
152 | }
153 |
154 | /**
155 | * Retrieve the status code value.
156 | * This status code will be 200 when the issuing token is succeeded.
157 | * If an error occurs, the code will be the 300 series value.
158 | * @return The HTTP status code value.
159 | */
160 | public int getCode() {
161 | return code;
162 | }
163 |
164 | /**
165 | * Retrieve the JSON string which has a token information.
166 | * The JSON string has the access token, refresh token, expires_in
167 | * value and the scope string. If the issuing a token failed,
168 | * this json string has the error type and description.
169 | * @return The JSON string value.
170 | */
171 | public String getBody() {
172 | return body;
173 | }
174 |
175 | }
176 |
177 | }
178 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/endpoint/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package has classes to become an endpoint. One is a class to issue a
21 | * token defined by OAuth 2.0. Other one is a class to check whether the request
22 | * for each API is valid or not. These classes are created as POJO class,
23 | * therefore, you can use them in your adopted architecture.
24 | */
25 | package jp.eisbahn.oauth2.server.endpoint;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/exceptions/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package has some exception class. Most exception represents errors
21 | * which are defined by OAuth 2.0.
22 | */
23 | package jp.eisbahn.oauth2.server.exceptions;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken;
20 |
21 | import java.util.Map;
22 |
23 | import jp.eisbahn.oauth2.server.models.Request;
24 |
25 | /**
26 | * This interface defines how to fetch an access token from a request object.
27 | * This match() method has an ability to judge whether the request has an
28 | * access token or not. The actual fetching process is executed in the fetch()
29 | * method. This fetch() method must be called when a result of the match()
30 | * method is true only.
31 | *
32 | * @author Yoichiro Tanaka
33 | *
34 | */
35 | public interface AccessTokenFetcher {
36 |
37 | /**
38 | * Judge whether a request has an access token or not.
39 | * @param request The request object.
40 | * @return If the request has an access token, return true.
41 | */
42 | public boolean match(Request request);
43 |
44 | /**
45 | * Retrieve an access token from a request object.
46 | * This method must be called when a result of the match() method
47 | * is true only.
48 | * @param request The request object.
49 | * @return The fetched access token.
50 | */
51 | public FetchResult fetch(Request request);
52 |
53 | /**
54 | * This is a holder class to has an access token with the AccessTokenFetcher
55 | * instance.
56 | *
57 | * @author Yoichiro Tanaka
58 | *
59 | */
60 | public static class FetchResult {
61 |
62 | private String token;
63 | private Map params;
64 |
65 | /**
66 | * This constructor initializes like both parameters become a null value.
67 | */
68 | public FetchResult() {
69 | this(null, null);
70 | }
71 |
72 | /**
73 | * This constructor initializes with the specified argument values.
74 | * @param token The access token string.
75 | * @param params Other parameters.
76 | */
77 | public FetchResult(String token, Map params) {
78 | super();
79 | this.token = token;
80 | this.params = params;
81 | }
82 |
83 | /**
84 | * Set the access token.
85 | * @param token The token string.
86 | */
87 | public void setToken(String token) {
88 | this.token = token;
89 | }
90 |
91 | /**
92 | * Retrieve the access token.
93 | * @return The token string.
94 | */
95 | public String getToken() {
96 | return token;
97 | }
98 |
99 | /**
100 | * Set other parameters.
101 | * @param params The other parameter map object.
102 | */
103 | public void setParams(Map params) {
104 | this.params = params;
105 | }
106 |
107 | /**
108 | * Retrieve the other parameters.
109 | * @return The other parameter map object.
110 | */
111 | public Map getParams() {
112 | return params;
113 | }
114 |
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcherProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken;
20 |
21 | import jp.eisbahn.oauth2.server.models.Request;
22 |
23 | /**
24 | * This class provides AccessTokenFetcher implementation classes supported.
25 | * For instance, the request is passed, then this class checks whether
26 | * a fetcher class which can fetch an access token from the request exists or
27 | * not with a match() method of each implementation class.
28 | *
29 | * @author Yoichiro Tanaka
30 | *
31 | */
32 | public class AccessTokenFetcherProvider {
33 |
34 | private AccessTokenFetcher[] fetchers;
35 |
36 | /**
37 | * Find a fetcher instance which can fetch an access token from the request
38 | * passed as an argument value and return it. The match() method of each
39 | * implementation class is used to confirm whether the access token can be
40 | * fetched or not.
41 | *
42 | * @param request The request object.
43 | * @return The fetcher instance which can fetch an access token from
44 | * the request. If not found, return null.
45 | */
46 | public AccessTokenFetcher getFetcher(Request request) {
47 | for (AccessTokenFetcher fetcher : fetchers) {
48 | if (fetcher.match(request)) {
49 | return fetcher;
50 | }
51 | }
52 | return null;
53 | }
54 |
55 | /**
56 | * Set AccessTokenFetcher implementation instances you support.
57 | * @param fetchers The implementation instance of the AccessTokenFetcher
58 | * class.
59 | */
60 | public void setAccessTokenFetchers(AccessTokenFetcher[] fetchers) {
61 | this.fetchers = fetchers;
62 | }
63 |
64 | /**
65 | * Retrieve the supported AccessTokenFetcher instances.
66 | * @return The fetcher instances.
67 | */
68 | public AccessTokenFetcher[] getAccessTokenFetchers() {
69 | return fetchers;
70 | }
71 |
72 | }
73 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/AuthHeader.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
20 |
21 | import java.util.HashMap;
22 | import java.util.Map;
23 | import java.util.regex.Matcher;
24 | import java.util.regex.Pattern;
25 |
26 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 | import jp.eisbahn.oauth2.server.utils.Util;
29 |
30 | /**
31 | * This class fetches an access token from Authorization Request header.
32 | * Actually, the access token is clipped from the header string with a regular
33 | * expression.
34 | *
35 | * @author Yoichiro Tanaka
36 | *
37 | */
38 | public class AuthHeader implements AccessTokenFetcher {
39 |
40 | private static final String HEADER_AUTHORIZATION = "Authorization";
41 | private static final Pattern REGEXP_AUTHORIZATION =
42 | Pattern.compile("^\\s*(OAuth|Bearer)\\s+([^\\s\\,]*)");
43 | private static final Pattern REGEXP_TRIM = Pattern.compile("^\\s*,\\s*");
44 | private static final Pattern REGEXP_DIV_COMMA = Pattern.compile(",\\s*");
45 |
46 | /**
47 | * Return whether an access token is included in the Authorization
48 | * request header.
49 | *
50 | * @param request The request object.
51 | * @return If the header value has an access token, this result is true.
52 | */
53 | @Override
54 | public boolean match(Request request) {
55 | String header = request.getHeader(HEADER_AUTHORIZATION);
56 | return (header != null)
57 | && (Pattern.matches("^\\s*(OAuth|Bearer)(.*)$", header));
58 | }
59 |
60 | /**
61 | * Fetch an access token from an Authorization request header and return it.
62 | * This method must be called when a result of the match() method is true
63 | * only.
64 | *
65 | * @param request The request object.
66 | * @return the fetched access token.
67 | */
68 | @Override
69 | public FetchResult fetch(Request request) {
70 | String header = request.getHeader(HEADER_AUTHORIZATION);
71 | Matcher matcher = REGEXP_AUTHORIZATION.matcher(header);
72 | if (!matcher.find()) {
73 | throw new IllegalStateException(
74 | "parse() method was called when match() result was false.");
75 | }
76 | String token = matcher.group(2);
77 | Map params = new HashMap();
78 | int end = matcher.end();
79 | if (header.length() != end) {
80 | header = header.substring(end);
81 | header = REGEXP_TRIM.matcher(header).replaceFirst("");
82 | String[] expList = REGEXP_DIV_COMMA.split(header);
83 | for (String exp : expList) {
84 | String[] keyValue = exp.split("=", 2);
85 | String value = keyValue[1].replaceFirst("^\"", "");
86 | value = value.replaceFirst("\"$", "");
87 | params.put(keyValue[0], Util.decodeParam(value));
88 | }
89 | }
90 | return new FetchResult(token, params);
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/DefaultAccessTokenFetcherProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
20 |
21 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
22 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcherProvider;
23 |
24 | /**
25 | * This class is the implementation class of the AccessTokenFetcherProvider.
26 | * This implementation provides two instances to fetch an access token
27 | * "AuthHeader" and "RequestParameter".
28 | *
29 | * @author Yoichiro Tanaka
30 | *
31 | */
32 | public class DefaultAccessTokenFetcherProvider extends AccessTokenFetcherProvider {
33 |
34 | /**
35 | * This constructor creates instances of AuthHeader and RequestParameter
36 | * implementation classes.
37 | */
38 | public DefaultAccessTokenFetcherProvider() {
39 | super();
40 | setAccessTokenFetchers(new AccessTokenFetcher[] {
41 | new AuthHeader(),
42 | new RequestParameter()
43 | });
44 | }
45 |
46 | }
47 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
20 |
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | import org.apache.commons.lang3.StringUtils;
25 |
26 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 |
29 | /**
30 | * This class fetches an access token from request parameters.
31 | * Actually, the access token is picked up from an "oauth_token" or "access_token"
32 | * parameter's value.
33 | *
34 | * @author Yoichiro Tanaka
35 | *
36 | */
37 | public class RequestParameter implements AccessTokenFetcher {
38 |
39 | /**
40 | * Return whether an access token is included in the request parameter's
41 | * values. Actually, this method confirms whether the "oauth_token" or
42 | * "access_token" request parameter exists or not.
43 | *
44 | * @param request The request object.
45 | * @return If either parameter exists, this result is true.
46 | */
47 | @Override
48 | public boolean match(Request request) {
49 | String oauthToken = request.getParameter("oauth_token");
50 | String accessToken = request.getParameter("access_token");
51 | return StringUtils.isNotEmpty(accessToken)
52 | || StringUtils.isNotEmpty(oauthToken);
53 | }
54 |
55 | /**
56 | * Fetch an access token from a request parameter and return it.
57 | * This method must be called when a result of the match() method is true
58 | * only.
59 | *
60 | * @param request The request object.
61 | * @return the fetched access token.
62 | */
63 | @Override
64 | public FetchResult fetch(Request request) {
65 | Map params = new HashMap();
66 | Map parameterMap = request.getParameterMap();
67 | params.putAll(parameterMap);
68 | String token = params.get("access_token");
69 | params.remove("access_token");
70 | if (StringUtils.isNotEmpty(params.get("oauth_token"))) {
71 | token = params.get("oauth_token");
72 | params.remove("oauth_token");
73 | }
74 | return new FetchResult(token, params);
75 | }
76 |
77 | }
78 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package has some implementation classes of the AccessTokenFetcher
21 | * interface.
22 | */
23 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package defines how to fetch an access token from a request.
21 | */
22 | package jp.eisbahn.oauth2.server.fetcher.accesstoken;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcher.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.clientcredential;
20 |
21 | import jp.eisbahn.oauth2.server.models.ClientCredential;
22 | import jp.eisbahn.oauth2.server.models.Request;
23 |
24 | /**
25 | * This interface defines a method to fetch a client credential information
26 | * from a request.
27 | *
28 | * @author Yoichiro Tanaka
29 | *
30 | */
31 | public interface ClientCredentialFetcher {
32 |
33 | /**
34 | * Fetch a client credential from a request passed as the argument and
35 | * return it.
36 | * @param request The request object.
37 | * @return The fetched client credential information.
38 | */
39 | public ClientCredential fetch(Request request);
40 |
41 | }
42 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.clientcredential;
20 |
21 | import java.util.regex.Matcher;
22 | import java.util.regex.Pattern;
23 |
24 | import jp.eisbahn.oauth2.server.models.ClientCredential;
25 | import jp.eisbahn.oauth2.server.models.Request;
26 | import jp.eisbahn.oauth2.server.utils.Util;
27 |
28 | /**
29 | * This implementation provides a client credential information
30 | * from a request header or request parameters
31 | *
32 | * @author Yoichiro Tanaka
33 | *
34 | */
35 | public class ClientCredentialFetcherImpl implements ClientCredentialFetcher {
36 |
37 | private static final Pattern REGEXP_BASIC =
38 | Pattern.compile("^\\s*(Basic)\\s+(.*)$");
39 |
40 | /**
41 | * Fetch a client credential sent from the client as a request header
42 | * or request parameters. First, this method attempts to fetch it from
43 | * the Authorization request header. For instance, it is expected as the
44 | * format "Basic [Base64 encoded]". The encoded value actually has two
45 | * parameter "Client ID" and "Client secret" delimited by ":" character.
46 | * If it does not exist, this method attempt to fetch it from request
47 | * parameter named "client_id" and "client_secret".
48 | *
49 | * @param request The request object.
50 | * @return The client credential information.
51 | */
52 | @Override
53 | public ClientCredential fetch(Request request) {
54 | String header = request.getHeader("Authorization");
55 | if (header != null) {
56 | Matcher matcher = REGEXP_BASIC.matcher(header);
57 | if (matcher.find()) {
58 | String decoded = Util.decodeBase64(matcher.group(2));
59 | if (decoded.indexOf(':') > 0) {
60 | String[] credential = decoded.split(":", 2);
61 | return new ClientCredential(credential[0], credential[1]);
62 | }
63 | }
64 | }
65 | return new ClientCredential(
66 | request.getParameter("client_id"),
67 | request.getParameter("client_secret"));
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package has an interface which defines how to fetch a client credential
21 | * from a request and its implementation class.
22 | */
23 | package jp.eisbahn.oauth2.server.fetcher.clientcredential;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/GrantHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype;
20 |
21 | import org.codehaus.jackson.annotate.JsonProperty;
22 | import org.codehaus.jackson.annotate.JsonPropertyOrder;
23 | import org.codehaus.jackson.map.annotate.JsonSerialize;
24 | import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;
25 |
26 | import jp.eisbahn.oauth2.server.data.DataHandler;
27 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
28 |
29 | /**
30 | * This interface defines how to issue a token for each grant type.
31 | * The issued token is passed to the client as the GrantHandlerResult instance.
32 | *
33 | * @author Yoichiro Tanaka
34 | *
35 | */
36 | public interface GrantHandler {
37 |
38 | /**
39 | * Handle a request to issue a token and issue it.
40 | * This method should be implemented for each grant type of OAuth2
41 | * specification. For instance, the procedure uses a DataHandler instance
42 | * to access to your database. Each grant type has some validation rule,
43 | * if the validation is failed, this method will throw an OAuthError
44 | * exception.
45 | *
46 | * @param dataHandler The DataHandler instance to access to your database.
47 | * @return The issued token information as the result of calling this method.
48 | * @throws OAuthError If the validation was failed.
49 | */
50 | public GrantHandlerResult handleRequest(DataHandler dataHandler) throws OAuthError;
51 |
52 | /**
53 | * This class has the information about issued token.
54 | *
55 | * @author Yoichiro Tanaka
56 | *
57 | */
58 | @JsonSerialize(include = Inclusion.NON_NULL)
59 | @JsonPropertyOrder({"token_type",
60 | "access_token",
61 | "refresh_token",
62 | "expires_in",
63 | "scope"})
64 | public static class GrantHandlerResult {
65 |
66 | @JsonProperty("token_type")
67 | private String tokenType;
68 | @JsonProperty("access_token")
69 | private String accessToken;
70 | @JsonProperty("expires_in")
71 | private Long expiresIn;
72 | @JsonProperty("refresh_token")
73 | private String refreshToken;
74 | private String scope;
75 |
76 | /**
77 | * Initialize this instance with these arguments.
78 | * These parameters is required.
79 | *
80 | * @param tokenType The token type string.
81 | * @param accessToken The access token string.
82 | */
83 | public GrantHandlerResult(String tokenType, String accessToken) {
84 | super();
85 | this.tokenType = tokenType;
86 | this.accessToken = accessToken;
87 | }
88 |
89 | /**
90 | * Retrieve the token type.
91 | * @return The issued token's type.
92 | */
93 | public String getTokenType() {
94 | return tokenType;
95 | }
96 |
97 | /**
98 | * Retrieve the access token.
99 | * @return The issued access token string.
100 | */
101 | public String getAccessToken() {
102 | return accessToken;
103 | }
104 |
105 | /**
106 | * Set the expires_in parameter's value.
107 | * An unit of this value is second.
108 | * @param expiresIn The expires_in value.
109 | */
110 | public void setExpiresIn(Long expiresIn) {
111 | this.expiresIn = expiresIn;
112 | }
113 |
114 | /**
115 | * Retrieve the expires_in value.
116 | * @return The expires_in value (this unit is second).
117 | */
118 | public Long getExpiresIn() {
119 | return expiresIn;
120 | }
121 |
122 | /**
123 | * Set the refresh token.
124 | * If a grant type which issues the refresh token is specified,
125 | * the issued refresh token is passed to the client via this method.
126 | * @param refreshToken The refresh token string.
127 | */
128 | public void setRefreshToken(String refreshToken) {
129 | this.refreshToken = refreshToken;
130 | }
131 |
132 | /**
133 | * Retrieve the refresh token.
134 | * @return The issued refresh token string.
135 | */
136 | public String getRefreshToken() {
137 | return refreshToken;
138 | }
139 |
140 | /**
141 | * Set the scope string.
142 | * This scope string specified by the client is passed to
143 | * this method untouched.
144 | * @param scope The scope string.
145 | */
146 | public void setScope(String scope) {
147 | this.scope = scope;
148 | }
149 |
150 | /**
151 | * Retrieve the scope string.
152 | * @return The scope string.
153 | */
154 | public String getScope() {
155 | return scope;
156 | }
157 |
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/GrantHandlerProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype;
20 |
21 | import java.util.Map;
22 |
23 | /**
24 | * This class provides a grant handler instance by specified grant type name.
25 | *
26 | * @author Yoichiro Tanaka
27 | *
28 | */
29 | public class GrantHandlerProvider {
30 |
31 | private Map handlers;
32 |
33 | /**
34 | * Retrieve the grant handler instance for the specified grant type.
35 | *
36 | * @param type The grant type string.
37 | * @return The grant handler instance. The null is returned when the target
38 | * grant handler is not found for the specified grant type.
39 | */
40 | public GrantHandler getHandler(String type) {
41 | return handlers.get(type);
42 | }
43 |
44 | /**
45 | * Retrieve the map instance which has grant handlers
46 | * This method is provided for an unit test.
47 | * @return The map object which has grant handlers.
48 | */
49 | public Map getHandlers() {
50 | return handlers;
51 | }
52 |
53 | /**
54 | * Set the map instance which has grant handlers.
55 | * The key means a grant type. The value is each grant handler instance.
56 | * @param handlers The map object which has grant handlers.
57 | */
58 | public void setGrantHandlers(Map handlers) {
59 | this.handlers = handlers;
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/AbstractGrantHandler.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import org.apache.commons.lang3.StringUtils;
22 |
23 | import jp.eisbahn.oauth2.server.data.DataHandler;
24 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
25 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcher;
26 | import jp.eisbahn.oauth2.server.granttype.GrantHandler;
27 | import jp.eisbahn.oauth2.server.models.AccessToken;
28 | import jp.eisbahn.oauth2.server.models.AuthInfo;
29 | import jp.eisbahn.oauth2.server.models.Request;
30 |
31 | /**
32 | * This abstract class provides some common functions for this sub classes.
33 | *
34 | * @author Yoichiro Tanaka
35 | *
36 | */
37 | public abstract class AbstractGrantHandler implements GrantHandler {
38 |
39 | private ClientCredentialFetcher clientCredentialFetcher;
40 |
41 | /**
42 | * Set the client credential fetcher instance.
43 | * @param clientCredentialFetcher The fetcher object to fetch a client
44 | * credential.
45 | */
46 | public void setClientCredentialFetcher(ClientCredentialFetcher clientCredentialFetcher) {
47 | this.clientCredentialFetcher = clientCredentialFetcher;
48 | }
49 |
50 | /**
51 | * Retrieve the client credential fetcher instance.
52 | * @return The fetcher object to fetch a client credential.
53 | */
54 | protected ClientCredentialFetcher getClientCredentialFetcher() {
55 | return clientCredentialFetcher;
56 | }
57 |
58 | /**
59 | * Issue an access token and relating information and return it.
60 | * Actually, issuing the access token is delegated to the specified data
61 | * handler. If the issued result has a expires_in, refresh token and/or
62 | * scope string, each parameter is included to the result of this method.
63 | * @param dataHandler The data handler instance to access to your database
64 | * and issue an access token.
65 | * @param authInfo The authorization information created in advance.
66 | * @return The result object which has an access token and etc.
67 | */
68 | protected GrantHandlerResult issueAccessToken(DataHandler dataHandler,
69 | AuthInfo authInfo) {
70 | AccessToken accessToken = dataHandler.createOrUpdateAccessToken(authInfo);
71 | GrantHandlerResult result =
72 | new GrantHandlerResult("Bearer", accessToken.getToken());
73 | if (accessToken.getExpiresIn() > 0) {
74 | result.setExpiresIn(accessToken.getExpiresIn());
75 | }
76 | if (StringUtils.isNotEmpty(authInfo.getRefreshToken())) {
77 | result.setRefreshToken(authInfo.getRefreshToken());
78 | }
79 | if (StringUtils.isNotEmpty(authInfo.getScope())) {
80 | result.setScope(authInfo.getScope());
81 | }
82 | return result;
83 | }
84 |
85 | /**
86 | * Retrieve the parameter value against the parameter name.
87 | *
88 | * @param request The request object which has each parameters.
89 | * @param name The parameter name which you want to retrieve.
90 | * @return The parameter value. This never be null.
91 | * @throws OAuthError.InvalidRequest If the parameter is not found or is
92 | * empty string.
93 | */
94 | protected String getParameter(Request request, String name)
95 | throws OAuthError.InvalidRequest {
96 | String value = request.getParameter(name);
97 | if (StringUtils.isEmpty(value)) {
98 | throw new OAuthError.InvalidRequest("'" + name + "' not found");
99 | }
100 | return value;
101 | }
102 |
103 | }
104 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/AuthorizationCode.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import org.apache.commons.lang3.StringUtils;
22 |
23 | import jp.eisbahn.oauth2.server.data.DataHandler;
24 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
25 | import jp.eisbahn.oauth2.server.models.AuthInfo;
26 | import jp.eisbahn.oauth2.server.models.ClientCredential;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 |
29 | /**
30 | * This class is an implementation for processing the Authorization Code Grant
31 | * flow of OAuth2.0.
32 | *
33 | * @author Yoichiro Tanaka
34 | *
35 | */
36 | public class AuthorizationCode extends AbstractGrantHandler {
37 |
38 | /*
39 | * (non-Javadoc)
40 | * @see jp.eisbahn.oauth2.server.granttype.GrantHandler#handleRequest(jp.eisbahn.oauth2.server.data.DataHandler)
41 | */
42 | @Override
43 | public GrantHandlerResult handleRequest(DataHandler dataHandler) throws OAuthError {
44 | Request request = dataHandler.getRequest();
45 |
46 | ClientCredential clientCredential = getClientCredentialFetcher().fetch(request);
47 | String clientId = clientCredential.getClientId();
48 |
49 | String code = getParameter(request, "code");
50 | String redirectUri = getParameter(request, "redirect_uri");
51 |
52 | AuthInfo authInfo = dataHandler.getAuthInfoByCode(code);
53 | if (authInfo == null) {
54 | throw new OAuthError.InvalidGrant("");
55 | }
56 | if (!authInfo.getClientId().equals(clientId)) {
57 | throw new OAuthError.InvalidClient("");
58 | }
59 | if (!(StringUtils.isNotEmpty(authInfo.getRedirectUri())
60 | && authInfo.getRedirectUri().equals(redirectUri))) {
61 | throw new OAuthError.RedirectUriMismatch("");
62 | }
63 |
64 | return issueAccessToken(dataHandler, authInfo);
65 | }
66 |
67 | }
68 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/ClientCredentials.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import org.apache.commons.lang3.StringUtils;
22 |
23 | import jp.eisbahn.oauth2.server.data.DataHandler;
24 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
25 | import jp.eisbahn.oauth2.server.models.AuthInfo;
26 | import jp.eisbahn.oauth2.server.models.ClientCredential;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 |
29 | /**
30 | * This class is an implementation for processing the Client Credentials Grant
31 | * flow of OAuth2.0.
32 | *
33 | * @author Yoichiro Tanaka
34 | *
35 | */
36 | public class ClientCredentials extends AbstractGrantHandler {
37 |
38 | /*
39 | * (non-Javadoc)
40 | * @see jp.eisbahn.oauth2.server.granttype.GrantHandler#handleRequest(jp.eisbahn.oauth2.server.data.DataHandler)
41 | */
42 | @Override
43 | public GrantHandlerResult handleRequest(DataHandler dataHandler) throws OAuthError {
44 | Request request = dataHandler.getRequest();
45 |
46 | ClientCredential clientCredential = getClientCredentialFetcher().fetch(request);
47 | String clientId = clientCredential.getClientId();
48 | String clientSecret = clientCredential.getClientSecret();
49 |
50 | String userId = dataHandler.getClientUserId(clientId, clientSecret);
51 | if (StringUtils.isEmpty(userId)) {
52 | throw new OAuthError.InvalidClient("");
53 | }
54 |
55 | String scope = request.getParameter("scope");
56 |
57 | AuthInfo authInfo =
58 | dataHandler.createOrUpdateAuthInfo(clientId, userId, scope);
59 | if (authInfo == null) {
60 | throw new OAuthError.InvalidGrant("");
61 | }
62 |
63 | return issueAccessToken(dataHandler, authInfo);
64 | }
65 |
66 | }
67 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/DefaultGrantHandlerProvider.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import java.util.HashMap;
22 | import java.util.Map;
23 |
24 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcher;
25 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
26 | import jp.eisbahn.oauth2.server.granttype.GrantHandler;
27 | import jp.eisbahn.oauth2.server.granttype.GrantHandlerProvider;
28 |
29 | /**
30 | * This class is a default implementation for the GrantHandlerProvider interface.
31 | * All grant types are supported in this class. If you don't support all types,
32 | * you should not use this implementation, then you should provide your
33 | * implementation to support only types you want to use.
34 | *
35 | * @author Yoichiro Tanaka
36 | *
37 | */
38 | public class DefaultGrantHandlerProvider extends GrantHandlerProvider {
39 |
40 | /**
41 | * Initialize this instance. All grant handlers are set.
42 | */
43 | public DefaultGrantHandlerProvider() {
44 | super();
45 | ClientCredentialFetcher fetcher = new ClientCredentialFetcherImpl();
46 | Map handlers = new HashMap();
47 | AuthorizationCode authorizationCode = new AuthorizationCode();
48 | authorizationCode.setClientCredentialFetcher(fetcher);
49 | handlers.put("authorization_code", authorizationCode);
50 | RefreshToken refreshToken = new RefreshToken();
51 | refreshToken.setClientCredentialFetcher(fetcher);
52 | handlers.put("refresh_token", refreshToken);
53 | ClientCredentials clientCredentials = new ClientCredentials();
54 | clientCredentials.setClientCredentialFetcher(fetcher);
55 | handlers.put("client_credentials", clientCredentials);
56 | Password password = new Password();
57 | password.setClientCredentialFetcher(fetcher);
58 | handlers.put("password", password);
59 | setGrantHandlers(handlers);
60 | }
61 |
62 | }
63 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/Password.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import org.apache.commons.lang3.StringUtils;
22 |
23 | import jp.eisbahn.oauth2.server.data.DataHandler;
24 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
25 | import jp.eisbahn.oauth2.server.models.AuthInfo;
26 | import jp.eisbahn.oauth2.server.models.ClientCredential;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 |
29 | /**
30 | * This class is an implementation for processing the Resource Owner Password
31 | * Credentials Grant flow of OAuth2.0.
32 | *
33 | * @author Yoichiro Tanaka
34 | *
35 | */
36 | public class Password extends AbstractGrantHandler {
37 |
38 | /*
39 | * (non-Javadoc)
40 | * @see jp.eisbahn.oauth2.server.granttype.GrantHandler#handleRequest(jp.eisbahn.oauth2.server.data.DataHandler)
41 | */
42 | @Override
43 | public GrantHandlerResult handleRequest(DataHandler dataHandler) throws OAuthError {
44 | Request request = dataHandler.getRequest();
45 |
46 | ClientCredential clientCredential = getClientCredentialFetcher().fetch(request);
47 | String clientId = clientCredential.getClientId();
48 |
49 | String username = getParameter(request, "username");
50 | String password = getParameter(request, "password");
51 |
52 | String userId = dataHandler.getUserId(username, password);
53 | if (StringUtils.isEmpty(userId)) {
54 | throw new OAuthError.InvalidGrant("");
55 | }
56 | String scope = request.getParameter("scope");
57 |
58 | AuthInfo authInfo =
59 | dataHandler.createOrUpdateAuthInfo(clientId, userId, scope);
60 | if (authInfo == null) {
61 | throw new OAuthError.InvalidGrant("");
62 | }
63 | if (!authInfo.getClientId().equals(clientId)) {
64 | throw new OAuthError.InvalidClient("");
65 | }
66 |
67 | return issueAccessToken(dataHandler, authInfo);
68 | }
69 |
70 | }
71 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/RefreshToken.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import jp.eisbahn.oauth2.server.data.DataHandler;
22 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
23 | import jp.eisbahn.oauth2.server.models.AuthInfo;
24 | import jp.eisbahn.oauth2.server.models.ClientCredential;
25 | import jp.eisbahn.oauth2.server.models.Request;
26 |
27 | /**
28 | * This class is an implementation to re-issue an access token with the
29 | * specified refresh token.
30 | *
31 | * @author Yoichiro Tanaka
32 | *
33 | */
34 | public class RefreshToken extends AbstractGrantHandler {
35 |
36 | /*
37 | * (non-Javadoc)
38 | * @see jp.eisbahn.oauth2.server.granttype.GrantHandler#handleRequest(jp.eisbahn.oauth2.server.data.DataHandler)
39 | */
40 | @Override
41 | public GrantHandlerResult handleRequest(DataHandler dataHandler) throws OAuthError {
42 | Request request = dataHandler.getRequest();
43 |
44 | ClientCredential clientCredential = getClientCredentialFetcher().fetch(request);
45 | String clientId = clientCredential.getClientId();
46 |
47 | String refreshToken = getParameter(request, "refresh_token");
48 |
49 | AuthInfo authInfo = dataHandler.getAuthInfoByRefreshToken(refreshToken);
50 | if (authInfo == null) {
51 | throw new OAuthError.InvalidGrant("");
52 | }
53 | if (!authInfo.getClientId().equals(clientId)) {
54 | throw new OAuthError.InvalidClient("");
55 | }
56 |
57 | return issueAccessToken(dataHandler, authInfo);
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/impl/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package provides some implementation classes for each grant types.
21 | */
22 | package jp.eisbahn.oauth2.server.granttype.impl;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/granttype/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package has classes to process each grant types of OAuth 2.0 for issuing
21 | * token.
22 | */
23 | package jp.eisbahn.oauth2.server.granttype;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/models/AccessToken.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | import java.util.Date;
22 |
23 | /**
24 | * This model class has an information about an access token.
25 | * The access token is issued related on one authorization information.
26 | * Actually, an instance of this model is created by an DataHandler.
27 | * The DataHandler implementation may store this to your database or
28 | * something to cache in memory or other lightweight storage.
29 | *
30 | * @author Yoichiro Tanaka
31 | *
32 | */
33 | public class AccessToken {
34 |
35 | private String authId;
36 | private String token;
37 | private long expiresIn;
38 | private Date createdOn;
39 |
40 | /**
41 | * Set the ID of the authorization information to relate between the
42 | * information and this access token.
43 | * @param authId The ID of the authorization information.
44 | */
45 | public void setAuthId(String authId) {
46 | this.authId = authId;
47 | }
48 |
49 | /**
50 | * Retrieve the ID of the authorization information.
51 | * @return The ID string.
52 | */
53 | public String getAuthId() {
54 | return authId;
55 | }
56 |
57 | /**
58 | * Set the issued access token.
59 | * @param token The access token string.
60 | */
61 | public void setToken(String token) {
62 | this.token = token;
63 | }
64 |
65 | /**
66 | * Retrieve the access token.
67 | * @return The access token string.
68 | */
69 | public String getToken() {
70 | return token;
71 | }
72 |
73 | /**
74 | * Set the expiration time of this access token.
75 | * If this access token has a time limitation, this value must be positive.
76 | * @param expiresIn The expiration time value. The unit is second.
77 | */
78 | public void setExpiresIn(long expiresIn) {
79 | this.expiresIn = expiresIn;
80 | }
81 |
82 | /**
83 | * Retrieve the expiration time of this access token.
84 | * @return The expiration time value. This unit is second.
85 | */
86 | public long getExpiresIn() {
87 | return expiresIn;
88 | }
89 |
90 | /**
91 | * Set the time when this access token is created.
92 | * @param createdOn The date and time value.
93 | */
94 | public void setCreatedOn(Date createdOn) {
95 | this.createdOn = createdOn;
96 | }
97 |
98 | /**
99 | * Retrieve the time when this access token is created.
100 | * @return The date and time value when this is created.
101 | */
102 | public Date getCreatedOn() {
103 | return createdOn;
104 | }
105 |
106 | }
107 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/models/AuthInfo.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | /**
22 | * This model class has some parameters to authorize.
23 | * A life-cycle of this model is different each grant types.
24 | * If the Authorization Code grant type is applied, this model will be created
25 | * after the authentication of the user. In other case, if the Client
26 | * Credentials grant type is applied, this model will be created at the same
27 | * time of receiving the request to issue the access token.
28 | *
29 | * @author Yoichiro Tanaka
30 | *
31 | */
32 | public class AuthInfo {
33 |
34 | private String id;
35 | private String userId;
36 | private String clientId;
37 | private String scope;
38 | private String refreshToken;
39 | private String code;
40 | private String redirectUri;
41 |
42 | /**
43 | * Set the ID of this model.
44 | * This ID value will be kept by some access token's information.
45 | * @param id The ID value.
46 | */
47 | public void setId(String id) {
48 | this.id = id;
49 | }
50 |
51 | /**
52 | * Retrieve the ID of this model.
53 | * @return The ID string value.
54 | */
55 | public String getId() {
56 | return id;
57 | }
58 |
59 | /**
60 | * Set the user's ID who is authenticated.
61 | * @param userId The user's ID value.
62 | */
63 | public void setUserId(String userId) {
64 | this.userId = userId;
65 | }
66 |
67 | /**
68 | * Retrieve the user's ID.
69 | * @return The user's ID string.
70 | */
71 | public String getUserId() {
72 | return userId;
73 | }
74 |
75 | /**
76 | * Set the client ID.
77 | * @param clientId The client ID.
78 | */
79 | public void setClientId(String clientId) {
80 | this.clientId = clientId;
81 | }
82 |
83 | /**
84 | * Retrieve the client ID.
85 | * @return The client ID string.
86 | */
87 | public String getClientId() {
88 | return clientId;
89 | }
90 |
91 | /**
92 | * Set the scope string.
93 | * This scope string has some scope identifiers delimited by a whitespace.
94 | * @param scope The scope string.
95 | */
96 | public void setScope(String scope) {
97 | this.scope = scope;
98 | }
99 |
100 | /**
101 | * Retrieve the scope string.
102 | * @return The scope string.
103 | */
104 | public String getScope() {
105 | return scope;
106 | }
107 |
108 | /**
109 | * Set the refresh token.
110 | * If the specified grant type should not return a refresh token,
111 | * this method must be set with a null as an argument.
112 | * @param refreshToken The refresh token string.
113 | */
114 | public void setRefreshToken(String refreshToken) {
115 | this.refreshToken = refreshToken;
116 | }
117 |
118 | /**
119 | * Retrieve the refresh token.
120 | * @return The refresh token string.
121 | */
122 | public String getRefreshToken() {
123 | return refreshToken;
124 | }
125 |
126 | /**
127 | * Set the authorization code.
128 | * If the grant type which doesn't need the authorization code is required,
129 | * this method must not be called.
130 | * @param code The authorization code value.
131 | */
132 | public void setCode(String code) {
133 | this.code = code;
134 | }
135 |
136 | /**
137 | * Retrieve the authorization code.
138 | * @return The authorization code value.
139 | */
140 | public String getCode() {
141 | return code;
142 | }
143 |
144 | /**
145 | * Set the redirect_uri string.
146 | * @param redirectUri The redirect_uri string.
147 | */
148 | public void setRedirectUri(String redirectUri) {
149 | this.redirectUri = redirectUri;
150 | }
151 |
152 | /**
153 | * Retrieve the redirect_uri string.
154 | * @return The redirect_uri string.
155 | */
156 | public String getRedirectUri() {
157 | return redirectUri;
158 | }
159 |
160 | }
161 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/models/ClientCredential.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | /**
22 | * This model class has an information of a client credential.
23 | *
24 | * @author Yoichiro Tanaka
25 | *
26 | */
27 | public class ClientCredential {
28 |
29 | private String clientId;
30 | private String clientSecret;
31 |
32 | /**
33 | * Initialize this instance with arguments.
34 | * @param clientId The client ID.
35 | * @param clientSecret The client secret string.
36 | */
37 | public ClientCredential(String clientId, String clientSecret) {
38 | super();
39 | this.clientId = clientId;
40 | this.clientSecret = clientSecret;
41 | }
42 |
43 | /**
44 | * Retrieve the client ID.
45 | * @return The client ID.
46 | */
47 | public String getClientId() {
48 | return clientId;
49 | }
50 |
51 | /**
52 | * Retrieve the client secret.
53 | * @return The client secret.
54 | */
55 | public String getClientSecret() {
56 | return clientSecret;
57 | }
58 |
59 | }
60 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/models/Request.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | import java.util.Map;
22 |
23 | /**
24 | * This interface defines some method to retrieve the information from the request
25 | * for processing each OAuth2.0 authorization.
26 | *
27 | * @author Yoichiro Tanaka
28 | *
29 | */
30 | public interface Request {
31 |
32 | /**
33 | * Retrieve the parameter value specified by the parameter name
34 | * from the request.
35 | * @param name The parameter name.
36 | * @return The value against the name.
37 | */
38 | public String getParameter(String name);
39 |
40 | /**
41 | * Retrieve all parameter names and values from the request as a Map instance.
42 | * @return The map instance which has all parameter names and values.
43 | */
44 | public Map getParameterMap();
45 |
46 | /**
47 | * Retrieve the request header value from the request.
48 | * @param name The header's name.
49 | * @return The value against the name.
50 | */
51 | public String getHeader(String name);
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/models/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package has some model classes to input/output between this framework
21 | * and your client.
22 | */
23 | package jp.eisbahn.oauth2.server.models;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This project is an implementation for OAuth 2.0 Specification.
21 | * Especially, the protocol of the server area is covered by this project.
22 | *
23 | * How to use
24 | *
25 | * This project is supporting some common processes to issue tokens.
26 | * To use this framework, you have to provide an implementation of a
27 | * DataHandler interface. The implementation class connects this framework
28 | * to your databases or such storages.
29 | *
30 | * Also, you have to implement a DataHandlerFactory interface to
31 | * create your DataHandler instance.
32 | *
33 | * Classes you have to implement are only above.
34 | *
35 | * A class to handle a request to issue an access token is Token class.
36 | * But, the Token class needs some helper classes. Therefore, you have to
37 | * provide their instances to the Token instance. If you're using Spring Framework
38 | * DI Container, you can inject them to the Token instance. Refer the applicationContext-token-schenario.xml file.
39 | *
40 | * The way to use the Token class is simple. You can use it as the following snippet:
41 | *
42 | *
43 | * HttpServletRequest request = ...; // Provided by Servlet Container
44 | * Token token = ...; // Injected
45 | * Token.Response response = token.handleRequest(request);
46 | * int code = response.getCode(); // 200, 400, 401, ...
47 | * String body = response.getBody(); // {"token_type":"Bearer","access_token":"...", ...}
48 | *
49 | * An code for an integration test has the request and response contents of each grant type.
50 | * Refer the test code TokenScenarioTest.
51 | */
52 | package jp.eisbahn.oauth2.server;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/spi/servlet/HttpServletRequestAdapter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import java.util.Map;
22 |
23 | import javax.servlet.http.HttpServletRequest;
24 |
25 | import jp.eisbahn.oauth2.server.models.Request;
26 |
27 | /**
28 | * This class adapts a HttpServletRequest to a Request interface.
29 | *
30 | * @author Yoichiro Tanaka
31 | *
32 | */
33 | public class HttpServletRequestAdapter implements Request {
34 |
35 | private HttpServletRequest request;
36 |
37 | /**
38 | * Initialize this instance with the HttpServletRequest.
39 | * @param request The request object on the Servlet API.
40 | */
41 | public HttpServletRequestAdapter(HttpServletRequest request) {
42 | super();
43 | this.request = request;
44 | }
45 |
46 | /*
47 | * (non-Javadoc)
48 | * @see jp.eisbahn.oauth2.server.models.Request#getParameter(java.lang.String)
49 | */
50 | @Override
51 | public String getParameter(String name) {
52 | return request.getParameter(name);
53 | }
54 |
55 | /*
56 | * (non-Javadoc)
57 | * @see jp.eisbahn.oauth2.server.models.Request#getHeader(java.lang.String)
58 | */
59 | @Override
60 | public String getHeader(String name) {
61 | return request.getHeader(name);
62 | }
63 |
64 | /*
65 | * (non-Javadoc)
66 | * @see jp.eisbahn.oauth2.server.models.Request#getParameterMap()
67 | */
68 | @SuppressWarnings("unchecked")
69 | @Override
70 | public Map getParameterMap() {
71 | return request.getParameterMap();
72 | }
73 |
74 | }
75 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/spi/servlet/ProtectedResourceFilter.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import java.io.IOException;
22 | import java.util.ArrayList;
23 | import java.util.List;
24 |
25 | import javax.servlet.Filter;
26 | import javax.servlet.FilterChain;
27 | import javax.servlet.FilterConfig;
28 | import javax.servlet.ServletException;
29 | import javax.servlet.ServletRequest;
30 | import javax.servlet.ServletResponse;
31 | import javax.servlet.http.HttpServletRequest;
32 | import javax.servlet.http.HttpServletResponse;
33 |
34 | import org.apache.commons.lang3.StringUtils;
35 |
36 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
37 | import jp.eisbahn.oauth2.server.endpoint.ProtectedResource;
38 | import jp.eisbahn.oauth2.server.endpoint.ProtectedResource.Response;
39 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
40 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcherProvider;
41 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.DefaultAccessTokenFetcherProvider;
42 |
43 | /**
44 | * This servlet filter checks whether a request to access to each protected
45 | * resource is valid or not as the OAuth 2.0.
46 | *
47 | * This instance needs two helper objects. One is a DataHandlerFactory instance.
48 | * Other one is a AccessTokenFetcherProvider instance. These implementation
49 | * class name are specified as the init-param values. For instance, specify
50 | * the following in your web.xml file:
51 | *
52 | *
53 | * <filter>
54 | * <filter-name>protectedResourceFilter<filter-name>
55 | * <filter-class>jp.eisbahn.oauth2.server.spi.servlet.ProtectedResourceFilter<filter-name>
56 | * <init-param>
57 | * <param-name>dataHandlerFactory</param-name>
58 | * <param-value>your-class-name</param-value>
59 | * </init-param>
60 | * <init-param>
61 | * <param-name>accessTokenFetcherProvider</param-name>
62 | * <param-value>your-class-name</param-value>
63 | * </init-param>
64 | * </filter>
65 | *
66 | *
67 | * @author Yoichiro Tanaka
68 | *
69 | */
70 | public class ProtectedResourceFilter implements Filter {
71 |
72 | private static final String DATA_HANDLER_FACTORY_CLASSNAME = "dataHandlerFactory";
73 | private static final String ACCESS_TOKEN_FETCHER_PROVIDER_CLASSNAME = "accessTokenFetcherProvider";
74 |
75 | private ProtectedResource protectedResource;
76 |
77 | /**
78 | * Initialize this filter.
79 | * For instance, this method loads two implementation class name and create
80 | * these instances. Then, the ProtectedResource instance to process the
81 | * OAuth 2.0 validation for the request is created with their helper instances.
82 | *
83 | * @param config The FilterConfig object.
84 | * @exception ServletException Each helper instance could not be created.
85 | */
86 | @Override
87 | public void init(FilterConfig config) throws ServletException {
88 | try {
89 | DataHandlerFactory dataHandlerFactory = getDataHandlerFactory(config);
90 | AccessTokenFetcherProvider accessTokenFetcherProvider = getAccessTokenFetcherProvider(config);
91 | protectedResource = new ProtectedResource();
92 | protectedResource.setDataHandlerFactory(dataHandlerFactory);
93 | protectedResource.setAccessTokenFetcherProvider(accessTokenFetcherProvider);
94 | } catch (ClassNotFoundException e) {
95 | throw new ServletException(e.getMessage(), e);
96 | } catch (InstantiationException e) {
97 | throw new ServletException(e.getMessage(), e);
98 | } catch (IllegalAccessException e) {
99 | throw new ServletException(e.getMessage(), e);
100 | }
101 | }
102 |
103 | /**
104 | * Check the request for whether can access or not to APIs to access the protected
105 | * resource.
106 | *
107 | * @param req The request object.
108 | * @param resp The response object.
109 | * @param chain The chain object to chain some filters.
110 | * @exception IOException When the error regarding I/O occurred.
111 | * @exception ServletException When the first argument is not a HttpServletRequest
112 | * instance.
113 | */
114 | @Override
115 | public void doFilter(ServletRequest req, ServletResponse resp,
116 | FilterChain chain) throws IOException, ServletException {
117 | if (req instanceof HttpServletRequest) {
118 | HttpServletRequest httpRequest = (HttpServletRequest)req;
119 | HttpServletRequestAdapter adapter = new HttpServletRequestAdapter(httpRequest);
120 | try {
121 | Response response = protectedResource.handleRequest(adapter);
122 | req.setAttribute("client_id", response.getClientId());
123 | req.setAttribute("remote_user", response.getRemoteUser());
124 | req.setAttribute("scope", response.getScope());
125 | chain.doFilter(req, resp);
126 | } catch (OAuthError e) {
127 | if (resp instanceof HttpServletResponse) {
128 | HttpServletResponse httpResponse = (HttpServletResponse)resp;
129 | httpResponse.setStatus(e.getCode());
130 | List params = new ArrayList();
131 | params.add("error=\"" + e.getType() + "\"");
132 | if (StringUtils.isNotBlank(e.getDescription())) {
133 | params.add("error_description=\"" + e.getDescription() + "\"");
134 | }
135 | String error = StringUtils.join(params, ", ");
136 | httpResponse.setHeader("WWW-Authenticate", "Bearer " + error);
137 | } else {
138 | throw new ServletException("This filter is available under HTTP Servlet container.");
139 | }
140 | }
141 | } else {
142 | throw new ServletException("This filter is available under HTTP Servlet container.");
143 | }
144 | }
145 |
146 | /**
147 | * Do nothing.
148 | */
149 | @Override
150 | public void destroy() {
151 | }
152 |
153 | private AccessTokenFetcherProvider getAccessTokenFetcherProvider(FilterConfig config)
154 | throws InstantiationException, IllegalAccessException, ClassNotFoundException {
155 | AccessTokenFetcherProvider provider = createInstance(ACCESS_TOKEN_FETCHER_PROVIDER_CLASSNAME, config);
156 | if (provider != null) {
157 | return provider;
158 | } else {
159 | return new DefaultAccessTokenFetcherProvider();
160 | }
161 | }
162 |
163 | private DataHandlerFactory getDataHandlerFactory(FilterConfig config)
164 | throws ClassNotFoundException, InstantiationException, IllegalAccessException {
165 | return createInstance(DATA_HANDLER_FACTORY_CLASSNAME, config);
166 | }
167 |
168 | @SuppressWarnings("unchecked")
169 | private T createInstance(String name, FilterConfig config)
170 | throws InstantiationException, IllegalAccessException, ClassNotFoundException {
171 | String className = config.getInitParameter(name);
172 | if (className != null) {
173 | Class> clazz = Class.forName(className);
174 | return (T)clazz.newInstance();
175 | } else {
176 | return null;
177 | }
178 | }
179 |
180 | }
181 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/spi/servlet/TokenServlet.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import java.io.IOException;
22 | import java.io.PrintWriter;
23 |
24 | import javax.servlet.ServletConfig;
25 | import javax.servlet.ServletException;
26 | import javax.servlet.http.HttpServlet;
27 | import javax.servlet.http.HttpServletRequest;
28 | import javax.servlet.http.HttpServletResponse;
29 |
30 | import org.apache.commons.io.IOUtils;
31 |
32 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
33 | import jp.eisbahn.oauth2.server.endpoint.Token;
34 | import jp.eisbahn.oauth2.server.endpoint.Token.Response;
35 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcher;
36 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
37 | import jp.eisbahn.oauth2.server.granttype.GrantHandlerProvider;
38 | import jp.eisbahn.oauth2.server.granttype.impl.DefaultGrantHandlerProvider;
39 |
40 | /**
41 | * This class is an HttpServlet implementation of the Token issuing endpoint.
42 | *
43 | * This instance needs Three helper objects. One is a DataHandlerFactory instance.
44 | * Other one is a GrantHandlerProvider instance. Last one is
45 | * ClientCredentialFetcher instance. These implementation
46 | * class name are specified as the init-param values. For instance, specify
47 | * the following in your web.xml file:
48 | *
49 | *
50 | * <servlet>
51 | * <servlet-name>token<servlet-name>
52 | * <servlet-class>jp.eisbahn.oauth2.server.spi.servlet.TokenServlet<servlet-name>
53 | * <init-param>
54 | * <param-name>dataHandlerFactory</param-name>
55 | * <param-value>your-class-name</param-value>
56 | * </init-param>
57 | * <init-param>
58 | * <param-name>grantHandlerProvider</param-name>
59 | * <param-value>your-class-name</param-value>
60 | * </init-param>
61 | * <init-param>
62 | * <param-name>clientCredentialFetcher</param-name>
63 | * <param-value>your-class-name</param-value>
64 | * </init-param>
65 | * </servlet>
66 | *
67 | *
68 | * @author Yoichiro Tanaka
69 | *
70 | */
71 | @SuppressWarnings("serial")
72 | public class TokenServlet extends HttpServlet {
73 |
74 | private static final String DATA_HANDLER_FACTORY_CLASSNAME = "dataHandlerFactory";
75 | private static final String GRANT_HANDLER_PROVIDER_CLASSNAME = "grantHandlerProvider";
76 | private static final String CLIENT_CREDENTIAL_FETCHER_CLASSNAME = "clientCredentialFetcher";
77 |
78 | private Token token;
79 |
80 | /**
81 | * Initialize this servlet.
82 | * For instance, this method loads three implementation class name and create
83 | * these instances. Then, the Token instance to process the
84 | * OAuth 2.0 grant execution for the request is created with their helper instances.
85 | *
86 | * @param config The ServletConfig object.
87 | * @exception ServletException Each helper instance could not be created.
88 | */
89 | @Override
90 | public void init(ServletConfig config) throws ServletException {
91 | try {
92 | DataHandlerFactory dataHandlerFactory = getDataHandlerFactory(config);
93 | GrantHandlerProvider grantHandlerProvider = getGrantHandlerProvider(config);
94 | ClientCredentialFetcher clientCredentialFetcher = getClientCredentialFetcher(config);
95 | token = new Token();
96 | token.setDataHandlerFactory(dataHandlerFactory);
97 | token.setGrantHandlerProvider(grantHandlerProvider);
98 | token.setClientCredentialFetcher(clientCredentialFetcher);
99 | } catch (ClassNotFoundException e) {
100 | throw new ServletException(e.getMessage(), e);
101 | } catch (InstantiationException e) {
102 | throw new ServletException(e.getMessage(), e);
103 | } catch (IllegalAccessException e) {
104 | throw new ServletException(e.getMessage(), e);
105 | }
106 | }
107 |
108 | private ClientCredentialFetcher getClientCredentialFetcher(ServletConfig config)
109 | throws InstantiationException, IllegalAccessException, ClassNotFoundException {
110 | ClientCredentialFetcher fetcher = createInstance(CLIENT_CREDENTIAL_FETCHER_CLASSNAME, config);
111 | if (fetcher != null) {
112 | return fetcher;
113 | } else {
114 | return new ClientCredentialFetcherImpl();
115 | }
116 | }
117 |
118 | private GrantHandlerProvider getGrantHandlerProvider(ServletConfig config)
119 | throws InstantiationException, IllegalAccessException, ClassNotFoundException {
120 | GrantHandlerProvider provider = createInstance(GRANT_HANDLER_PROVIDER_CLASSNAME, config);
121 | if (provider != null) {
122 | return provider;
123 | } else {
124 | return new DefaultGrantHandlerProvider();
125 | }
126 | }
127 |
128 | private DataHandlerFactory getDataHandlerFactory(ServletConfig config)
129 | throws ClassNotFoundException, InstantiationException, IllegalAccessException {
130 | return createInstance(DATA_HANDLER_FACTORY_CLASSNAME, config);
131 | }
132 |
133 | @SuppressWarnings("unchecked")
134 | private T createInstance(String name, ServletConfig config)
135 | throws InstantiationException, IllegalAccessException, ClassNotFoundException {
136 | String className = config.getInitParameter(name);
137 | if (className != null) {
138 | Class> clazz = Class.forName(className);
139 | return (T)clazz.newInstance();
140 | } else {
141 | return null;
142 | }
143 | }
144 |
145 | /**
146 | * Issue the token against the request based on OAuth 2.0.
147 | *
148 | * @param req The request object.
149 | * @param resp The response object.
150 | * @exception IOException When the error regarding I/O occurred.
151 | * @exception ServletException When other error occurred.
152 | */
153 | @Override
154 | protected void doPost(HttpServletRequest req, HttpServletResponse resp)
155 | throws ServletException, IOException {
156 | HttpServletRequestAdapter request = new HttpServletRequestAdapter(req);
157 | Response response = token.handleRequest(request);
158 | resp.setStatus(response.getCode());
159 | resp.setContentType("application/json; charset=UTF-8");
160 | PrintWriter writer = resp.getWriter();
161 | IOUtils.write(response.getBody(), writer);
162 | writer.flush();
163 | }
164 |
165 | }
166 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/spi/servlet/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package provides an implementation of this framework with Servlet API.
21 | * You can use this framework easily and quickly using this package.
22 | */
23 | package jp.eisbahn.oauth2.server.spi.servlet;
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/utils/Util.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.utils;
20 |
21 | import java.io.IOException;
22 | import java.io.UnsupportedEncodingException;
23 | import java.net.URLDecoder;
24 |
25 | import org.apache.commons.codec.binary.Base64;
26 | import org.codehaus.jackson.JsonGenerationException;
27 | import org.codehaus.jackson.map.JsonMappingException;
28 | import org.codehaus.jackson.map.ObjectMapper;
29 |
30 | /**
31 | * This class provides some utility methods.
32 | *
33 | * @author Yoichiro Tanaka
34 | *
35 | */
36 | public class Util {
37 |
38 | /**
39 | * Decode the URL encoded string.
40 | * @param source The URL encoded string.
41 | * @return The decoded original string.
42 | */
43 | public static String decodeParam(String source) {
44 | try {
45 | return URLDecoder.decode(source, "UTF-8");
46 | } catch (UnsupportedEncodingException e) {
47 | throw new IllegalStateException(e);
48 | }
49 | }
50 |
51 | /**
52 | * Decode the BASE64 encoded string.
53 | * @param source The BASE64 string.
54 | * @return The decoded original string.
55 | */
56 | public static String decodeBase64(String source) {
57 | try {
58 | return new String(Base64.decodeBase64(source), "UTF-8");
59 | } catch (UnsupportedEncodingException e) {
60 | throw new IllegalStateException(e);
61 | }
62 | }
63 |
64 | /**
65 | * Encode the object to JSON format string.
66 | * @param source The object that you want to change to JSON string.
67 | * @return The JSON encoded string.
68 | * @throws IllegalStateException If the translation failed.
69 | */
70 | public static String toJson(Object source) {
71 | try {
72 | ObjectMapper mapper = new ObjectMapper();
73 | return mapper.writeValueAsString(source);
74 | } catch (JsonGenerationException e) {
75 | throw new IllegalStateException(e);
76 | } catch (JsonMappingException e) {
77 | throw new IllegalStateException(e);
78 | } catch (IOException e) {
79 | throw new IllegalStateException(e);
80 | }
81 | }
82 |
83 | }
84 |
--------------------------------------------------------------------------------
/src/main/java/jp/eisbahn/oauth2/server/utils/package-info.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | /**
20 | * This package provides a class which has some methods to use commonly.
21 | */
22 | package jp.eisbahn.oauth2.server.utils;
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/data/DataHandlerTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.data;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | import org.easymock.EasyMock;
24 | import org.junit.Test;
25 |
26 | import jp.eisbahn.oauth2.server.data.DataHandler;
27 | import jp.eisbahn.oauth2.server.models.AccessToken;
28 | import jp.eisbahn.oauth2.server.models.AuthInfo;
29 | import jp.eisbahn.oauth2.server.models.Request;
30 |
31 | public class DataHandlerTest {
32 |
33 | private class Target extends DataHandler {
34 |
35 | public Target(Request request) {
36 | super(request);
37 | }
38 |
39 | @Override
40 | public boolean validateClient(String clientId, String clientSecret,
41 | String grantType) {
42 | return false;
43 | }
44 |
45 | @Override
46 | public String getUserId(String userName, String password) {
47 | return null;
48 | }
49 |
50 | @Override
51 | public AuthInfo createOrUpdateAuthInfo(String clientId, String userId,
52 | String scope) {
53 | return null;
54 | }
55 |
56 | @Override
57 | public AccessToken createOrUpdateAccessToken(AuthInfo authInfo) {
58 | return null;
59 | }
60 |
61 | @Override
62 | public AuthInfo getAuthInfoByCode(String code) {
63 | return null;
64 | }
65 |
66 | @Override
67 | public AuthInfo getAuthInfoByRefreshToken(String refreshToken) {
68 | return null;
69 | }
70 |
71 | @Override
72 | public String getClientUserId(String clientId, String clientSecret) {
73 | return null;
74 | }
75 |
76 | @Override
77 | public AccessToken getAccessToken(String token) {
78 | return null;
79 | }
80 |
81 | @Override
82 | public AuthInfo getAuthInfoById(String id) {
83 | return null;
84 | }
85 |
86 | @Override
87 | public boolean validateClientById(String clientId) {
88 | return true;
89 | }
90 |
91 | @Override
92 | public boolean validateUserById(String userId) {
93 | return true;
94 | }
95 |
96 | }
97 |
98 | @Test
99 | public void testSimple() throws Exception {
100 | Request request = EasyMock.createMock(Request.class);
101 | DataHandler target = new Target(request);
102 | assertEquals(request, target.getRequest());
103 | assertTrue(target.validateClientById(null));
104 | assertTrue(target.validateUserById(null));
105 | }
106 |
107 | }
108 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/endpoint/ProtectedResourceResponseTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.endpoint;
20 |
21 | import static org.junit.Assert.assertEquals;
22 |
23 | import org.junit.Test;
24 |
25 | import jp.eisbahn.oauth2.server.endpoint.ProtectedResource.Response;
26 |
27 | public class ProtectedResourceResponseTest {
28 |
29 | @Test
30 | public void testSimple() {
31 | Response target = new Response("remoteUser1", "clientId1", "scope1");
32 | assertEquals("remoteUser1", target.getRemoteUser());
33 | assertEquals("clientId1", target.getClientId());
34 | assertEquals("scope1", target.getScope());
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/endpoint/TokenResponseTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.endpoint;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | import org.junit.Test;
24 |
25 | import jp.eisbahn.oauth2.server.endpoint.Token.Response;
26 |
27 | public class TokenResponseTest {
28 |
29 | @Test
30 | public void testSimple() {
31 | Response target = new Response(200, "body1");
32 | assertEquals(200, target.getCode());
33 | assertEquals("body1", target.getBody());
34 | }
35 |
36 | }
37 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/endpoint/TokenTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.endpoint;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.easymock.EasyMock.verify;
25 | import static org.junit.Assert.assertEquals;
26 |
27 | import java.util.HashMap;
28 |
29 | import jp.eisbahn.oauth2.server.data.DataHandler;
30 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
31 | import jp.eisbahn.oauth2.server.endpoint.Token;
32 | import jp.eisbahn.oauth2.server.endpoint.Token.Response;
33 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
34 | import jp.eisbahn.oauth2.server.granttype.GrantHandler;
35 | import jp.eisbahn.oauth2.server.granttype.GrantHandlerProvider;
36 | import jp.eisbahn.oauth2.server.granttype.impl.RefreshToken;
37 | import jp.eisbahn.oauth2.server.models.AccessToken;
38 | import jp.eisbahn.oauth2.server.models.AuthInfo;
39 | import jp.eisbahn.oauth2.server.models.Request;
40 |
41 | import org.junit.Test;
42 |
43 | public class TokenTest {
44 |
45 | @Test
46 | public void testHandleRequestGrantTypeNotFound() throws Exception {
47 | Request request = createMock(Request.class);
48 | expect(request.getParameter("grant_type")).andReturn(null);
49 | replay(request);
50 | Token target = new Token();
51 | Response response = target.handleRequest(request);
52 | assertEquals(400, response.getCode());
53 | assertEquals(
54 | "{\"error\":\"invalid_request\","
55 | + "\"error_description\":\"'grant_type' not found\"}",
56 | response.getBody());
57 | verify(request);
58 | }
59 |
60 | @Test
61 | public void testHandleRequestGrantTypeNotSupported() throws Exception {
62 | Request request = createMock(Request.class);
63 | expect(request.getParameter("grant_type")).andReturn("evil");
64 | DataHandlerFactory factory = createMock(DataHandlerFactory.class);
65 | replay(request, factory);
66 | Token target = createToken(factory);
67 | Response response = target.handleRequest(request);
68 | assertEquals(400, response.getCode());
69 | assertEquals(
70 | "{\"error\":\"unsupported_grant_type\"}",
71 | response.getBody());
72 | verify(request, factory);
73 | }
74 |
75 | @Test
76 | public void testHandleRequestClientIdNotFound() throws Exception {
77 | Request request = createMock(Request.class);
78 | expect(request.getParameter("grant_type")).andReturn("refresh_token");
79 | expect(request.getHeader("Authorization")).andReturn(null);
80 | expect(request.getParameter("client_id")).andReturn(null);
81 | expect(request.getParameter("client_secret")).andReturn(null);
82 | DataHandlerFactory factory = createMock(DataHandlerFactory.class);
83 | expect(factory.create(request)).andReturn(null);
84 | replay(request, factory);
85 | Token target = createToken(factory);
86 | Response response = target.handleRequest(request);
87 | assertEquals(400, response.getCode());
88 | assertEquals(
89 | "{\"error\":\"invalid_request\","
90 | + "\"error_description\":\"'client_id' not found\"}",
91 | response.getBody());
92 | verify(request, factory);
93 | }
94 |
95 | @Test
96 | public void testHandleRequestClientSecretNotFound() throws Exception {
97 | Request request = createMock(Request.class);
98 | expect(request.getParameter("grant_type")).andReturn("refresh_token");
99 | expect(request.getHeader("Authorization")).andReturn(null);
100 | expect(request.getParameter("client_id")).andReturn("clientId1");
101 | expect(request.getParameter("client_secret")).andReturn(null);
102 | DataHandlerFactory factory = createMock(DataHandlerFactory.class);
103 | expect(factory.create(request)).andReturn(null);
104 | replay(request, factory);
105 | Token target = createToken(factory);
106 | Response response = target.handleRequest(request);
107 | assertEquals(400, response.getCode());
108 | assertEquals(
109 | "{\"error\":\"invalid_request\","
110 | + "\"error_description\":\"'client_secret' not found\"}",
111 | response.getBody());
112 | verify(request, factory);
113 | }
114 |
115 | @Test
116 | public void testHandleRequestClientInvalid() throws Exception {
117 | Request request = createMock(Request.class);
118 | expect(request.getParameter("grant_type")).andReturn("refresh_token");
119 | expect(request.getHeader("Authorization")).andReturn(null);
120 | expect(request.getParameter("client_id")).andReturn("clientId1");
121 | expect(request.getParameter("client_secret")).andReturn("clientSecret1");
122 | DataHandlerFactory factory = createMock(DataHandlerFactory.class);
123 | DataHandler dataHandler = createMock(DataHandler.class);
124 | expect(dataHandler.validateClient(
125 | "clientId1", "clientSecret1", "refresh_token")).andReturn(false);
126 | expect(factory.create(request)).andReturn(dataHandler);
127 | replay(request, factory, dataHandler);
128 | Token target = createToken(factory);
129 | Response response = target.handleRequest(request);
130 | assertEquals(401, response.getCode());
131 | assertEquals(
132 | "{\"error\":\"invalid_client\"}",
133 | response.getBody());
134 | verify(request, factory, dataHandler);
135 | }
136 |
137 | @Test
138 | public void testHandleRequestSimple() throws Exception {
139 | Request request = createMock(Request.class);
140 | expect(request.getParameter("grant_type")).andReturn("refresh_token");
141 | expect(request.getHeader("Authorization")).andReturn(null).times(2);
142 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
143 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
144 | expect(request.getParameter("refresh_token")).andReturn("refreshToken1");
145 | DataHandlerFactory factory = createMock(DataHandlerFactory.class);
146 | DataHandler dataHandler = createMock(DataHandler.class);
147 | expect(dataHandler.validateClient(
148 | "clientId1", "clientSecret1", "refresh_token")).andReturn(true);
149 | expect(dataHandler.getRequest()).andReturn(request);
150 | AuthInfo authInfo = new AuthInfo();
151 | authInfo.setClientId("clientId1");
152 | expect(dataHandler.getAuthInfoByRefreshToken("refreshToken1")).andReturn(authInfo);
153 | AccessToken accessToken = new AccessToken();
154 | accessToken.setToken("accessToken1");
155 | expect(dataHandler.createOrUpdateAccessToken(authInfo)).andReturn(accessToken);
156 | expect(factory.create(request)).andReturn(dataHandler);
157 | replay(request, factory, dataHandler);
158 | Token target = createToken(factory);
159 | Response response = target.handleRequest(request);
160 | assertEquals(200, response.getCode());
161 | assertEquals(
162 | "{\"token_type\":\"Bearer\",\"access_token\":\"accessToken1\"}",
163 | response.getBody());
164 | verify(request, factory, dataHandler);
165 | }
166 |
167 | @SuppressWarnings("serial")
168 | private Token createToken(DataHandlerFactory factory) {
169 | Token token = new Token();
170 | token.setDataHandlerFactory(factory);
171 | token.setClientCredentialFetcher(new ClientCredentialFetcherImpl());
172 | GrantHandlerProvider provider = new GrantHandlerProvider();
173 | final RefreshToken refreshToken = new RefreshToken();
174 | refreshToken.setClientCredentialFetcher(new ClientCredentialFetcherImpl());
175 | provider.setGrantHandlers(new HashMap() {
176 | {
177 | put("refresh_token", refreshToken);
178 | }
179 | });
180 | token.setGrantHandlerProvider(provider);
181 | return token;
182 | }
183 |
184 | }
185 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/exceptions/OAuthErrorTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.exceptions;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | import org.junit.Test;
24 |
25 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
26 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.AccessDenied;
27 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.ExpiredToken;
28 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.InsufficientScope;
29 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.InvalidClient;
30 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.InvalidGrant;
31 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.InvalidRequest;
32 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.InvalidScope;
33 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.InvalidToken;
34 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.RedirectUriMismatch;
35 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.UnauthorizedClient;
36 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.UnsupportedGrantType;
37 | import jp.eisbahn.oauth2.server.exceptions.OAuthError.UnsupportedResponseType;
38 |
39 | public class OAuthErrorTest {
40 |
41 | @SuppressWarnings("serial")
42 | private static class Target extends OAuthError {
43 |
44 | public Target(int code, String description) {
45 | super(code, description);
46 | }
47 |
48 | public Target(String description) {
49 | super(description);
50 | }
51 |
52 | @Override
53 | public String getType() {
54 | return null;
55 | }
56 |
57 | }
58 |
59 | @Test
60 | public void testErrorSimple() {
61 | OAuthError target = new Target(401, "desc1");
62 | assertEquals(401, target.getCode());
63 | assertEquals("desc1", target.getDescription());
64 |
65 | target = new Target("desc2");
66 | assertEquals(400, target.getCode());
67 | assertEquals("desc2", target.getDescription());
68 | }
69 |
70 | @Test
71 | public void testInvalidRequest() {
72 | InvalidRequest target = new InvalidRequest("desc1");
73 | assertEquals(400, target.getCode());
74 | assertEquals("desc1", target.getDescription());
75 | assertEquals("invalid_request", target.getType());
76 | }
77 |
78 | @Test
79 | public void testInvalidClient() {
80 | InvalidClient target = new InvalidClient("desc1");
81 | assertEquals(401, target.getCode());
82 | assertEquals("desc1", target.getDescription());
83 | assertEquals("invalid_client", target.getType());
84 | }
85 |
86 | @Test
87 | public void testUnauthorizedClient() {
88 | UnauthorizedClient target = new UnauthorizedClient("desc1");
89 | assertEquals(401, target.getCode());
90 | assertEquals("desc1", target.getDescription());
91 | assertEquals("unauthorized_client", target.getType());
92 | }
93 |
94 | @Test
95 | public void testRedirectUriMismatch() {
96 | RedirectUriMismatch target = new RedirectUriMismatch("desc1");
97 | assertEquals(401, target.getCode());
98 | assertEquals("desc1", target.getDescription());
99 | assertEquals("redirect_uri_mismatch", target.getType());
100 | }
101 |
102 | @Test
103 | public void testAccessDenied() {
104 | AccessDenied target = new AccessDenied("desc1");
105 | assertEquals(401, target.getCode());
106 | assertEquals("desc1", target.getDescription());
107 | assertEquals("access_denied", target.getType());
108 | }
109 |
110 | @Test
111 | public void testUnsupportedResponseType() {
112 | UnsupportedResponseType target = new UnsupportedResponseType("desc1");
113 | assertEquals(400, target.getCode());
114 | assertEquals("desc1", target.getDescription());
115 | assertEquals("unsupported_response_type", target.getType());
116 | }
117 |
118 | @Test
119 | public void testInvalidGrant() {
120 | InvalidGrant target = new InvalidGrant("desc1");
121 | assertEquals(401, target.getCode());
122 | assertEquals("desc1", target.getDescription());
123 | assertEquals("invalid_grant", target.getType());
124 | }
125 |
126 | @Test
127 | public void testUnsupportedGrantType() {
128 | UnsupportedGrantType target = new UnsupportedGrantType("desc1");
129 | assertEquals(400, target.getCode());
130 | assertEquals("desc1", target.getDescription());
131 | assertEquals("unsupported_grant_type", target.getType());
132 | }
133 |
134 | @Test
135 | public void testInvalidScope() {
136 | InvalidScope target = new InvalidScope("desc1");
137 | assertEquals(401, target.getCode());
138 | assertEquals("desc1", target.getDescription());
139 | assertEquals("invalid_scope", target.getType());
140 | }
141 |
142 | @Test
143 | public void testInvalidToken() {
144 | InvalidToken target = new InvalidToken("desc1");
145 | assertEquals(401, target.getCode());
146 | assertEquals("desc1", target.getDescription());
147 | assertEquals("invalid_token", target.getType());
148 | }
149 |
150 | @Test
151 | public void testExpiredToken() {
152 | ExpiredToken target = new ExpiredToken();
153 | assertEquals(401, target.getCode());
154 | assertEquals("The access token expired", target.getDescription());
155 | assertEquals("invalid_token", target.getType());
156 | }
157 |
158 | @Test
159 | public void testInsufficientScope() {
160 | InsufficientScope target = new InsufficientScope("desc1");
161 | assertEquals(401, target.getCode());
162 | assertEquals("desc1", target.getDescription());
163 | assertEquals("insufficient_scope", target.getType());
164 | }
165 |
166 | }
167 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/AccessTokenFetcherProviderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.junit.Assert.assertNull;
25 | import static org.junit.Assert.assertTrue;
26 | import static org.junit.Assert.assertEquals;
27 |
28 | import org.junit.After;
29 | import org.junit.Before;
30 | import org.junit.Test;
31 |
32 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.AuthHeader;
33 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.RequestParameter;
34 | import jp.eisbahn.oauth2.server.models.Request;
35 |
36 | public class AccessTokenFetcherProviderTest {
37 |
38 | private AccessTokenFetcherProvider target;
39 |
40 | @Before
41 | public void setUp() {
42 | target = new AccessTokenFetcherProvider();
43 | target.setAccessTokenFetchers(new AccessTokenFetcher[]{
44 | new AuthHeader(),
45 | new RequestParameter()
46 | });
47 | }
48 |
49 | @After
50 | public void tearDown() {
51 | target = null;
52 | }
53 |
54 | @Test
55 | public void testFetchers() throws Exception {
56 | AccessTokenFetcher[] accessTokenFetchers = target.getAccessTokenFetchers();
57 | assertEquals(2, accessTokenFetchers.length);
58 | assertTrue(accessTokenFetchers[0] instanceof AuthHeader);
59 | assertTrue(accessTokenFetchers[1] instanceof RequestParameter);
60 | }
61 |
62 | @Test
63 | public void testGetParamParserAuthHeader() throws Exception {
64 | Request request = createMock(Request.class);
65 | expect(request.getHeader("Authorization")).andReturn("Bearer access_token_value");
66 | replay(request);
67 | AccessTokenFetcher paramParser = target.getFetcher(request);
68 | assertTrue(paramParser instanceof AuthHeader);
69 | }
70 |
71 | @Test
72 | public void testGetParamParserRequestParameter() throws Exception {
73 | Request request = createMock(Request.class);
74 | expect(request.getHeader("Authorization")).andReturn(null);
75 | expect(request.getParameter("oauth_token")).andReturn("access_token_value");
76 | expect(request.getParameter("access_token")).andReturn("access_token_value");
77 | replay(request);
78 | AccessTokenFetcher paramParser = target.getFetcher(request);
79 | assertTrue(paramParser instanceof RequestParameter);
80 | }
81 |
82 | @Test
83 | public void testGetParamParserNotFound() throws Exception {
84 | Request request = createMock(Request.class);
85 | expect(request.getHeader("Authorization")).andReturn(null);
86 | expect(request.getParameter("oauth_token")).andReturn(null);
87 | expect(request.getParameter("access_token")).andReturn(null);
88 | replay(request);
89 | AccessTokenFetcher paramParser = target.getFetcher(request);
90 | assertNull(paramParser);
91 | }
92 |
93 | }
94 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/FetchResultTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken;
20 |
21 | import static org.junit.Assert.assertEquals;
22 |
23 | import java.util.HashMap;
24 | import java.util.Map;
25 |
26 | import org.junit.After;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 |
30 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
31 |
32 | public class FetchResultTest {
33 |
34 | private FetchResult target;
35 |
36 | @Before
37 | public void setUp() {
38 | target = new FetchResult();
39 | }
40 |
41 | @After
42 | public void tearDown() {
43 | target = null;
44 | }
45 |
46 | @Test
47 | public void testTokenProperty() throws Exception {
48 | String token = "token1";
49 | target.setToken(token);
50 | assertEquals(token, target.getToken());
51 | }
52 |
53 | @Test
54 | public void testParamsProperty() throws Exception {
55 | Map params = new HashMap();
56 | target.setParams(params);
57 | assertEquals(params, target.getParams());
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/AuthHeaderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
20 |
21 | import static org.junit.Assert.*;
22 | import static org.easymock.EasyMock.*;
23 |
24 | import java.util.Map;
25 |
26 | import org.junit.After;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 |
30 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
31 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.AuthHeader;
32 | import jp.eisbahn.oauth2.server.models.Request;
33 |
34 | public class AuthHeaderTest {
35 |
36 | private AuthHeader target;
37 |
38 | @Before
39 | public void setUp() {
40 | target = new AuthHeader();
41 | }
42 |
43 | @After
44 | public void tearDown() {
45 | target = null;
46 | }
47 |
48 | @Test
49 | public void testMatch() {
50 | Request req;
51 |
52 | req = createRequestMock(null);
53 | assertFalse(target.match(req));
54 | verify(req);
55 |
56 | req = createRequestMock("OAuth token1");
57 | assertTrue(target.match(req));
58 | verify(req);
59 |
60 | req = createRequestMock("OAuth");
61 | assertTrue(target.match(req));
62 | verify(req);
63 |
64 | req = createRequestMock(" OAuth token1");
65 | assertTrue(target.match(req));
66 | verify(req);
67 |
68 | req = createRequestMock("OAut token1");
69 | assertFalse(target.match(req));
70 | verify(req);
71 |
72 | req = createRequestMock("oauth token1");
73 | assertFalse(target.match(req));
74 | verify(req);
75 |
76 | req = createRequestMock("Bearer token1");
77 | assertTrue(target.match(req));
78 | verify(req);
79 |
80 | req = createRequestMock("Bearer");
81 | assertTrue(target.match(req));
82 | verify(req);
83 |
84 | req = createRequestMock(" Bearer token1");
85 | assertTrue(target.match(req));
86 | verify(req);
87 |
88 | req = createRequestMock("Beare token1");
89 | assertFalse(target.match(req));
90 | verify(req);
91 |
92 | req = createRequestMock("bearer token1");
93 | assertFalse(target.match(req));
94 | verify(req);
95 | }
96 |
97 | @Test
98 | public void testParse() throws Exception {
99 | Request req;
100 | FetchResult parseResult;
101 | Map params;
102 |
103 | req = createRequestMock("Bearer access_token_value");
104 | parseResult = target.fetch(req);
105 | assertEquals("access_token_value", parseResult.getToken());
106 | assertTrue(parseResult.getParams().isEmpty());
107 |
108 | req = createRequestMock("OAuth access_token_value");
109 | parseResult = target.fetch(req);
110 | assertEquals("access_token_value", parseResult.getToken());
111 | params = parseResult.getParams();
112 | assertTrue(params.isEmpty());
113 |
114 | req = createRequestMock(
115 | "Bearer access_token_value, "
116 | + "algorithm=\"hmac-sha256\", "
117 | + "nonce=\"s8djwd\", "
118 | + "signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\", "
119 | + "timestamp=\"137131200\"");
120 | parseResult = target.fetch(req);
121 | assertEquals("access_token_value", parseResult.getToken());
122 | params = parseResult.getParams();
123 | assertFalse(params.isEmpty());
124 | assertEquals("hmac-sha256", params.get("algorithm"));
125 | assertEquals("s8djwd", params.get("nonce"));
126 | assertEquals("wOJIO9A2W5mFwDgiDvZbTSMK/PY=", params.get("signature"));
127 | assertEquals("137131200", params.get("timestamp"));
128 |
129 | req = createRequestMock(
130 | "OAuth access_token_value, "
131 | + "algorithm=\"hmac-sha256\", "
132 | + "nonce=\"s8djwd\", "
133 | + "signature=\"wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D\", "
134 | + "timestamp=\"137131200\"");
135 | parseResult = target.fetch(req);
136 | assertEquals("access_token_value", parseResult.getToken());
137 | params = parseResult.getParams();
138 | assertFalse(params.isEmpty());
139 | assertEquals("hmac-sha256", params.get("algorithm"));
140 | assertEquals("s8djwd", params.get("nonce"));
141 | assertEquals("wOJIO9A2W5mFwDgiDvZbTSMK/PY=", params.get("signature"));
142 | assertEquals("137131200", params.get("timestamp"));
143 |
144 | req = createRequestMock("evil");
145 | try {
146 | parseResult = target.fetch(req);
147 | fail("IllegalStateException not occurred.");
148 | } catch (IllegalStateException e) {
149 | }
150 | }
151 |
152 | private Request createRequestMock(String authorization) {
153 | Request request = createMock(Request.class);
154 | expect(request.getHeader("Authorization")).andReturn(authorization);
155 | replay(request);
156 | return request;
157 | }
158 |
159 | }
160 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/DefaultAccessTokenFetcherProviderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
20 |
21 | import static org.junit.Assert.*;
22 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher;
23 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.AuthHeader;
24 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.DefaultAccessTokenFetcherProvider;
25 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.RequestParameter;
26 |
27 | import org.junit.Test;
28 |
29 | public class DefaultAccessTokenFetcherProviderTest {
30 |
31 | @Test
32 | public void testSimple() throws Exception {
33 | DefaultAccessTokenFetcherProvider target = new DefaultAccessTokenFetcherProvider();
34 | AccessTokenFetcher[] accessTokenFetchers = target.getAccessTokenFetchers();
35 | assertEquals(2, accessTokenFetchers.length);
36 | assertTrue(accessTokenFetchers[0] instanceof AuthHeader);
37 | assertTrue(accessTokenFetchers[1] instanceof RequestParameter);
38 | }
39 |
40 | }
41 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/fetcher/accesstoken/impl/RequestParameterTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.accesstoken.impl;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.easymock.EasyMock.verify;
25 | import static org.junit.Assert.assertEquals;
26 | import static org.junit.Assert.assertFalse;
27 | import static org.junit.Assert.assertTrue;
28 |
29 | import java.util.HashMap;
30 | import java.util.Map;
31 |
32 | import org.apache.commons.collections.MapUtils;
33 | import org.junit.After;
34 | import org.junit.Before;
35 | import org.junit.Test;
36 |
37 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.AccessTokenFetcher.FetchResult;
38 | import jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.RequestParameter;
39 | import jp.eisbahn.oauth2.server.models.Request;
40 |
41 | public class RequestParameterTest {
42 |
43 | private RequestParameter target;
44 |
45 | @Before
46 | public void setUp() throws Exception {
47 | target = new RequestParameter();
48 | }
49 |
50 | @After
51 | public void tearDown() throws Exception {
52 | target = null;
53 | }
54 |
55 | @Test
56 | public void testMatch() throws Exception {
57 | Request req;
58 |
59 | req = createRequestMock(null, null);
60 | assertFalse(target.match(req));
61 | verify(req);
62 |
63 | req = createRequestMock("token1", null);
64 | assertTrue(target.match(req));
65 | verify(req);
66 |
67 | req = createRequestMock(null, "token1");
68 | assertTrue(target.match(req));
69 | verify(req);
70 |
71 | req = createRequestMock("token1", "token2");
72 | assertTrue(target.match(req));
73 | verify(req);
74 | }
75 |
76 | @Test
77 | public void testParse() throws Exception {
78 | Request req;
79 | FetchResult parseResult;
80 |
81 | req = createRequestMock(new String[]{
82 | "oauth_token", "access_token_value"
83 | });
84 | parseResult = target.fetch(req);
85 | assertEquals("access_token_value", parseResult.getToken());
86 | assertTrue(parseResult.getParams().isEmpty());
87 | verify(req);
88 |
89 | req = createRequestMock(new String[]{
90 | "access_token", "access_token_value"
91 | });
92 | parseResult = target.fetch(req);
93 | assertEquals("access_token_value", parseResult.getToken());
94 | assertTrue(parseResult.getParams().isEmpty());
95 | verify(req);
96 |
97 | req = createRequestMock(new String[]{
98 | "access_token", "access_token_value",
99 | "foo", "bar"
100 | });
101 | parseResult = target.fetch(req);
102 | assertEquals("access_token_value", parseResult.getToken());
103 | assertFalse(parseResult.getParams().isEmpty());
104 | Map params = parseResult.getParams();
105 | assertEquals(1, params.size());
106 | assertEquals("bar", params.get("foo"));
107 | verify(req);
108 | }
109 |
110 | private Request createRequestMock(
111 | String oauthToken, String accessToken) {
112 | Request request = createMock(Request.class);
113 | expect(request.getParameter("oauth_token")).andReturn(oauthToken);
114 | expect(request.getParameter("access_token")).andReturn(accessToken);
115 | replay(request);
116 | return request;
117 | }
118 |
119 | private Request createRequestMock(String[] values) {
120 | Map parameterMap = new HashMap();
121 | MapUtils.putAll(parameterMap, values);
122 | Request request = createMock(Request.class);
123 | expect(request.getParameterMap()).andReturn(parameterMap);
124 | replay(request);
125 | return request;
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/fetcher/clientcredential/ClientCredentialFetcherImplTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.fetcher.clientcredential;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.junit.Assert.assertEquals;
25 |
26 | import org.junit.After;
27 | import org.junit.Before;
28 | import org.junit.Test;
29 |
30 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
31 | import jp.eisbahn.oauth2.server.models.ClientCredential;
32 | import jp.eisbahn.oauth2.server.models.Request;
33 |
34 | public class ClientCredentialFetcherImplTest {
35 |
36 | private ClientCredentialFetcherImpl target;
37 |
38 | @Before
39 | public void setUp() {
40 | target = new ClientCredentialFetcherImpl();
41 | }
42 |
43 | @After
44 | public void tearDown() {
45 | target = null;
46 | }
47 |
48 | @Test
49 | public void testFetchBasic() throws Exception {
50 | Request request = createMock(Request.class);
51 | String encoded = "Y2xpZW50X2lkX3ZhbHVlOmNsaWVudF9zZWNyZXRfdmFsdWU=";
52 | expect(request.getHeader("Authorization")).andReturn("Basic " + encoded);
53 | replay(request);
54 | ClientCredential clientCredential = target.fetch(request);
55 | assertEquals("client_id_value", clientCredential.getClientId());
56 | assertEquals("client_secret_value", clientCredential.getClientSecret());
57 | }
58 |
59 | @Test
60 | public void testFetchParameter() throws Exception {
61 | Request request = createMock(Request.class);
62 | expect(request.getHeader("Authorization")).andReturn(null);
63 | expect(request.getParameter("client_id")).andReturn("client_id_value");
64 | expect(request.getParameter("client_secret")).andReturn("client_secret_value");
65 | replay(request);
66 | ClientCredential clientCredential = target.fetch(request);
67 | assertEquals("client_id_value", clientCredential.getClientId());
68 | assertEquals("client_secret_value", clientCredential.getClientSecret());
69 | }
70 |
71 | }
72 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/granttype/GrantHandlerProviderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype;
20 |
21 | import static org.junit.Assert.assertTrue;
22 | import static org.junit.Assert.assertEquals;
23 |
24 | import java.util.HashMap;
25 | import java.util.Map;
26 |
27 | import org.junit.Test;
28 |
29 | import jp.eisbahn.oauth2.server.granttype.GrantHandler;
30 | import jp.eisbahn.oauth2.server.granttype.GrantHandlerProvider;
31 | import jp.eisbahn.oauth2.server.granttype.impl.AuthorizationCode;
32 | import jp.eisbahn.oauth2.server.granttype.impl.ClientCredentials;
33 | import jp.eisbahn.oauth2.server.granttype.impl.Password;
34 | import jp.eisbahn.oauth2.server.granttype.impl.RefreshToken;
35 |
36 | public class GrantHandlerProviderTest {
37 |
38 | @Test
39 | public void testSimple() {
40 | @SuppressWarnings("serial")
41 | Map handlers = new HashMap() {
42 | {
43 | put("authorization_code", new AuthorizationCode());
44 | put("password", new Password());
45 | put("refresh_token", new RefreshToken());
46 | put("client_credentials", new ClientCredentials());
47 | }
48 | };
49 | GrantHandlerProvider target = new GrantHandlerProvider();
50 | target.setGrantHandlers(handlers);
51 | assertTrue(target.getHandler("authorization_code") instanceof AuthorizationCode);
52 | assertTrue(target.getHandler("password") instanceof Password);
53 | assertTrue(target.getHandler("refresh_token") instanceof RefreshToken);
54 | assertTrue(target.getHandler("client_credentials") instanceof ClientCredentials);
55 | handlers = target.getHandlers();
56 | assertEquals(4, handlers.size());
57 | assertTrue(handlers.get("authorization_code") instanceof AuthorizationCode);
58 | assertTrue(handlers.get("password") instanceof Password);
59 | assertTrue(handlers.get("refresh_token") instanceof RefreshToken);
60 | assertTrue(handlers.get("client_credentials") instanceof ClientCredentials);
61 | }
62 |
63 | }
64 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/granttype/GrantHandlerResultTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | import org.junit.Test;
24 |
25 | import jp.eisbahn.oauth2.server.granttype.GrantHandler.GrantHandlerResult;
26 |
27 | public class GrantHandlerResultTest {
28 |
29 | @Test
30 | public void testSimple() {
31 | GrantHandlerResult target = new GrantHandlerResult(
32 | "tokenType1", "accessToken1");
33 | assertEquals("tokenType1", target.getTokenType());
34 | assertEquals("accessToken1", target.getAccessToken());
35 |
36 | long expiresIn = 123L;
37 | target.setExpiresIn(expiresIn);
38 | assertEquals(expiresIn, (long)target.getExpiresIn());
39 | String refreshToken = "refreshToken1";
40 | target.setRefreshToken(refreshToken);
41 | assertEquals(refreshToken, target.getRefreshToken());
42 | String scope = "scope1";
43 | target.setScope(scope);
44 | assertEquals(scope, target.getScope());
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/granttype/impl/ClientCredentialsTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.junit.Assert.assertEquals;
25 | import static org.junit.Assert.assertNull;
26 | import static org.junit.Assert.fail;
27 |
28 | import org.junit.After;
29 | import org.junit.Before;
30 | import org.junit.Test;
31 |
32 | import jp.eisbahn.oauth2.server.data.DataHandler;
33 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
34 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
35 | import jp.eisbahn.oauth2.server.granttype.GrantHandler.GrantHandlerResult;
36 | import jp.eisbahn.oauth2.server.granttype.impl.ClientCredentials;
37 | import jp.eisbahn.oauth2.server.models.AccessToken;
38 | import jp.eisbahn.oauth2.server.models.AuthInfo;
39 | import jp.eisbahn.oauth2.server.models.Request;
40 |
41 | public class ClientCredentialsTest {
42 |
43 | private ClientCredentials target;
44 |
45 | @Before
46 | public void setUp() {
47 | target = new ClientCredentials();
48 | target.setClientCredentialFetcher(new ClientCredentialFetcherImpl());
49 | }
50 |
51 | @After
52 | public void tearDown() {
53 | target = null;
54 | }
55 |
56 | @Test
57 | public void testHandleRequestClientUserIdNotFound() throws Exception {
58 | Request request = createRequestMock();
59 | DataHandler dataHandler = createDataHandlerMock(request);
60 | expect(dataHandler.getClientUserId("clientId1", "clientSecret1")).andReturn(null);
61 | replay(request, dataHandler);
62 | try {
63 | target.handleRequest(dataHandler);
64 | fail("Error.InvalidClient not occurred.");
65 | } catch (OAuthError.InvalidClient e) {
66 | }
67 | }
68 |
69 | @Test
70 | public void testHandleRequestAuthInfoNotFound() throws Exception {
71 | Request request = createRequestMock();
72 | expect(request.getParameter("scope")).andReturn("scope1");
73 | DataHandler dataHandler = createDataHandlerMock(request);
74 | expect(dataHandler.getClientUserId("clientId1", "clientSecret1")).andReturn("userId1");
75 | expect(dataHandler.createOrUpdateAuthInfo("clientId1", "userId1", "scope1")).andReturn(null);
76 | replay(request, dataHandler);
77 | try {
78 | target.handleRequest(dataHandler);
79 | fail("Error.InvalidGrant not occurred.");
80 | } catch (OAuthError.InvalidGrant e) {
81 | }
82 | }
83 |
84 | @Test
85 | public void testHandleRequestSimple() throws Exception {
86 | Request request = createRequestMock();
87 | expect(request.getParameter("scope")).andReturn("scope1");
88 | DataHandler dataHandler = createDataHandlerMock(request);
89 | expect(dataHandler.getClientUserId("clientId1", "clientSecret1")).andReturn("userId1");
90 | AuthInfo authInfo = new AuthInfo();
91 | authInfo.setClientId("clientId1");
92 | expect(dataHandler.createOrUpdateAuthInfo("clientId1", "userId1", "scope1")).andReturn(authInfo);
93 | AccessToken accessToken = new AccessToken();
94 | accessToken.setToken("accessToken1");
95 | expect(dataHandler.createOrUpdateAccessToken(authInfo)).andReturn(accessToken);
96 | replay(request, dataHandler);
97 | GrantHandlerResult result = target.handleRequest(dataHandler);
98 | assertEquals("Bearer", result.getTokenType());
99 | assertEquals("accessToken1", result.getAccessToken());
100 | assertNull(result.getExpiresIn());
101 | assertNull(result.getRefreshToken());
102 | assertNull(result.getScope());
103 | }
104 |
105 | @Test
106 | public void testHandleRequestFull() throws Exception {
107 | Request request = createRequestMock();
108 | expect(request.getParameter("scope")).andReturn("scope1");
109 | DataHandler dataHandler = createDataHandlerMock(request);
110 | expect(dataHandler.getClientUserId("clientId1", "clientSecret1")).andReturn("userId1");
111 | AuthInfo authInfo = new AuthInfo();
112 | authInfo.setClientId("clientId1");
113 | authInfo.setRedirectUri("redirectUri1");
114 | authInfo.setRefreshToken("refreshToken1");
115 | authInfo.setScope("scope1");
116 | expect(dataHandler.createOrUpdateAuthInfo("clientId1", "userId1", "scope1")).andReturn(authInfo);
117 | AccessToken accessToken = new AccessToken();
118 | accessToken.setToken("accessToken1");
119 | accessToken.setExpiresIn(123L);
120 | expect(dataHandler.createOrUpdateAccessToken(authInfo)).andReturn(accessToken);
121 | replay(request, dataHandler);
122 | GrantHandlerResult result = target.handleRequest(dataHandler);
123 | assertEquals("Bearer", result.getTokenType());
124 | assertEquals("accessToken1", result.getAccessToken());
125 | assertEquals(123L, (long)result.getExpiresIn());
126 | assertEquals("refreshToken1", result.getRefreshToken());
127 | assertEquals("scope1", result.getScope());
128 | }
129 |
130 | private Request createRequestMock() {
131 | Request request = createMock(Request.class);
132 | expect(request.getHeader("Authorization")).andReturn(null);
133 | expect(request.getParameter("client_id")).andReturn("clientId1");
134 | expect(request.getParameter("client_secret")).andReturn("clientSecret1");
135 | return request;
136 | }
137 |
138 | private DataHandler createDataHandlerMock(Request request) {
139 | DataHandler dataHandler = createMock(DataHandler.class);
140 | expect(dataHandler.getRequest()).andReturn(request);
141 | return dataHandler;
142 | }
143 |
144 | }
145 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/granttype/impl/DefaultGrantHandlerProviderTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import static org.junit.Assert.*;
22 |
23 | import java.util.Map;
24 |
25 | import jp.eisbahn.oauth2.server.granttype.GrantHandler;
26 | import jp.eisbahn.oauth2.server.granttype.impl.AuthorizationCode;
27 | import jp.eisbahn.oauth2.server.granttype.impl.ClientCredentials;
28 | import jp.eisbahn.oauth2.server.granttype.impl.DefaultGrantHandlerProvider;
29 | import jp.eisbahn.oauth2.server.granttype.impl.Password;
30 | import jp.eisbahn.oauth2.server.granttype.impl.RefreshToken;
31 |
32 | import org.junit.Test;
33 |
34 | public class DefaultGrantHandlerProviderTest {
35 |
36 | @Test
37 | public void testSimple() throws Exception {
38 | DefaultGrantHandlerProvider target = new DefaultGrantHandlerProvider();
39 | Map handlers = target.getHandlers();
40 | assertEquals(4, handlers.size());
41 | assertTrue(handlers.get("authorization_code") instanceof AuthorizationCode);
42 | assertTrue(handlers.get("password") instanceof Password);
43 | assertTrue(handlers.get("refresh_token") instanceof RefreshToken);
44 | assertTrue(handlers.get("client_credentials") instanceof ClientCredentials);
45 | }
46 |
47 | }
48 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/granttype/impl/RefreshTokenTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.granttype.impl;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.junit.Assert.assertEquals;
25 | import static org.junit.Assert.assertNull;
26 | import static org.junit.Assert.fail;
27 |
28 | import org.junit.After;
29 | import org.junit.Before;
30 | import org.junit.Test;
31 |
32 | import jp.eisbahn.oauth2.server.data.DataHandler;
33 | import jp.eisbahn.oauth2.server.exceptions.OAuthError;
34 | import jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl;
35 | import jp.eisbahn.oauth2.server.granttype.GrantHandler.GrantHandlerResult;
36 | import jp.eisbahn.oauth2.server.granttype.impl.RefreshToken;
37 | import jp.eisbahn.oauth2.server.models.AccessToken;
38 | import jp.eisbahn.oauth2.server.models.AuthInfo;
39 | import jp.eisbahn.oauth2.server.models.Request;
40 |
41 | public class RefreshTokenTest {
42 |
43 | private RefreshToken target;
44 |
45 | @Before
46 | public void setUp() {
47 | target = new RefreshToken();
48 | target.setClientCredentialFetcher(new ClientCredentialFetcherImpl());
49 | }
50 |
51 | @After
52 | public void tearDown() {
53 | target = null;
54 | }
55 |
56 | @Test
57 | public void testHandleRequestRefreshTokenNotFound() throws Exception {
58 | Request request = createRequestMock();
59 | expect(request.getParameter("refresh_token")).andReturn(null);
60 | DataHandler dataHandler = createDataHandlerMock(request);
61 | replay(request, dataHandler);
62 | try {
63 | target.handleRequest(dataHandler);
64 | fail("Error.InvalidRequest not occurred.");
65 | } catch (OAuthError.InvalidRequest e) {
66 | assertEquals("'refresh_token' not found", e.getDescription());
67 | }
68 | }
69 |
70 | @Test
71 | public void testHandleRequestAuthInfoNotFound() throws Exception {
72 | Request request = createRequestMock();
73 | expect(request.getParameter("refresh_token")).andReturn("refreshToken1");
74 | DataHandler dataHandler = createDataHandlerMock(request);
75 | expect(dataHandler.getAuthInfoByRefreshToken("refreshToken1")).andReturn(null);
76 | replay(request, dataHandler);
77 | try {
78 | target.handleRequest(dataHandler);
79 | fail("Error.InvalidGrant not occurred.");
80 | } catch (OAuthError.InvalidGrant e) {
81 | }
82 | }
83 |
84 | @Test
85 | public void testHandleRequestClientIdMismatch() throws Exception {
86 | Request request = createRequestMock();
87 | expect(request.getParameter("refresh_token")).andReturn("refreshToken1");
88 | DataHandler dataHandler = createDataHandlerMock(request);
89 | AuthInfo authInfo = new AuthInfo();
90 | authInfo.setClientId("clientId2");
91 | expect(dataHandler.getAuthInfoByRefreshToken("refreshToken1")).andReturn(authInfo);
92 | replay(request, dataHandler);
93 | try {
94 | target.handleRequest(dataHandler);
95 | fail("Error.InvalidClient not occurred.");
96 | } catch (OAuthError.InvalidClient e) {
97 | }
98 | }
99 |
100 | @Test
101 | public void testHandleRequestSimple() throws Exception {
102 | Request request = createRequestMock();
103 | expect(request.getParameter("refresh_token")).andReturn("refreshToken1");
104 | DataHandler dataHandler = createDataHandlerMock(request);
105 | AuthInfo authInfo = new AuthInfo();
106 | authInfo.setClientId("clientId1");
107 | expect(dataHandler.getAuthInfoByRefreshToken("refreshToken1")).andReturn(authInfo);
108 | AccessToken accessToken = new AccessToken();
109 | accessToken.setToken("accessToken1");
110 | expect(dataHandler.createOrUpdateAccessToken(authInfo)).andReturn(accessToken);
111 | replay(request, dataHandler);
112 | GrantHandlerResult result = target.handleRequest(dataHandler);
113 | assertEquals("Bearer", result.getTokenType());
114 | assertEquals("accessToken1", result.getAccessToken());
115 | assertNull(result.getExpiresIn());
116 | assertNull(result.getRefreshToken());
117 | assertNull(result.getScope());
118 | }
119 |
120 | @Test
121 | public void testHandleRequestFull() throws Exception {
122 | Request request = createRequestMock();
123 | expect(request.getParameter("refresh_token")).andReturn("refreshToken1");
124 | DataHandler dataHandler = createDataHandlerMock(request);
125 | AuthInfo authInfo = new AuthInfo();
126 | authInfo.setClientId("clientId1");
127 | authInfo.setRedirectUri("redirectUri1");
128 | authInfo.setRefreshToken("refreshToken1");
129 | authInfo.setScope("scope1");
130 | expect(dataHandler.getAuthInfoByRefreshToken("refreshToken1")).andReturn(authInfo);
131 | AccessToken accessToken = new AccessToken();
132 | accessToken.setToken("accessToken1");
133 | accessToken.setExpiresIn(123L);
134 | expect(dataHandler.createOrUpdateAccessToken(authInfo)).andReturn(accessToken);
135 | replay(request, dataHandler);
136 | GrantHandlerResult result = target.handleRequest(dataHandler);
137 | assertEquals("Bearer", result.getTokenType());
138 | assertEquals("accessToken1", result.getAccessToken());
139 | assertEquals(123L, (long)result.getExpiresIn());
140 | assertEquals("refreshToken1", result.getRefreshToken());
141 | assertEquals("scope1", result.getScope());
142 | }
143 |
144 | private Request createRequestMock() {
145 | Request request = createMock(Request.class);
146 | expect(request.getHeader("Authorization")).andReturn(null);
147 | expect(request.getParameter("client_id")).andReturn("clientId1");
148 | expect(request.getParameter("client_secret")).andReturn("clientSecret1");
149 | return request;
150 | }
151 |
152 | private DataHandler createDataHandlerMock(Request request) {
153 | DataHandler dataHandler = createMock(DataHandler.class);
154 | expect(dataHandler.getRequest()).andReturn(request);
155 | return dataHandler;
156 | }
157 |
158 | }
159 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/integration/DummyDataHandlerFactoryImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.integration;
20 |
21 | import java.util.Date;
22 |
23 | import jp.eisbahn.oauth2.server.data.DataHandler;
24 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
25 | import jp.eisbahn.oauth2.server.models.AccessToken;
26 | import jp.eisbahn.oauth2.server.models.AuthInfo;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 |
29 | public class DummyDataHandlerFactoryImpl implements DataHandlerFactory {
30 |
31 | @Override
32 | public DataHandler create(Request request) {
33 | return new DummyDataHandler(request);
34 | }
35 |
36 | public static class DummyDataHandler extends DataHandler {
37 |
38 | public DummyDataHandler(Request request) {
39 | super(request);
40 | }
41 |
42 | @Override
43 | public boolean validateClient(String clientId, String clientSecret,
44 | String grantType) {
45 | return true;
46 | }
47 |
48 | @Override
49 | public String getUserId(String username, String password) {
50 | return "userId1";
51 | }
52 |
53 | @Override
54 | public AuthInfo createOrUpdateAuthInfo(String clientId, String userId,
55 | String scope) {
56 | AuthInfo authInfo = new AuthInfo();
57 | authInfo.setClientId(clientId);
58 | authInfo.setUserId(userId);
59 | authInfo.setRefreshToken("refreshToken1");
60 | authInfo.setScope(scope);
61 | return authInfo;
62 | }
63 |
64 | @Override
65 | public AccessToken createOrUpdateAccessToken(AuthInfo authInfo) {
66 | AccessToken accessToken = new AccessToken();
67 | accessToken.setToken("accessToken1");
68 | accessToken.setExpiresIn(900L);
69 | return accessToken;
70 | }
71 |
72 | @Override
73 | public AuthInfo getAuthInfoByCode(String code) {
74 | AuthInfo authInfo = new AuthInfo();
75 | authInfo.setClientId("clientId1");
76 | authInfo.setRedirectUri("redirectUri1");
77 | authInfo.setRefreshToken("refreshToken1");
78 | authInfo.setScope("scope1");
79 | authInfo.setCode(code);
80 | return authInfo;
81 | }
82 |
83 | @Override
84 | public AuthInfo getAuthInfoByRefreshToken(String refreshToken) {
85 | AuthInfo authInfo = new AuthInfo();
86 | authInfo.setClientId("clientId1");
87 | authInfo.setRedirectUri("redirectUri1");
88 | authInfo.setRefreshToken(refreshToken);
89 | authInfo.setScope("scope1");
90 | return authInfo;
91 | }
92 |
93 | @Override
94 | public String getClientUserId(String clientId, String clientSecret) {
95 | return "clientUserId";
96 | }
97 |
98 | @Override
99 | public AccessToken getAccessToken(String token) {
100 | AccessToken accessToken = new AccessToken();
101 | accessToken.setAuthId("authId1");
102 | accessToken.setCreatedOn(new Date());
103 | accessToken.setExpiresIn(3600);
104 | return accessToken;
105 | }
106 |
107 | @Override
108 | public AuthInfo getAuthInfoById(String id) {
109 | AuthInfo authInfo = new AuthInfo();
110 | authInfo.setClientId("clientId1");
111 | authInfo.setId(id);
112 | authInfo.setUserId("userId1");
113 | authInfo.setScope("scope1");
114 | return authInfo;
115 | }
116 |
117 | @Override
118 | public boolean validateClientById(String clientId) {
119 | return true;
120 | }
121 |
122 | @Override
123 | public boolean validateUserById(String userId) {
124 | return true;
125 | }
126 |
127 | }
128 |
129 | }
130 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/integration/ProtectedResourceScenarioTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.integration;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.easymock.EasyMock.verify;
25 | import static org.junit.Assert.assertEquals;
26 |
27 | import jp.eisbahn.oauth2.server.endpoint.ProtectedResource;
28 | import jp.eisbahn.oauth2.server.endpoint.ProtectedResource.Response;
29 | import jp.eisbahn.oauth2.server.models.Request;
30 |
31 | import org.junit.Test;
32 | import org.junit.runner.RunWith;
33 | import org.springframework.beans.factory.annotation.Autowired;
34 | import org.springframework.test.context.ContextConfiguration;
35 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
36 |
37 | @RunWith(SpringJUnit4ClassRunner.class)
38 | @ContextConfiguration("/applicationContext-protectedresource-scenario.xml")
39 | public class ProtectedResourceScenarioTest {
40 |
41 | @Autowired
42 | private ProtectedResource target;
43 |
44 | @Test
45 | public void testSimple() throws Exception {
46 | Request request = createMock(Request.class);
47 | expect(request.getHeader("Authorization")).andReturn("Bearer accessToken1").times(2);
48 | replay(request);
49 | Response response = target.handleRequest(request);
50 | assertEquals("userId1", response.getRemoteUser());
51 | assertEquals("clientId1", response.getClientId());
52 | assertEquals("scope1", response.getScope());
53 | verify(request);
54 | }
55 |
56 | }
57 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/integration/TokenScenarioTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.integration;
20 |
21 | import static org.junit.Assert.*;
22 | import static org.easymock.EasyMock.*;
23 |
24 | import org.junit.Test;
25 | import org.junit.runner.RunWith;
26 | import org.springframework.beans.factory.annotation.Autowired;
27 | import org.springframework.test.context.ContextConfiguration;
28 | import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
29 |
30 | import jp.eisbahn.oauth2.server.endpoint.Token;
31 | import jp.eisbahn.oauth2.server.endpoint.Token.Response;
32 | import jp.eisbahn.oauth2.server.models.Request;
33 |
34 | @RunWith(SpringJUnit4ClassRunner.class)
35 | @ContextConfiguration("/applicationContext-token-scenario.xml")
36 | public class TokenScenarioTest {
37 |
38 | @Autowired
39 | private Token token;
40 |
41 | @Test
42 | public void testAuthorizationCodeGrant() throws Exception {
43 | Request request = createMock(Request.class);
44 | expect(request.getParameter("grant_type")).andReturn("authorization_code");
45 | expect(request.getHeader("Authorization")).andReturn(null).times(2);
46 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
47 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
48 | expect(request.getParameter("code")).andReturn("code1");
49 | expect(request.getParameter("redirect_uri")).andReturn("redirectUri1");
50 | replay(request);
51 | Response response = token.handleRequest(request);
52 | assertEquals(200, response.getCode());
53 | assertEquals(
54 | "{\"token_type\":\"Bearer\","
55 | + "\"access_token\":\"accessToken1\","
56 | + "\"refresh_token\":\"refreshToken1\","
57 | + "\"expires_in\":900,"
58 | + "\"scope\":\"scope1\"}",
59 | response.getBody());
60 | verify(request);
61 | }
62 |
63 | @Test
64 | public void testRefreshTokenGrant() throws Exception {
65 | Request request = createMock(Request.class);
66 | expect(request.getParameter("grant_type")).andReturn("refresh_token");
67 | expect(request.getHeader("Authorization")).andReturn(null).times(2);
68 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
69 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
70 | expect(request.getParameter("refresh_token")).andReturn("refreshToken1");
71 | replay(request);
72 | Response response = token.handleRequest(request);
73 | assertEquals(200, response.getCode());
74 | assertEquals(
75 | "{\"token_type\":\"Bearer\","
76 | + "\"access_token\":\"accessToken1\","
77 | + "\"refresh_token\":\"refreshToken1\","
78 | + "\"expires_in\":900,"
79 | + "\"scope\":\"scope1\"}",
80 | response.getBody());
81 | verify(request);
82 | }
83 |
84 | @Test
85 | public void testResourceOwnerPasswordCredentialsGrant() throws Exception {
86 | Request request = createMock(Request.class);
87 | expect(request.getParameter("grant_type")).andReturn("password");
88 | expect(request.getHeader("Authorization")).andReturn(null).times(2);
89 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
90 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
91 | expect(request.getParameter("username")).andReturn("username1");
92 | expect(request.getParameter("password")).andReturn("password1");
93 | expect(request.getParameter("scope")).andReturn("scope1");
94 | replay(request);
95 | Response response = token.handleRequest(request);
96 | assertEquals(200, response.getCode());
97 | assertEquals(
98 | "{\"token_type\":\"Bearer\","
99 | + "\"access_token\":\"accessToken1\","
100 | + "\"refresh_token\":\"refreshToken1\","
101 | + "\"expires_in\":900,"
102 | + "\"scope\":\"scope1\"}",
103 | response.getBody());
104 | verify(request);
105 | }
106 |
107 | @Test
108 | public void testClientCredentialsGrant() throws Exception {
109 | Request request = createMock(Request.class);
110 | expect(request.getParameter("grant_type")).andReturn("client_credentials");
111 | expect(request.getHeader("Authorization")).andReturn(null).times(2);
112 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
113 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
114 | expect(request.getParameter("scope")).andReturn("scope1");
115 | replay(request);
116 | Response response = token.handleRequest(request);
117 | assertEquals(200, response.getCode());
118 | assertEquals(
119 | "{\"token_type\":\"Bearer\","
120 | + "\"access_token\":\"accessToken1\","
121 | + "\"refresh_token\":\"refreshToken1\","
122 | + "\"expires_in\":900,"
123 | + "\"scope\":\"scope1\"}",
124 | response.getBody());
125 | verify(request);
126 | }
127 |
128 | }
129 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/models/AccessTokenTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | import static org.junit.Assert.assertEquals;
22 |
23 | import java.util.Date;
24 |
25 | import jp.eisbahn.oauth2.server.models.AccessToken;
26 |
27 | import org.junit.Test;
28 |
29 | public class AccessTokenTest {
30 |
31 | @Test
32 | public void testAuthIdProperty() throws Exception {
33 | AccessToken target = new AccessToken();
34 | target.setAuthId("authId1");
35 | assertEquals("authId1", target.getAuthId());
36 | }
37 |
38 | @Test
39 | public void testTokenProperty() throws Exception {
40 | AccessToken target = new AccessToken();
41 | target.setToken("token1");
42 | assertEquals("token1", target.getToken());
43 | }
44 |
45 | @Test
46 | public void testExpiresInProperty() throws Exception {
47 | AccessToken target = new AccessToken();
48 | target.setExpiresIn(12345L);
49 | assertEquals(12345L, target.getExpiresIn());
50 | }
51 |
52 | @Test
53 | public void testCreatedOnProperty() throws Exception {
54 | AccessToken target = new AccessToken();
55 | Date now = new Date();
56 | target.setCreatedOn(now);
57 | assertEquals(now, target.getCreatedOn());
58 | }
59 |
60 | }
61 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/models/AuthInfoTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | import static org.junit.Assert.assertEquals;
22 | import jp.eisbahn.oauth2.server.models.AuthInfo;
23 |
24 | import org.junit.After;
25 | import org.junit.Before;
26 | import org.junit.Test;
27 |
28 | public class AuthInfoTest {
29 |
30 | private AuthInfo target;
31 |
32 | @Before
33 | public void setUp() {
34 | target = new AuthInfo();
35 | }
36 |
37 | @After
38 | public void tearDown() {
39 | target = null;
40 | }
41 |
42 | @Test
43 | public void testIdProperty() throws Exception {
44 | target.setId("id1");
45 | assertEquals("id1", target.getId());
46 | }
47 |
48 | @Test
49 | public void testUserIdProperty() throws Exception {
50 | target.setUserId("userId1");
51 | assertEquals("userId1", target.getUserId());
52 | }
53 |
54 | @Test
55 | public void testClientIdProperty() throws Exception {
56 | target.setClientId("clientId1");
57 | assertEquals("clientId1", target.getClientId());
58 | }
59 |
60 | @Test
61 | public void testScopeProperty() throws Exception {
62 | target.setScope("scope1");
63 | assertEquals("scope1", target.getScope());
64 | }
65 |
66 | @Test
67 | public void testRefreshTokenProperty() throws Exception {
68 | target.setRefreshToken("refreshToken1");
69 | assertEquals("refreshToken1", target.getRefreshToken());
70 | }
71 |
72 | @Test
73 | public void testCodeProperty() throws Exception {
74 | target.setCode("code1");
75 | assertEquals("code1", target.getCode());
76 | }
77 |
78 | @Test
79 | public void testRedirectUriProperty() throws Exception {
80 | target.setRedirectUri("redirectUri1");
81 | assertEquals("redirectUri1", target.getRedirectUri());
82 | }
83 |
84 | }
85 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/models/ClientCredentialTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.models;
20 |
21 | import static org.junit.Assert.*;
22 | import jp.eisbahn.oauth2.server.models.ClientCredential;
23 |
24 | import org.junit.Test;
25 |
26 | public class ClientCredentialTest {
27 |
28 | @Test
29 | public void testSimple() {
30 | String clientId = "clientId1";
31 | String clientSecret = "clientSecret1";
32 | ClientCredential target = new ClientCredential(clientId, clientSecret);
33 | assertEquals(clientId, target.getClientId());
34 | assertEquals(clientSecret, target.getClientSecret());
35 | }
36 |
37 | }
38 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/spi/servlet/DummyDataHandlerFactoryImpl.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import java.util.Date;
22 |
23 | import jp.eisbahn.oauth2.server.data.DataHandler;
24 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
25 | import jp.eisbahn.oauth2.server.models.AccessToken;
26 | import jp.eisbahn.oauth2.server.models.AuthInfo;
27 | import jp.eisbahn.oauth2.server.models.Request;
28 |
29 | public class DummyDataHandlerFactoryImpl implements DataHandlerFactory {
30 |
31 | @Override
32 | public DataHandler create(Request request) {
33 | return new DummyDataHandler(request);
34 | }
35 |
36 | private static class DummyDataHandler extends DataHandler {
37 |
38 | public DummyDataHandler(Request request) {
39 | super(request);
40 | }
41 |
42 | @Override
43 | public boolean validateClient(String clientId, String clientSecret,
44 | String grantType) {
45 | return true;
46 | }
47 |
48 | @Override
49 | public String getUserId(String username, String password) {
50 | return null;
51 | }
52 |
53 | @Override
54 | public AuthInfo createOrUpdateAuthInfo(String clientId, String userId,
55 | String scope) {
56 | return null;
57 | }
58 |
59 | @Override
60 | public AccessToken createOrUpdateAccessToken(AuthInfo authInfo) {
61 | AccessToken accessToken = new AccessToken();
62 | accessToken.setToken("accessToken1");
63 | accessToken.setExpiresIn(900L);
64 | return accessToken;
65 | }
66 |
67 | @Override
68 | public AuthInfo getAuthInfoByCode(String code) {
69 | AuthInfo authInfo = new AuthInfo();
70 | authInfo.setClientId("clientId1");
71 | authInfo.setRedirectUri("redirectUri1");
72 | authInfo.setRefreshToken("refreshToken1");
73 | authInfo.setScope("scope1");
74 | authInfo.setCode(code);
75 | return authInfo;
76 | }
77 |
78 | @Override
79 | public AuthInfo getAuthInfoByRefreshToken(String refreshToken) {
80 | return null;
81 | }
82 |
83 | @Override
84 | public String getClientUserId(String clientId, String clientSecret) {
85 | return null;
86 | }
87 |
88 | @Override
89 | public AccessToken getAccessToken(String token) {
90 | AccessToken accessToken = new AccessToken();
91 | accessToken.setCreatedOn(new Date());
92 | accessToken.setExpiresIn(3600);
93 | return accessToken;
94 | }
95 |
96 | @Override
97 | public AuthInfo getAuthInfoById(String id) {
98 | AuthInfo authInfo = new AuthInfo();
99 | authInfo.setClientId("clientId1");
100 | authInfo.setUserId("userId1");
101 | authInfo.setScope("scope1");
102 | return authInfo;
103 | }
104 |
105 | @Override
106 | public boolean validateClientById(String clientId) {
107 | return true;
108 | }
109 |
110 | @Override
111 | public boolean validateUserById(String userId) {
112 | return true;
113 | }
114 |
115 | }
116 |
117 | }
118 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/spi/servlet/HttpServletRequestAdapterTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import static org.junit.Assert.*;
22 | import static org.easymock.EasyMock.*;
23 |
24 | import java.util.HashMap;
25 | import java.util.Map;
26 |
27 | import javax.servlet.http.HttpServletRequest;
28 |
29 | import org.junit.Test;
30 |
31 | public class HttpServletRequestAdapterTest {
32 |
33 | @Test
34 | public void test() {
35 | HttpServletRequest request = createMock(HttpServletRequest.class);
36 | expect(request.getParameter("name1")).andReturn("value1");
37 | expect(request.getHeader("name2")).andReturn("value2");
38 | @SuppressWarnings("serial")
39 | Map map = new HashMap() {
40 | {
41 | put("k1", "v1");
42 | put("k2", "v2");
43 | }
44 | };
45 | expect(request.getParameterMap()).andReturn(map);
46 | replay(request);
47 | HttpServletRequestAdapter target = new HttpServletRequestAdapter(request);
48 | assertEquals("value1", target.getParameter("name1"));
49 | assertEquals("value2", target.getHeader("name2"));
50 | Map parameterMap = target.getParameterMap();
51 | assertEquals(2, parameterMap.size());
52 | assertEquals("v1", parameterMap.get("k1"));
53 | assertEquals("v2", parameterMap.get("k2"));
54 | verify(request);
55 | }
56 |
57 | }
58 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/spi/servlet/ProtectedResourceFilterTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.easymock.EasyMock.verify;
25 | import static org.junit.Assert.fail;
26 |
27 | import javax.servlet.FilterChain;
28 | import javax.servlet.FilterConfig;
29 | import javax.servlet.ServletException;
30 | import javax.servlet.ServletRequest;
31 | import javax.servlet.ServletResponse;
32 | import javax.servlet.http.HttpServletRequest;
33 | import javax.servlet.http.HttpServletResponse;
34 |
35 | import org.junit.Test;
36 |
37 | import jp.eisbahn.oauth2.server.data.DataHandler;
38 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
39 | import jp.eisbahn.oauth2.server.models.Request;
40 |
41 | public class ProtectedResourceFilterTest {
42 |
43 | @Test
44 | public void testSuccess() throws Exception {
45 | HttpServletRequest request = createMock(HttpServletRequest.class);
46 | expect(request.getHeader("Authorization")).andReturn("Bearer accessToken1").times(2);
47 | request.setAttribute("client_id", "clientId1");
48 | request.setAttribute("remote_user", "userId1");
49 | request.setAttribute("scope", "scope1");
50 | HttpServletResponse response = createMock(HttpServletResponse.class);
51 | FilterConfig config = createMock(FilterConfig.class);
52 | FilterChain chain = createMock(FilterChain.class);
53 | chain.doFilter(request, response);
54 | expect(config.getInitParameter("dataHandlerFactory"))
55 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
56 | expect(config.getInitParameter("accessTokenFetcherProvider")).andReturn(null);
57 | replay(request, response, config, chain);
58 | ProtectedResourceFilter target = new ProtectedResourceFilter();
59 | target.init(config);
60 | target.doFilter(request, response, chain);
61 | target.destroy();
62 | verify(request, response, config, chain);
63 | }
64 |
65 | @Test
66 | public void testSuccessExplicitAccessTokenFetcherProvider() throws Exception {
67 | HttpServletRequest request = createMock(HttpServletRequest.class);
68 | expect(request.getHeader("Authorization")).andReturn("Bearer accessToken1").times(2);
69 | request.setAttribute("client_id", "clientId1");
70 | request.setAttribute("remote_user", "userId1");
71 | request.setAttribute("scope", "scope1");
72 | HttpServletResponse response = createMock(HttpServletResponse.class);
73 | FilterConfig config = createMock(FilterConfig.class);
74 | FilterChain chain = createMock(FilterChain.class);
75 | chain.doFilter(request, response);
76 | expect(config.getInitParameter("dataHandlerFactory"))
77 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
78 | expect(config.getInitParameter("accessTokenFetcherProvider")).andReturn(
79 | "jp.eisbahn.oauth2.server.fetcher.accesstoken.impl.DefaultAccessTokenFetcherProvider");
80 | replay(request, response, config, chain);
81 | ProtectedResourceFilter target = new ProtectedResourceFilter();
82 | target.init(config);
83 | target.doFilter(request, response, chain);
84 | target.destroy();
85 | verify(request, response, config, chain);
86 | }
87 |
88 | @Test
89 | public void testFailed() throws Exception {
90 | HttpServletRequest request = createMock(HttpServletRequest.class);
91 | expect(request.getHeader("Authorization")).andReturn(null);
92 | expect(request.getParameter("oauth_token")).andReturn(null);
93 | expect(request.getParameter("access_token")).andReturn(null);
94 | HttpServletResponse response = createMock(HttpServletResponse.class);
95 | response.setStatus(400);
96 | response.setHeader("WWW-Authenticate",
97 | "Bearer error=\"invalid_request\", "
98 | + "error_description=\"Access token was not specified.\"");
99 | FilterConfig config = createMock(FilterConfig.class);
100 | FilterChain chain = createMock(FilterChain.class);
101 | expect(config.getInitParameter("dataHandlerFactory"))
102 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
103 | expect(config.getInitParameter("accessTokenFetcherProvider")).andReturn(null);
104 | replay(request, response, config, chain);
105 | ProtectedResourceFilter target = new ProtectedResourceFilter();
106 | target.init(config);
107 | target.doFilter(request, response, chain);
108 | target.destroy();
109 | verify(request, response, config, chain);
110 | }
111 |
112 | @Test
113 | public void testClassNotFound() throws Exception {
114 | FilterConfig config = createMock(FilterConfig.class);
115 | expect(config.getInitParameter("dataHandlerFactory")).andReturn("evil");
116 | replay(config);
117 |
118 | ProtectedResourceFilter target = new ProtectedResourceFilter();
119 | try {
120 | target.init(config);
121 | fail("ServletException not occurred.");
122 | } catch (ServletException e) {
123 | }
124 | verify(config);
125 | }
126 |
127 | @Test
128 | public void testIllegalAccessException() throws Exception {
129 | FilterConfig config = createMock(FilterConfig.class);
130 | expect(config.getInitParameter("dataHandlerFactory")).andReturn(
131 | EvilDataHandlerFactory.class.getName());
132 | replay(config);
133 |
134 | ProtectedResourceFilter target = new ProtectedResourceFilter();
135 | try {
136 | target.init(config);
137 | fail("ServletException not occurred.");
138 | } catch (ServletException e) {
139 | }
140 | verify(config);
141 | }
142 |
143 | @Test
144 | public void testInstantiationException() throws Exception {
145 | FilterConfig config = createMock(FilterConfig.class);
146 | expect(config.getInitParameter("dataHandlerFactory")).andReturn(
147 | DataHandlerFactory.class.getName());
148 | replay(config);
149 |
150 | ProtectedResourceFilter target = new ProtectedResourceFilter();
151 | try {
152 | target.init(config);
153 | fail("ServletException not occurred.");
154 | } catch (ServletException e) {
155 | }
156 | verify(config);
157 | }
158 |
159 | @Test
160 | public void testRequestNotHttpServletRequest() throws Exception {
161 | ServletRequest request = createMock(ServletRequest.class);
162 | replay(request);
163 | ProtectedResourceFilter target = new ProtectedResourceFilter();
164 | try {
165 | target.doFilter(request, null, null);
166 | fail("ServletException not occurred.");
167 | } catch (ServletException e) {
168 | }
169 | verify(request);
170 | }
171 |
172 | @Test
173 | public void testResponseNotHttpServletResponse() throws Exception {
174 | HttpServletRequest request = createMock(HttpServletRequest.class);
175 | expect(request.getHeader("Authorization")).andReturn(null);
176 | expect(request.getParameter("oauth_token")).andReturn(null);
177 | expect(request.getParameter("access_token")).andReturn(null);
178 | ServletResponse response = createMock(ServletResponse.class);
179 | FilterConfig config = createMock(FilterConfig.class);
180 | FilterChain chain = createMock(FilterChain.class);
181 | expect(config.getInitParameter("dataHandlerFactory"))
182 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
183 | expect(config.getInitParameter("accessTokenFetcherProvider")).andReturn(null);
184 | replay(request, response, config, chain);
185 | ProtectedResourceFilter target = new ProtectedResourceFilter();
186 | target.init(config);
187 | try {
188 | target.doFilter(request, response, chain);
189 | fail("ServletException not occurred.");
190 | } catch (ServletException e) {
191 | }
192 | target.destroy();
193 | verify(request, response, config, chain);
194 | }
195 |
196 | public static class EvilDataHandlerFactory implements DataHandlerFactory {
197 |
198 | private EvilDataHandlerFactory() {
199 | }
200 |
201 | @Override
202 | public DataHandler create(Request request) {
203 | return null;
204 | }
205 |
206 | }
207 |
208 | }
209 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/spi/servlet/TokenServletTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.spi.servlet;
20 |
21 | import static org.easymock.EasyMock.createMock;
22 | import static org.easymock.EasyMock.expect;
23 | import static org.easymock.EasyMock.replay;
24 | import static org.easymock.EasyMock.verify;
25 | import static org.junit.Assert.fail;
26 |
27 | import java.io.PrintWriter;
28 |
29 | import javax.servlet.ServletConfig;
30 | import javax.servlet.ServletException;
31 | import javax.servlet.http.HttpServletRequest;
32 | import javax.servlet.http.HttpServletResponse;
33 |
34 | import jp.eisbahn.oauth2.server.data.DataHandler;
35 | import jp.eisbahn.oauth2.server.data.DataHandlerFactory;
36 | import jp.eisbahn.oauth2.server.models.Request;
37 |
38 | import org.junit.Test;
39 |
40 | public class TokenServletTest {
41 |
42 | @Test
43 | public void testSimple() throws Exception {
44 | HttpServletRequest request = createMock(HttpServletRequest.class);
45 | expect(request.getParameter("grant_type")).andReturn("authorization_code");
46 | expect(request.getHeader("Authorization")).andReturn("Bearer accessToken1").times(2);
47 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
48 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
49 | expect(request.getParameter("code")).andReturn("code1");
50 | expect(request.getParameter("redirect_uri")).andReturn("redirectUri1");
51 | PrintWriter writer = createMock(PrintWriter.class);
52 | writer.write("{\"token_type\":\"Bearer\",\"access_token\":\"accessToken1\",\"refresh_token\":\"refreshToken1\",\"expires_in\":900,\"scope\":\"scope1\"}");
53 | writer.flush();
54 | HttpServletResponse response = createMock(HttpServletResponse.class);
55 | response.setStatus(200);
56 | response.setContentType("application/json; charset=UTF-8");
57 | expect(response.getWriter()).andReturn(writer);
58 | ServletConfig config = createMock(ServletConfig.class);
59 | expect(config.getInitParameter("dataHandlerFactory"))
60 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
61 | expect(config.getInitParameter("grantHandlerProvider")).andReturn(null);
62 | expect(config.getInitParameter("clientCredentialFetcher")).andReturn(null);
63 | replay(request, response, config, writer);
64 |
65 | TokenServlet target = new TokenServlet();
66 | target.init(config);
67 | target.doPost(request, response);
68 |
69 | verify(request, response, config, writer);
70 | }
71 |
72 | @Test
73 | public void testSimpleWithExplicitDefaultGrantHandler() throws Exception {
74 | HttpServletRequest request = createMock(HttpServletRequest.class);
75 | expect(request.getParameter("grant_type")).andReturn("authorization_code");
76 | expect(request.getHeader("Authorization")).andReturn("Bearer accessToken1").times(2);
77 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
78 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
79 | expect(request.getParameter("code")).andReturn("code1");
80 | expect(request.getParameter("redirect_uri")).andReturn("redirectUri1");
81 | PrintWriter writer = createMock(PrintWriter.class);
82 | writer.write("{\"token_type\":\"Bearer\",\"access_token\":\"accessToken1\",\"refresh_token\":\"refreshToken1\",\"expires_in\":900,\"scope\":\"scope1\"}");
83 | writer.flush();
84 | HttpServletResponse response = createMock(HttpServletResponse.class);
85 | response.setStatus(200);
86 | response.setContentType("application/json; charset=UTF-8");
87 | expect(response.getWriter()).andReturn(writer);
88 | ServletConfig config = createMock(ServletConfig.class);
89 | expect(config.getInitParameter("dataHandlerFactory"))
90 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
91 | expect(config.getInitParameter("grantHandlerProvider")).andReturn(
92 | "jp.eisbahn.oauth2.server.granttype.impl.DefaultGrantHandlerProvider");
93 | expect(config.getInitParameter("clientCredentialFetcher")).andReturn(null);
94 | replay(request, response, config, writer);
95 |
96 | TokenServlet target = new TokenServlet();
97 | target.init(config);
98 | target.doPost(request, response);
99 |
100 | verify(request, response, config, writer);
101 | }
102 |
103 | @Test
104 | public void testSimpleWithExplicitClientCredentialFetcher() throws Exception {
105 | HttpServletRequest request = createMock(HttpServletRequest.class);
106 | expect(request.getParameter("grant_type")).andReturn("authorization_code");
107 | expect(request.getHeader("Authorization")).andReturn("Bearer accessToken1").times(2);
108 | expect(request.getParameter("client_id")).andReturn("clientId1").times(2);
109 | expect(request.getParameter("client_secret")).andReturn("clientSecret1").times(2);
110 | expect(request.getParameter("code")).andReturn("code1");
111 | expect(request.getParameter("redirect_uri")).andReturn("redirectUri1");
112 | PrintWriter writer = createMock(PrintWriter.class);
113 | writer.write("{\"token_type\":\"Bearer\",\"access_token\":\"accessToken1\",\"refresh_token\":\"refreshToken1\",\"expires_in\":900,\"scope\":\"scope1\"}");
114 | writer.flush();
115 | HttpServletResponse response = createMock(HttpServletResponse.class);
116 | response.setStatus(200);
117 | response.setContentType("application/json; charset=UTF-8");
118 | expect(response.getWriter()).andReturn(writer);
119 | ServletConfig config = createMock(ServletConfig.class);
120 | expect(config.getInitParameter("dataHandlerFactory"))
121 | .andReturn("jp.eisbahn.oauth2.server.spi.servlet.DummyDataHandlerFactoryImpl");
122 | expect(config.getInitParameter("grantHandlerProvider")).andReturn(
123 | "jp.eisbahn.oauth2.server.granttype.impl.DefaultGrantHandlerProvider");
124 | expect(config.getInitParameter("clientCredentialFetcher")).andReturn(
125 | "jp.eisbahn.oauth2.server.fetcher.clientcredential.ClientCredentialFetcherImpl");
126 | replay(request, response, config, writer);
127 |
128 | TokenServlet target = new TokenServlet();
129 | target.init(config);
130 | target.doPost(request, response);
131 |
132 | verify(request, response, config, writer);
133 | }
134 |
135 | @Test
136 | public void testClassNotFound() throws Exception {
137 | ServletConfig config = createMock(ServletConfig.class);
138 | expect(config.getInitParameter("dataHandlerFactory")).andReturn("evil");
139 | replay(config);
140 |
141 | TokenServlet target = new TokenServlet();
142 | try {
143 | target.init(config);
144 | fail("ServletException not occurred.");
145 | } catch(ServletException e) {
146 | }
147 | verify(config);
148 | }
149 |
150 | @Test
151 | public void testIllegalAccessException() throws Exception {
152 | ServletConfig config = createMock(ServletConfig.class);
153 | expect(config.getInitParameter("dataHandlerFactory")).andReturn(
154 | EvilDataHandlerFactory.class.getName());
155 | replay(config);
156 |
157 | TokenServlet target = new TokenServlet();
158 | try {
159 | target.init(config);
160 | fail("ServletException not occurred.");
161 | } catch(ServletException e) {
162 | }
163 | verify(config);
164 | }
165 |
166 | @Test
167 | public void testInstantiationException() throws Exception {
168 | ServletConfig config = createMock(ServletConfig.class);
169 | expect(config.getInitParameter("dataHandlerFactory")).andReturn(
170 | DataHandlerFactory.class.getName());
171 | replay(config);
172 |
173 | TokenServlet target = new TokenServlet();
174 | try {
175 | target.init(config);
176 | fail("ServletException not occurred.");
177 | } catch(ServletException e) {
178 | }
179 | verify(config);
180 | }
181 |
182 | public static class EvilDataHandlerFactory implements DataHandlerFactory {
183 |
184 | private EvilDataHandlerFactory() {
185 | }
186 |
187 | @Override
188 | public DataHandler create(Request request) {
189 | return null;
190 | }
191 |
192 | }
193 |
194 | }
195 |
--------------------------------------------------------------------------------
/src/test/java/jp/eisbahn/oauth2/server/utils/UtilTest.java:
--------------------------------------------------------------------------------
1 | /*
2 | * Licensed to the Apache Software Foundation (ASF) under one
3 | * or more contributor license agreements. See the NOTICE file
4 | * distributed with this work for additional information
5 | * regarding copyright ownership. The ASF licenses this file
6 | * to you under the Apache License, Version 2.0 (the
7 | * "License"); you may not use this file except in compliance
8 | * with the License. You may obtain a copy of the License at
9 | *
10 | * http://www.apache.org/licenses/LICENSE-2.0
11 | *
12 | * Unless required by applicable law or agreed to in writing,
13 | * software distributed under the License is distributed on an
14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 | * KIND, either express or implied. See the License for the
16 | * specific language governing permissions and limitations under the License.
17 | */
18 |
19 | package jp.eisbahn.oauth2.server.utils;
20 |
21 | import static org.junit.Assert.assertEquals;
22 | import jp.eisbahn.oauth2.server.utils.Util;
23 |
24 | import org.codehaus.jackson.annotate.JsonPropertyOrder;
25 | import org.junit.Test;
26 |
27 | public class UtilTest {
28 |
29 | @Test
30 | public void testDecodeParam() throws Exception {
31 | String source = "wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D";
32 | String result = Util.decodeParam(source);
33 | assertEquals("wOJIO9A2W5mFwDgiDvZbTSMK/PY=", result);
34 | }
35 |
36 | @Test
37 | public void testToJson() throws Exception {
38 | JsonTarget target = new JsonTarget();
39 | target.foo = "foo1";
40 | target.bar = "bar1";
41 | String json = Util.toJson(target);
42 | assertEquals("{\"foo\":\"foo1\",\"bar\":\"bar1\"}", json);
43 | }
44 |
45 | @JsonPropertyOrder({"foo", "bar"})
46 | private static class JsonTarget {
47 | @SuppressWarnings("unused")
48 | public String foo;
49 | @SuppressWarnings("unused")
50 | public String bar;
51 | }
52 |
53 | }
54 |
--------------------------------------------------------------------------------
/src/test/resources/applicationContext-protectedresource-scenario.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/src/test/resources/applicationContext-token-scenario.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
5 |
6 |
7 |
8 |
9 |
10 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
41 |
42 |
43 |
45 |
46 |
47 |
--------------------------------------------------------------------------------