├── docs
└── images
│ ├── user-attribute.png
│ ├── direct-grants-flow.png
│ ├── sample-api-postman.png
│ └── configure-direct-grant-flow.png
├── keycloak-api-key-core
├── Dockerfile
├── src
│ └── main
│ │ ├── resources
│ │ └── META-INF
│ │ │ ├── services
│ │ │ ├── org.keycloak.authentication.AuthenticatorFactory
│ │ │ └── org.keycloak.services.resource.RealmResourceProviderFactory
│ │ │ └── jboss-deployment-structure.xml
│ │ └── java
│ │ └── com
│ │ └── carbonrider
│ │ └── keycloak
│ │ ├── model
│ │ └── APIKey.java
│ │ ├── exception
│ │ ├── APIKeyException.java
│ │ ├── ErrorMessage.java
│ │ ├── InvalidAPIKeyException.java
│ │ ├── UserNotFoundException.java
│ │ ├── APIKeyNotConfiguredForUserException.java
│ │ ├── ExceptionResponseHandler.java
│ │ └── UnauthorizedAccessException.java
│ │ ├── api
│ │ ├── APIKeyEndpointResourceProvider.java
│ │ ├── APIKeyEndpointResourceFactory.java
│ │ └── APIKeyEndpointResource.java
│ │ ├── provider
│ │ ├── APIKeyAuthenticator.java
│ │ └── APIKeyAuthenticationProviderFactory.java
│ │ └── domain
│ │ └── APIKeyDomain.java
└── pom.xml
├── example-spring-keycloak
├── src
│ └── main
│ │ ├── resources
│ │ └── application.properties
│ │ └── java
│ │ └── com
│ │ └── carbonrider
│ │ └── keycloak
│ │ └── api
│ │ └── example
│ │ ├── controller
│ │ ├── HelloMessage.java
│ │ └── HelloController.java
│ │ ├── SpringKeycloakAPIApplication.java
│ │ └── configuration
│ │ └── ExampleConfiguration.java
└── pom.xml
├── .gitignore
├── pom.xml
├── keycloak-spring-api-key-adapter
├── src
│ └── main
│ │ └── java
│ │ └── com
│ │ └── carbonrider
│ │ └── keycloak
│ │ └── spring
│ │ ├── adapter
│ │ └── KeycloakAPIKeySecurityAdapter.java
│ │ └── filter
│ │ └── KeycloakAPIKeyProcessingFilter.java
└── pom.xml
├── README.md
└── LICENSE
/docs/images/user-attribute.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carbonrider/keycloak-api-key-module/HEAD/docs/images/user-attribute.png
--------------------------------------------------------------------------------
/docs/images/direct-grants-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carbonrider/keycloak-api-key-module/HEAD/docs/images/direct-grants-flow.png
--------------------------------------------------------------------------------
/docs/images/sample-api-postman.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carbonrider/keycloak-api-key-module/HEAD/docs/images/sample-api-postman.png
--------------------------------------------------------------------------------
/docs/images/configure-direct-grant-flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/carbonrider/keycloak-api-key-module/HEAD/docs/images/configure-direct-grant-flow.png
--------------------------------------------------------------------------------
/keycloak-api-key-core/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM jboss/keycloak:11.0.3
2 |
3 | COPY target/keycloak-api-key-core.jar /opt/jboss/keycloak/standalone/deployments/
4 |
5 | EXPOSE 8080
6 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/resources/META-INF/services/org.keycloak.authentication.AuthenticatorFactory:
--------------------------------------------------------------------------------
1 | com.carbonrider.keycloak.provider.APIKeyAuthenticationProviderFactory
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/resources/META-INF/services/org.keycloak.services.resource.RealmResourceProviderFactory:
--------------------------------------------------------------------------------
1 | com.carbonrider.keycloak.api.APIKeyEndpointResourceFactory
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/resources/META-INF/jboss-deployment-structure.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/example-spring-keycloak/src/main/resources/application.properties:
--------------------------------------------------------------------------------
1 | server.port=9080
2 | logging.level.com.carbonrider.keycloak.spring.filter=DEBUG
3 |
4 | keycloak.realm=api-test-realm
5 | keycloak.auth-server-url=http://localhost:8080/auth
6 | keycloak.resource=api-client
7 | keycloak.use-resource-role-mappings=true
8 | keycloak.bearer-only=true
9 | keycloak.ssl-required=external
10 |
--------------------------------------------------------------------------------
/example-spring-keycloak/src/main/java/com/carbonrider/keycloak/api/example/controller/HelloMessage.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api.example.controller;
2 |
3 | public class HelloMessage {
4 |
5 | private String message;
6 |
7 | public String getMessage() {
8 | return message;
9 | }
10 |
11 | public void setMessage(String message) {
12 | this.message = message;
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Compiled class file
2 | *.class
3 |
4 | # Log file
5 | *.log
6 |
7 | # BlueJ files
8 | *.ctxt
9 |
10 | # Mobile Tools for Java (J2ME)
11 | .mtj.tmp/
12 |
13 | # Package Files #
14 | *.jar
15 | *.war
16 | *.nar
17 | *.ear
18 | *.zip
19 | *.tar.gz
20 | *.rar
21 |
22 | # virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
23 | hs_err_pid*
24 |
25 | # Intellij Project files
26 | .idea
27 |
28 | target
29 |
30 | *.versionsBackup
--------------------------------------------------------------------------------
/example-spring-keycloak/src/main/java/com/carbonrider/keycloak/api/example/SpringKeycloakAPIApplication.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api.example;
2 |
3 | import org.springframework.boot.SpringApplication;
4 | import org.springframework.boot.autoconfigure.SpringBootApplication;
5 |
6 | @SpringBootApplication
7 | public class SpringKeycloakAPIApplication {
8 |
9 | public static void main(String[] args) {
10 | SpringApplication.run(SpringKeycloakAPIApplication.class, args);
11 | }
12 |
13 | }
14 |
--------------------------------------------------------------------------------
/example-spring-keycloak/src/main/java/com/carbonrider/keycloak/api/example/controller/HelloController.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api.example.controller;
2 |
3 | import org.springframework.web.bind.annotation.GetMapping;
4 | import org.springframework.web.bind.annotation.RestController;
5 |
6 | @RestController
7 | public class HelloController {
8 |
9 | @GetMapping(path = {"/hello"})
10 | public HelloMessage sayHello() {
11 |
12 | HelloMessage message = new HelloMessage();
13 | message.setMessage("hello there.");
14 | return message;
15 | }
16 | }
17 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/model/APIKey.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.model;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import java.util.UUID;
21 |
22 | /*
23 | * @author Yogesh Jadhav
24 | */
25 |
26 | public class APIKey {
27 |
28 | private UUID key;
29 |
30 | public UUID getKey() {
31 | return key;
32 | }
33 |
34 | public void setKey(UUID key) {
35 | this.key = key;
36 | }
37 | }
38 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/APIKeyException.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | /*
21 | * @author Yogesh Jadhav
22 | */
23 |
24 | public abstract class APIKeyException extends RuntimeException {
25 |
26 | protected APIKeyException(String message) {
27 | super(message);
28 | }
29 |
30 | protected APIKeyException() {
31 | super();
32 | }
33 |
34 | public abstract int getCode();
35 |
36 | public abstract ErrorMessage getFriendlyMessage();
37 | }
38 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/ErrorMessage.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | /*
21 | * @author Yogesh Jadhav
22 | */
23 |
24 | public class ErrorMessage {
25 |
26 | private String code;
27 |
28 | private String message;
29 |
30 | public ErrorMessage(String code, String message) {
31 | this.code = code;
32 | this.message = message;
33 | }
34 |
35 | public String getCode() {
36 | return code;
37 | }
38 |
39 | public void setCode(String code) {
40 | this.code = code;
41 | }
42 |
43 | public String getMessage() {
44 | return message;
45 | }
46 |
47 | public void setMessage(String message) {
48 | this.message = message;
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/api/APIKeyEndpointResourceProvider.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.keycloak.models.KeycloakSession;
21 | import org.keycloak.services.resource.RealmResourceProvider;
22 |
23 | /*
24 | * Resource provider for REST endpoint.
25 | * @author Yogesh Jadhav
26 | */
27 | public class APIKeyEndpointResourceProvider implements RealmResourceProvider {
28 |
29 | private final KeycloakSession session;
30 |
31 | public APIKeyEndpointResourceProvider(KeycloakSession session) {
32 | this.session = session;
33 | }
34 |
35 | @Override
36 | public Object getResource() {
37 | return new APIKeyEndpointResource(this.session);
38 | }
39 |
40 | @Override
41 | public void close() {
42 | }
43 | }
44 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/InvalidAPIKeyException.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | /*
21 | * @author Yogesh Jadhav
22 | */
23 |
24 | public class InvalidAPIKeyException extends APIKeyException {
25 |
26 | private static final int CODE = 400;
27 |
28 | private static final String INVALID_API_KEY = "Invalid api key {%s}";
29 |
30 | private final String apiKey;
31 |
32 | public InvalidAPIKeyException(String apiKey) {
33 | super(String.format(INVALID_API_KEY, apiKey));
34 | this.apiKey = apiKey;
35 | }
36 |
37 | public int getCode() {
38 | return CODE;
39 | }
40 |
41 | @Override
42 | public ErrorMessage getFriendlyMessage() {
43 | return new ErrorMessage("INVALID_API_KEY", this.toString());
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | return String.format(INVALID_API_KEY, apiKey);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/UserNotFoundException.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | /*
21 | * @author Yogesh Jadhav
22 | */
23 |
24 | public class UserNotFoundException extends APIKeyException {
25 |
26 | private static final int CODE = 400;
27 |
28 | private static final String USER_NOT_FOUND = "User not found {%s}";
29 |
30 | private final String userKey;
31 |
32 | public UserNotFoundException(String userKey) {
33 | super(String.format(USER_NOT_FOUND, userKey));
34 | this.userKey = userKey;
35 | }
36 |
37 | public int getCode() {
38 | return CODE;
39 | }
40 |
41 | @Override
42 | public ErrorMessage getFriendlyMessage() {
43 | return new ErrorMessage("USER_NOT_FOUND", this.toString());
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | return String.format(USER_NOT_FOUND, userKey);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 | com.carbonrider.keycloak
6 | keycloak-api-key-module
7 | 0.1.0
8 | keycloak-api-key-module
9 | pom
10 | Parent module for Keycloak API.
11 |
12 |
13 | 11
14 | 11.0.3
15 | 2.4.10
16 |
17 |
18 |
19 | example-spring-keycloak
20 | keycloak-api-key-core
21 | keycloak-spring-api-key-adapter
22 |
23 |
24 |
25 |
26 |
27 | org.keycloak
28 | keycloak-spring-boot-starter
29 | ${keycloak.version}
30 | provided
31 |
32 |
33 | org.springframework.boot
34 | spring-boot-starter-security
35 | ${spring.boot.version}
36 | provided
37 |
38 |
39 |
40 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/APIKeyNotConfiguredForUserException.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | /*
21 | * @author Yogesh Jadhav
22 | */
23 |
24 | public class APIKeyNotConfiguredForUserException extends APIKeyException {
25 |
26 | private static final int CODE = 400;
27 |
28 | private static final String API_KEY_NOT_CONFIGURED_FOR_USER = "API key not configured for user {%s}";
29 |
30 | private final String userKey;
31 |
32 | public APIKeyNotConfiguredForUserException(String userKey) {
33 | super(String.format(API_KEY_NOT_CONFIGURED_FOR_USER, userKey));
34 | this.userKey = userKey;
35 | }
36 |
37 | public int getCode() {
38 | return CODE;
39 | }
40 |
41 | @Override
42 | public ErrorMessage getFriendlyMessage() {
43 | return new ErrorMessage("API_KEY_NOT_CONFIGURED_FOR_USER", this.toString());
44 | }
45 |
46 | @Override
47 | public String toString() {
48 | return String.format(API_KEY_NOT_CONFIGURED_FOR_USER, userKey);
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/ExceptionResponseHandler.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.slf4j.Logger;
21 | import org.slf4j.LoggerFactory;
22 |
23 | import javax.ws.rs.core.Response;
24 |
25 | /*
26 | * @author Yogesh Jadhav
27 | */
28 |
29 | public class ExceptionResponseHandler {
30 |
31 | private static final Logger logger = LoggerFactory.getLogger(ExceptionResponseHandler.class);
32 |
33 | private ExceptionResponseHandler() {
34 | }
35 |
36 | public static Response handleException(Exception e) {
37 |
38 | if (logger.isErrorEnabled()) {
39 | logger.error("Request couldn't be served.", e);
40 | }
41 |
42 | if (e instanceof APIKeyException) {
43 | APIKeyException apiKeyException = (APIKeyException) e;
44 | return Response.status(apiKeyException.getCode()).entity(apiKeyException.getFriendlyMessage()).build();
45 | }
46 |
47 | return Response.status(400).entity(new ErrorMessage("SERVER_ERROR", e.getMessage())).build();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/exception/UnauthorizedAccessException.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.exception;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | /*
21 | * @author Yogesh Jadhav
22 | */
23 |
24 | public class UnauthorizedAccessException extends APIKeyException {
25 |
26 | private static final int CODE = 403;
27 |
28 | private static final String UNAUTHORISED = "Unauthorized access by {%s}";
29 |
30 | private final String subject;
31 |
32 | public UnauthorizedAccessException(String byWhom) {
33 | super(String.format(UNAUTHORISED, byWhom));
34 | this.subject = byWhom;
35 | }
36 |
37 | public UnauthorizedAccessException() {
38 | this("UNAUTHENTICATED");
39 | }
40 |
41 | @Override
42 | public int getCode() {
43 | return CODE;
44 | }
45 |
46 | @Override
47 | public ErrorMessage getFriendlyMessage() {
48 | return new ErrorMessage("UNAUTHORISED_ACCESS", this.toString());
49 | }
50 |
51 | @Override
52 | public String toString() {
53 | return String.format(UNAUTHORISED, this.subject);
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/api/APIKeyEndpointResourceFactory.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.keycloak.Config;
21 | import org.keycloak.models.KeycloakSession;
22 | import org.keycloak.models.KeycloakSessionFactory;
23 | import org.keycloak.services.resource.RealmResourceProvider;
24 | import org.keycloak.services.resource.RealmResourceProviderFactory;
25 |
26 | /*
27 | * Factory implementation for REST endpoint.
28 | * @author Yogesh Jadhav
29 | */
30 | public class APIKeyEndpointResourceFactory implements RealmResourceProviderFactory {
31 |
32 | private static final String ID = "carbonrider-keycloak-api-key";
33 |
34 | @Override
35 | public RealmResourceProvider create(KeycloakSession session) {
36 | return new APIKeyEndpointResourceProvider(session);
37 | }
38 |
39 | @Override
40 | public void init(Config.Scope scope) {
41 | }
42 |
43 | @Override
44 | public void postInit(KeycloakSessionFactory keycloakSessionFactory) {
45 | }
46 |
47 | @Override
48 | public void close() {
49 | }
50 |
51 | @Override
52 | public String getId() {
53 | return ID;
54 | }
55 | }
56 |
--------------------------------------------------------------------------------
/keycloak-spring-api-key-adapter/src/main/java/com/carbonrider/keycloak/spring/adapter/KeycloakAPIKeySecurityAdapter.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.spring.adapter;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 |
21 | import com.carbonrider.keycloak.spring.filter.KeycloakAPIKeyProcessingFilter;
22 | import org.keycloak.adapters.springsecurity.config.KeycloakWebSecurityConfigurerAdapter;
23 | import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
24 | import org.springframework.context.annotation.Bean;
25 | import org.springframework.security.core.session.SessionRegistryImpl;
26 | import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
27 | import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
28 |
29 | /*
30 | * An adapter to plug custom API Key processing filter.
31 | *
32 | * @author Yogesh Jadhav
33 | */
34 |
35 | public class KeycloakAPIKeySecurityAdapter extends KeycloakWebSecurityConfigurerAdapter {
36 |
37 | @Bean
38 | @Override
39 | protected KeycloakAuthenticationProcessingFilter keycloakAuthenticationProcessingFilter() throws Exception {
40 | KeycloakAPIKeyProcessingFilter filter = new KeycloakAPIKeyProcessingFilter(authenticationManagerBean());
41 | filter.setSessionAuthenticationStrategy(sessionAuthenticationStrategy());
42 | return filter;
43 | }
44 |
45 | @Override
46 | @Bean
47 | protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
48 | return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
49 | }
50 | }
51 |
--------------------------------------------------------------------------------
/example-spring-keycloak/src/main/java/com/carbonrider/keycloak/api/example/configuration/ExampleConfiguration.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api.example.configuration;
2 |
3 | import com.carbonrider.keycloak.spring.adapter.KeycloakAPIKeySecurityAdapter;
4 | import org.keycloak.adapters.KeycloakConfigResolver;
5 | import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
6 | import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
7 | import org.keycloak.adapters.springsecurity.KeycloakSecurityComponents;
8 | import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
9 | import org.springframework.beans.factory.annotation.Autowired;
10 | import org.springframework.context.annotation.Bean;
11 | import org.springframework.context.annotation.ComponentScan;
12 | import org.springframework.context.annotation.Configuration;
13 | import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
14 | import org.springframework.security.config.annotation.web.builders.HttpSecurity;
15 | import org.springframework.security.core.authority.mapping.SimpleAuthorityMapper;
16 | import org.springframework.security.core.session.SessionRegistryImpl;
17 | import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
18 | import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
19 |
20 | @Configuration
21 | @KeycloakConfiguration
22 | @ComponentScan(basePackageClasses = {KeycloakSecurityComponents.class})
23 | public class ExampleConfiguration extends KeycloakAPIKeySecurityAdapter {
24 |
25 | @Override
26 | protected void configure(HttpSecurity http) throws Exception {
27 | super.configure(http);
28 | http.csrf().disable().cors().and().authorizeRequests()
29 | .antMatchers("/**").authenticated();
30 | }
31 |
32 | @Autowired
33 | public void configureGlobal(AuthenticationManagerBuilder auth) {
34 | KeycloakAuthenticationProvider keycloakAuthenticationProvider = keycloakAuthenticationProvider();
35 | keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
36 | auth.authenticationProvider(keycloakAuthenticationProvider);
37 | }
38 |
39 | @Bean
40 | @Override
41 | protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
42 | return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
43 | }
44 |
45 | @Bean
46 | public KeycloakConfigResolver keycloakConfigResolver() {
47 | return new KeycloakSpringBootConfigResolver();
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/api/APIKeyEndpointResource.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.api;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import com.carbonrider.keycloak.domain.APIKeyDomain;
21 | import com.carbonrider.keycloak.exception.ExceptionResponseHandler;
22 | import com.carbonrider.keycloak.model.APIKey;
23 | import org.jboss.resteasy.spi.HttpRequest;
24 | import org.keycloak.models.KeycloakSession;
25 | import org.keycloak.services.resources.Cors;
26 |
27 | import javax.ws.rs.*;
28 | import javax.ws.rs.core.MediaType;
29 | import javax.ws.rs.core.Response;
30 |
31 | /*
32 | * REST endpoints for creating and deleting api key.
33 | *
34 | * @author Yogesh Jadhav
35 | */
36 |
37 | public class APIKeyEndpointResource {
38 |
39 | private final KeycloakSession session;
40 |
41 | private final APIKeyDomain apiKeyDomain;
42 |
43 | public APIKeyEndpointResource(KeycloakSession session) {
44 | this.session = session;
45 | this.apiKeyDomain = new APIKeyDomain(session);
46 | }
47 |
48 | @OPTIONS
49 | @Path("{any:.*}")
50 | public Response preflight() {
51 | HttpRequest httpRequest = this.session.getContext().getContextObject(HttpRequest.class);
52 | return Cors.add(httpRequest, Response.ok()).auth().preflight().build();
53 | }
54 |
55 | @POST
56 | @Path("/api-key")
57 | @Produces({MediaType.APPLICATION_JSON})
58 | public Response generateAPIKeyForUser(@QueryParam("userid") String userId) {
59 | try {
60 | APIKey apiKey = this.apiKeyDomain.generateAPIKeyForUser(userId);
61 | return Response.ok().entity(apiKey).build();
62 | } catch (Exception e) {
63 | return ExceptionResponseHandler.handleException(e);
64 | }
65 | }
66 |
67 | @DELETE
68 | @Path("/api-key")
69 | @Produces({MediaType.APPLICATION_JSON})
70 | public Response deleteAPIKeyForUser(@QueryParam("userid") String userId) {
71 | try {
72 | this.apiKeyDomain.deleteAPIKeyFromUser(userId);
73 | return Response.ok().build();
74 | } catch (Exception e) {
75 | return ExceptionResponseHandler.handleException(e);
76 | }
77 | }
78 | }
79 |
--------------------------------------------------------------------------------
/example-spring-keycloak/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 | com.carbonrider.keycloak
6 | example-spring-keycloak-api
7 | 0.1.0
8 | example-spring-keycloak-api
9 | jar
10 | Example application for Keycloak api key.
11 |
12 |
13 | com.carbonrider.keycloak
14 | keycloak-api-key-module
15 | 0.1.0
16 |
17 |
18 |
19 |
20 |
21 | org.springframework.boot
22 | spring-boot-maven-plugin
23 | ${spring.boot.version}
24 |
25 | true
26 |
27 |
28 |
29 | org.apache.maven.plugins
30 | maven-compiler-plugin
31 | 3.8.1
32 |
33 | ${java.version}
34 | ${java.version}
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 | org.springframework.boot
44 | spring-boot-starter-parent
45 | ${spring.boot.version}
46 | pom
47 | import
48 |
49 |
50 | org.keycloak.bom
51 | keycloak-adapter-bom
52 | ${keycloak.version}
53 | pom
54 | import
55 |
56 |
57 |
58 |
59 |
60 |
61 | org.springframework.boot
62 | spring-boot-starter-web
63 |
64 |
65 | org.keycloak
66 | keycloak-spring-boot-starter
67 |
68 |
69 | com.carbonrider.keycloak
70 | keycloak-spring-api-key-adapter
71 | 0.1.0
72 |
73 |
74 | org.springframework.boot
75 | spring-boot-starter-security
76 |
77 |
78 |
--------------------------------------------------------------------------------
/keycloak-spring-api-key-adapter/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 | com.carbonrider.keycloak
6 | keycloak-spring-api-key-adapter
7 | 0.1.0
8 | keycloak-spring-api-key-adapter
9 | jar
10 | Adapter to enable authentication using API key.
11 |
12 |
13 | com.carbonrider.keycloak
14 | keycloak-api-key-module
15 | 0.1.0
16 |
17 |
18 |
19 |
20 |
21 | org.keycloak
22 | keycloak-spring-boot-starter
23 | ${keycloak.version}
24 | provided
25 |
26 |
27 | org.springframework.boot
28 | spring-boot-starter-security
29 | ${spring.boot.version}
30 | provided
31 |
32 |
33 |
34 |
35 |
36 |
37 | org.keycloak
38 | keycloak-spring-boot-starter
39 |
40 |
41 | org.springframework.boot
42 | spring-boot-starter-security
43 |
44 |
45 |
46 |
47 | keycloak-spring-api-key-adapter
48 |
49 |
50 | org.apache.maven.plugins
51 | maven-compiler-plugin
52 | 3.8.1
53 |
54 | ${java.version}
55 | ${java.version}
56 |
57 |
58 |
59 | maven-assembly-plugin
60 |
61 |
62 | package
63 |
64 | single
65 |
66 |
67 |
68 |
69 | false
70 |
71 | jar-with-dependencies
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/provider/APIKeyAuthenticator.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.provider;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import com.carbonrider.keycloak.domain.APIKeyDomain;
21 | import org.keycloak.authentication.AuthenticationFlowContext;
22 | import org.keycloak.authentication.AuthenticationFlowError;
23 | import org.keycloak.authentication.AuthenticationFlowException;
24 | import org.keycloak.authentication.Authenticator;
25 | import org.keycloak.authentication.authenticators.browser.AbstractUsernameFormAuthenticator;
26 | import org.keycloak.models.KeycloakSession;
27 | import org.keycloak.models.RealmModel;
28 | import org.keycloak.models.UserModel;
29 |
30 | import java.util.List;
31 |
32 | /*
33 | * @author Yogesh Jadhav
34 | */
35 |
36 | public class APIKeyAuthenticator extends AbstractUsernameFormAuthenticator implements Authenticator {
37 |
38 | private final KeycloakSession session;
39 |
40 | public APIKeyAuthenticator(KeycloakSession session) {
41 | this.session = session;
42 | }
43 |
44 | @Override
45 | public void authenticate(AuthenticationFlowContext context) {
46 | List apiKeyCollection = context.getHttpRequest().getHttpHeaders().getRequestHeader(APIKeyDomain.API_KEY_HEADER_ATTRIBUTE);
47 | if (apiKeyCollection == null || apiKeyCollection.isEmpty()) {
48 | return;
49 | }
50 |
51 | String apiKey = apiKeyCollection.get(0);
52 |
53 | APIKeyDomain apiKeyDomain = new APIKeyDomain(this.session);
54 |
55 | UserModel user = apiKeyDomain.findUserFromKey(apiKey).orElseThrow(() -> new AuthenticationFlowException("Invalid api key", AuthenticationFlowError.INVALID_CREDENTIALS));
56 |
57 | if (!enabledUser(context, user)) {
58 | context.cancelLogin();
59 | return;
60 | }
61 |
62 | context.setUser(user);
63 | context.success();
64 | }
65 |
66 | @Override
67 | public void action(AuthenticationFlowContext authenticationFlowContext) {
68 | }
69 |
70 | @Override
71 | public boolean requiresUser() {
72 | return false;
73 | }
74 |
75 | @Override
76 | public boolean configuredFor(KeycloakSession keycloakSession, RealmModel realmModel, UserModel userModel) {
77 | return true;
78 | }
79 |
80 | @Override
81 | public void setRequiredActions(KeycloakSession keycloakSession, RealmModel realmModel, UserModel userModel) {
82 | }
83 |
84 | @Override
85 | public void close() {
86 | }
87 | }
88 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/provider/APIKeyAuthenticationProviderFactory.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.provider;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.keycloak.Config;
21 | import org.keycloak.authentication.Authenticator;
22 | import org.keycloak.authentication.AuthenticatorFactory;
23 | import org.keycloak.models.AuthenticationExecutionModel;
24 | import org.keycloak.models.KeycloakSession;
25 | import org.keycloak.models.KeycloakSessionFactory;
26 | import org.keycloak.provider.ProviderConfigProperty;
27 | import org.slf4j.Logger;
28 | import org.slf4j.LoggerFactory;
29 |
30 | import java.util.List;
31 |
32 | /*
33 | * @author Yogesh Jadhav
34 | */
35 |
36 | public class APIKeyAuthenticationProviderFactory implements AuthenticatorFactory {
37 |
38 | private static final String ID = "API-KEY-AUTHENTICATOR";
39 |
40 | private static final Logger logger = LoggerFactory.getLogger(APIKeyAuthenticationProviderFactory.class);
41 |
42 | protected static final AuthenticationExecutionModel.Requirement[] REQUIREMENT_CHOICES = {
43 | AuthenticationExecutionModel.Requirement.REQUIRED,
44 | AuthenticationExecutionModel.Requirement.ALTERNATIVE,
45 | AuthenticationExecutionModel.Requirement.DISABLED};
46 |
47 | @Override
48 | public String getDisplayType() {
49 | return "Carbonrider Keycloak API Key";
50 | }
51 |
52 | @Override
53 | public String getReferenceCategory() {
54 | return "APIKEY";
55 | }
56 |
57 | @Override
58 | public boolean isConfigurable() {
59 | return false;
60 | }
61 |
62 | @Override
63 | public AuthenticationExecutionModel.Requirement[] getRequirementChoices() {
64 | return REQUIREMENT_CHOICES;
65 | }
66 |
67 | @Override
68 | public boolean isUserSetupAllowed() {
69 | return false;
70 | }
71 |
72 | @Override
73 | public String getHelpText() {
74 | return "API key support";
75 | }
76 |
77 | @Override
78 | public List getConfigProperties() {
79 | return null;
80 | }
81 |
82 | @Override
83 | public Authenticator create(KeycloakSession keycloakSession) {
84 | return new APIKeyAuthenticator(keycloakSession);
85 | }
86 |
87 | @Override
88 | public void init(Config.Scope scope) {
89 | logger.debug("***API Key authentication***");
90 | }
91 |
92 | @Override
93 | public void postInit(KeycloakSessionFactory keycloakSessionFactory) {
94 | }
95 |
96 | @Override
97 | public void close() {
98 | }
99 |
100 | @Override
101 | public String getId() {
102 | return ID;
103 | }
104 | }
105 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # keycloak-api-key-module
2 |
3 | Keycloak doesn't natively support API key generation for Users. This project attempts to provide the feature of creating API key for users. The feature can be used with existing Spring boot project which has Bearer authentication enabled.
4 |
5 | ## Module structure
6 |
7 | The module has been divided into 3 main directories
8 |
9 | - **keycloak-api-key-core**: Keycloak plugin to enable API key generation for user and validation.
10 | - **example-spring-keycloak**: A sample spring boot application demonstrating how to use the adapter
11 | - **keycloak-spring-api-key-adapter**: An adapter to be included in Spring boot project. It reads API key (x-api-key) header from web request and passes that to Keycloak for validation.
12 |
13 | ## How to configure?
14 |
15 | To enable API key feature in a spring boot project refer to following steps.
16 |
17 | ### Build and Deploy Keycloak plugin
18 |
19 | - Execute `mvn package` command at the root directory. This will build all the modules and create deployable JAR files inside *keycloak-api-key-core* and *keycloak-spring-api-key-adapter*
20 | - Copy the JAR file from *keycloak-api-key-core/target/keycloak-api-key-core.jar* to */opt/jboss/keycloak/standalone/deployments/* directory to deploy the plugin (You will find a sample Docker file inside *keycloak-api-key-core*)
21 |
22 | ### Enable API Key adapter in Spring boot project
23 |
24 | To enable authentication via API key, copy the jar file from *keycloak-spring-api-key-adapter/target/keycloak-spring-api-key-adapter.jar* to your project lib directory.
25 |
26 | (The project artifacts are not yet available on Maven central repository and hence either jar or source code must be copied to project directory.)
27 |
28 | Refer to *com.carbonrider.keycloak.api.example.configuration.ExampleConfiguration.java* in **example-spring-keycloak** project to configure the adapter.
29 |
30 | ### Keycloak configuration
31 |
32 | You must have a client configured in Keycloak with **Direct grants access**.
33 |
34 | - Copy an existing authentication flow (**Direct Grant**) and add a new execution (**Carbonrider Keycloak API Key**).
35 |
36 | - Remove existing executions (Username validation, Password, Direct Grant - Conditional OTP). The new flow must have only one execution (**Carbonrider Keycloak API Key**).
37 | 
38 |
39 | - Go to **Bindings** tab and for *Direct Grant Flow* select the authentication flow created in prior step.
40 |
41 | 
42 |
43 | ## How to test?
44 |
45 | You can test the configuration by
46 |
47 | - By setting a custom attribute (**api-key**) for any user and initialize it with a value.
48 |
49 | 
50 |
51 | - Invoke a sample API from Postman with a request header as **x-api-key** with the value configured as above. You will find a sample Hello API in the **example-spring-keycloak** project.
52 |
53 | 
54 |
55 | ## How to enable API Key generation
56 | An API key can be genreated using built-in rest API available with the project.
57 | - Create a new role **api-key-generator** role at realm level.
58 | - Assign the role to a user (service account). This user will be used from your application to invoke Keycloak provided API.
59 | - Execute post request */api-key* with *userid* as query parameter (e.g. /api-key?userid=jim). Note that the invoking user must have **api-key-generator** role at realm level.
--------------------------------------------------------------------------------
/keycloak-api-key-core/pom.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 | 4.0.0
5 | com.carbonrider.keycloak
6 | keycloak-api-key-core
7 | 0.1.0
8 | keycloak-api-key-core
9 | jar
10 | To enable API key functionality in keycloak.
11 |
12 |
13 | com.carbonrider.keycloak
14 | keycloak-api-key-module
15 | 0.1.0
16 |
17 |
18 |
19 |
20 |
21 | org.keycloak
22 | keycloak-core
23 | ${keycloak.version}
24 | provided
25 |
26 |
27 | org.keycloak
28 | keycloak-server-spi
29 | provided
30 | ${keycloak.version}
31 |
32 |
33 | org.keycloak
34 | keycloak-server-spi-private
35 | provided
36 | ${keycloak.version}
37 |
38 |
39 | org.keycloak
40 | keycloak-services
41 | provided
42 | ${keycloak.version}
43 |
44 |
45 | org.keycloak
46 | keycloak-model-jpa
47 | ${keycloak.version}
48 | provided
49 |
50 |
51 |
52 |
53 |
54 |
55 | org.keycloak
56 | keycloak-core
57 |
58 |
59 | org.keycloak
60 | keycloak-server-spi
61 |
62 |
63 | org.keycloak
64 | keycloak-server-spi-private
65 |
66 |
67 | org.keycloak
68 | keycloak-services
69 |
70 |
71 | org.keycloak
72 | keycloak-model-jpa
73 |
74 |
75 |
76 |
77 | keycloak-api-key-core
78 |
79 |
80 | org.apache.maven.plugins
81 | maven-compiler-plugin
82 | 3.8.1
83 |
84 | ${java.version}
85 | ${java.version}
86 |
87 |
88 |
89 | maven-assembly-plugin
90 |
91 |
92 | package
93 |
94 | single
95 |
96 |
97 |
98 |
99 | false
100 |
101 | jar-with-dependencies
102 |
103 |
104 |
105 |
106 |
107 |
--------------------------------------------------------------------------------
/keycloak-api-key-core/src/main/java/com/carbonrider/keycloak/domain/APIKeyDomain.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.domain;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import com.carbonrider.keycloak.exception.APIKeyNotConfiguredForUserException;
21 | import com.carbonrider.keycloak.exception.UnauthorizedAccessException;
22 | import com.carbonrider.keycloak.exception.UserNotFoundException;
23 | import com.carbonrider.keycloak.model.APIKey;
24 | import org.keycloak.common.util.RandomString;
25 | import org.keycloak.connections.jpa.JpaConnectionProvider;
26 | import org.keycloak.models.KeycloakSession;
27 | import org.keycloak.models.RealmModel;
28 | import org.keycloak.models.UserModel;
29 | import org.keycloak.models.jpa.entities.UserAttributeEntity;
30 | import org.keycloak.models.jpa.entities.UserEntity;
31 | import org.keycloak.services.managers.AppAuthManager;
32 | import org.keycloak.services.managers.AuthenticationManager;
33 |
34 | import javax.persistence.EntityManager;
35 | import javax.persistence.Query;
36 | import javax.persistence.criteria.CriteriaBuilder;
37 | import javax.persistence.criteria.CriteriaQuery;
38 | import javax.persistence.criteria.Root;
39 | import java.util.List;
40 | import java.util.Optional;
41 | import java.util.UUID;
42 |
43 | /*
44 | * Contains implementation logic for generating and deleting API key.
45 | * @author Yogesh Jadhav
46 | */
47 | public class APIKeyDomain {
48 |
49 | public static final String API_KEY_ATTRIBUTE = "api-key";
50 |
51 | public static final String API_KEY_HEADER_ATTRIBUTE = "x-api-key";
52 |
53 | private final RandomString randomString;
54 |
55 | private final EntityManager entityManager;
56 |
57 | private final AuthenticationManager.AuthResult authResult;
58 |
59 | private final KeycloakSession session;
60 |
61 | public APIKeyDomain(KeycloakSession session) {
62 | this.session = session;
63 | this.randomString = new RandomString(50);
64 | this.entityManager = session.getProvider(JpaConnectionProvider.class).getEntityManager();
65 | this.authResult = new AppAuthManager().authenticateBearerToken(session);
66 | }
67 |
68 | private void checkAuthorisation() {
69 | if (authResult == null) {
70 | throw new UnauthorizedAccessException();
71 | }
72 |
73 | if (this.authResult.getToken().getRealmAccess() == null) {
74 | throw new UnauthorizedAccessException("NO_REALM_ACCESS");
75 | }
76 |
77 | boolean hasAccess = this.authResult.getToken().getRealmAccess().isUserInRole("api-key-generator");
78 |
79 | if (!hasAccess) {
80 | throw new UnauthorizedAccessException(this.authResult.getUser().getId());
81 | }
82 |
83 | }
84 |
85 | public APIKey generateAPIKeyForUser(String userId) {
86 |
87 | checkAuthorisation();
88 |
89 | String randomAPIKey = this.randomString.nextString();
90 | UserEntity user = this.entityManager.find(UserEntity.class, userId);
91 | if (user == null) {
92 | throw new UserNotFoundException(userId);
93 | }
94 |
95 | UserAttributeEntity apiKeyAttribute = new UserAttributeEntity();
96 | apiKeyAttribute.setUser(user);
97 | apiKeyAttribute.setName(API_KEY_ATTRIBUTE);
98 | apiKeyAttribute.setValue(randomAPIKey);
99 |
100 | UUID apiKey = UUID.randomUUID();
101 | apiKeyAttribute.setId(apiKey.toString());
102 |
103 | this.entityManager.persist(apiKeyAttribute);
104 |
105 | APIKey key = new APIKey();
106 | key.setKey(apiKey);
107 |
108 | return key;
109 | }
110 |
111 |
112 | public void deleteAPIKeyFromUser(String userId) {
113 | checkAuthorisation();
114 |
115 | UserEntity user = this.entityManager.find(UserEntity.class, userId);
116 | if (user == null) {
117 | throw new UserNotFoundException(userId);
118 | }
119 |
120 | CriteriaBuilder cb = this.entityManager.getCriteriaBuilder();
121 | CriteriaQuery query = cb.createQuery(UserAttributeEntity.class);
122 | Root item = query.from(UserAttributeEntity.class);
123 | query.select(item).where(
124 | cb.and(
125 | cb.equal(item.get("user"), user),
126 | cb.equal(item.get("name"), API_KEY_ATTRIBUTE)
127 | )
128 | );
129 |
130 | Query apiAttributeQuery = this.entityManager.createQuery(query);
131 | List apiAttributes = apiAttributeQuery.getResultList();
132 | if (apiAttributes == null || apiAttributes.isEmpty()) {
133 | throw new APIKeyNotConfiguredForUserException(userId);
134 | } else {
135 | this.entityManager.remove(apiAttributes.get(0));
136 | }
137 | }
138 |
139 | public Optional findUserFromKey(String apiKey) {
140 |
141 | RealmModel realm = this.session.getContext().getRealm();
142 |
143 | List users = this.session.userStorageManager().searchForUserByUserAttribute(API_KEY_ATTRIBUTE, apiKey, realm);
144 |
145 | if(users.isEmpty()) {
146 | return Optional.empty();
147 | }
148 |
149 | return Optional.of(users.get(0));
150 | }
151 | }
152 |
--------------------------------------------------------------------------------
/keycloak-spring-api-key-adapter/src/main/java/com/carbonrider/keycloak/spring/filter/KeycloakAPIKeyProcessingFilter.java:
--------------------------------------------------------------------------------
1 | package com.carbonrider.keycloak.spring.filter;
2 |
3 | /*
4 | * Copyright 2022 Carbonrider.com and/or its affiliates
5 | * and other contributors as mentioned in author tags.
6 | *
7 | * Licensed under the Apache License, Version 2.0 (the "License");
8 | * you may not use this file except in compliance with the License.
9 | * You may obtain a copy of the License at
10 | *
11 | * http://www.apache.org/licenses/LICENSE-2.0
12 | *
13 | * Unless required by applicable law or agreed to in writing, software
14 | * distributed under the License is distributed on an "AS IS" BASIS,
15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 | * See the License for the specific language governing permissions and
17 | * limitations under the License.
18 | */
19 |
20 | import org.apache.http.HttpEntity;
21 | import org.apache.http.HttpResponse;
22 | import org.apache.http.NameValuePair;
23 | import org.apache.http.client.entity.UrlEncodedFormEntity;
24 | import org.apache.http.client.methods.HttpPost;
25 | import org.apache.http.message.BasicNameValuePair;
26 | import org.keycloak.KeycloakPrincipal;
27 | import org.keycloak.OAuth2Constants;
28 | import org.keycloak.adapters.*;
29 | import org.keycloak.adapters.rotation.AdapterTokenVerifier;
30 | import org.keycloak.adapters.spi.AuthChallenge;
31 | import org.keycloak.adapters.spi.HttpFacade;
32 | import org.keycloak.adapters.spi.KeycloakAccount;
33 | import org.keycloak.adapters.springsecurity.KeycloakAuthenticationException;
34 | import org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount;
35 | import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationEntryPoint;
36 | import org.keycloak.adapters.springsecurity.authentication.RequestAuthenticatorFactory;
37 | import org.keycloak.adapters.springsecurity.authentication.SpringSecurityRequestAuthenticatorFactory;
38 | import org.keycloak.adapters.springsecurity.facade.SimpleHttpFacade;
39 | import org.keycloak.adapters.springsecurity.filter.AdapterStateCookieRequestMatcher;
40 | import org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter;
41 | import org.keycloak.adapters.springsecurity.filter.QueryParamPresenceRequestMatcher;
42 | import org.keycloak.adapters.springsecurity.token.AdapterTokenStoreFactory;
43 | import org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken;
44 | import org.keycloak.adapters.springsecurity.token.SpringSecurityAdapterTokenStoreFactory;
45 | import org.keycloak.common.VerificationException;
46 | import org.keycloak.representations.AccessToken;
47 | import org.keycloak.representations.AccessTokenResponse;
48 | import org.keycloak.util.JsonSerialization;
49 | import org.slf4j.Logger;
50 | import org.slf4j.LoggerFactory;
51 | import org.springframework.beans.BeansException;
52 | import org.springframework.context.ApplicationContext;
53 | import org.springframework.context.ApplicationContextAware;
54 | import org.springframework.security.authentication.AuthenticationManager;
55 | import org.springframework.security.authentication.AuthenticationServiceException;
56 | import org.springframework.security.authentication.BadCredentialsException;
57 | import org.springframework.security.core.Authentication;
58 | import org.springframework.security.core.AuthenticationException;
59 | import org.springframework.security.core.context.SecurityContext;
60 | import org.springframework.security.core.context.SecurityContextHolder;
61 | import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
62 | import org.springframework.security.web.util.matcher.OrRequestMatcher;
63 | import org.springframework.security.web.util.matcher.RequestHeaderRequestMatcher;
64 | import org.springframework.security.web.util.matcher.RequestMatcher;
65 |
66 | import javax.servlet.ServletException;
67 | import javax.servlet.http.HttpServletRequest;
68 | import javax.servlet.http.HttpServletResponse;
69 | import java.io.ByteArrayOutputStream;
70 | import java.io.IOException;
71 | import java.io.InputStream;
72 | import java.util.ArrayList;
73 | import java.util.List;
74 | import java.util.Set;
75 |
76 | /*
77 | * Custom filter to check presence of "x-api-key" header.
78 | * The filter falls back to default Bearer Authentication
79 | * in case the header is not present.
80 | *
81 | * @author Yogesh Jadhav
82 | */
83 | public class KeycloakAPIKeyProcessingFilter extends KeycloakAuthenticationProcessingFilter implements ApplicationContextAware {
84 |
85 | private static final Logger logger = LoggerFactory.getLogger(KeycloakAPIKeyProcessingFilter.class);
86 |
87 | private static final String API_KEY_HEADER = "x-api-key";
88 |
89 | public static final RequestMatcher API_KEY_REQUEST_MATCHER =
90 | new OrRequestMatcher(
91 | new AntPathRequestMatcher(KeycloakAuthenticationEntryPoint.DEFAULT_LOGIN_URI),
92 | new RequestHeaderRequestMatcher(AUTHORIZATION_HEADER),
93 | new RequestHeaderRequestMatcher(API_KEY_HEADER),
94 | new QueryParamPresenceRequestMatcher(OAuth2Constants.ACCESS_TOKEN),
95 | new AdapterStateCookieRequestMatcher()
96 | );
97 |
98 |
99 | private final AdapterTokenStoreFactory adapterTokenStoreFactory = new SpringSecurityAdapterTokenStoreFactory();
100 |
101 | private final RequestAuthenticatorFactory requestAuthenticatorFactory = new SpringSecurityRequestAuthenticatorFactory();
102 |
103 | private AdapterDeploymentContext adapterDeploymentContext;
104 |
105 | private ApplicationContext applicationContext;
106 |
107 | private final AuthenticationManager authenticationManager;
108 |
109 | public KeycloakAPIKeyProcessingFilter(AuthenticationManager authenticationManager) {
110 | super(authenticationManager, API_KEY_REQUEST_MATCHER);
111 | this.authenticationManager = authenticationManager;
112 | }
113 |
114 | @Override
115 | public void afterPropertiesSet() {
116 | adapterDeploymentContext = applicationContext.getBean(AdapterDeploymentContext.class);
117 | super.afterPropertiesSet();
118 | }
119 |
120 | @Override
121 | public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
122 | super.setApplicationContext(applicationContext);
123 | this.applicationContext = applicationContext;
124 | }
125 |
126 | @Override
127 | public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
128 | String apiKey = request.getHeader(API_KEY_HEADER);
129 |
130 | if (request.getAttribute(KeycloakAPIKeyProcessingFilter.class.getName()) != null) {
131 | return (Authentication) request.getAttribute(KeycloakAPIKeyProcessingFilter.class.getName());
132 | }
133 |
134 | if (apiKey == null) {
135 | return super.attemptAuthentication(request, response);
136 | } else {
137 |
138 | logger.info("Attempting authentication using API key");
139 |
140 | HttpFacade facade = new SimpleHttpFacade(request, response);
141 |
142 | KeycloakDeployment deployment = adapterDeploymentContext.resolveDeployment(facade);
143 |
144 | deployment.setDelegateBearerErrorResponseSending(true);
145 |
146 | AdapterTokenStore tokenStore = adapterTokenStoreFactory.createAdapterTokenStore(deployment, request, response);
147 |
148 |
149 | logger.debug("Token URL {}", deployment.getTokenUrl());
150 |
151 | RequestAuthenticator authenticator
152 | = requestAuthenticatorFactory.createRequestAuthenticator(facade, request, deployment, tokenStore, -1);
153 |
154 | AccessTokenResponse result = validateAPIKey(deployment, apiKey);
155 |
156 | logger.debug("Authentication outcome {}", result);
157 |
158 | if (result == null) {
159 | AuthChallenge challenge = authenticator.getChallenge();
160 | if (challenge != null) {
161 | challenge.challenge(facade);
162 | }
163 | throw new KeycloakAuthenticationException("Invalid API key, please set valid value for x-api-key header");
164 | } else {
165 | try {
166 | AccessToken token = AdapterTokenVerifier.verifyToken(result.getToken(), deployment);
167 | RefreshableKeycloakSecurityContext session = new RefreshableKeycloakSecurityContext(deployment, null, result.getToken(), token, null, null, null);
168 | final KeycloakPrincipal principal = new KeycloakPrincipal<>(
169 | AdapterUtils.getPrincipalName(deployment, token), session);
170 |
171 | RefreshableKeycloakSecurityContext securityContext = principal.getKeycloakSecurityContext();
172 | Set roles = AdapterUtils.getRolesFromSecurityContext(securityContext);
173 | final KeycloakAccount account = new SimpleKeycloakAccount(principal, roles, securityContext);
174 |
175 | SecurityContext context = SecurityContextHolder.createEmptyContext();
176 | context.setAuthentication(new KeycloakAuthenticationToken(account, false));
177 | SecurityContextHolder.setContext(context);
178 |
179 | } catch (VerificationException e) {
180 | throw new RuntimeException(e);
181 | }
182 |
183 |
184 | Authentication auth = authenticationManager.authenticate(SecurityContextHolder.getContext().getAuthentication());
185 | request.setAttribute(KeycloakAPIKeyProcessingFilter.class.getName(), auth);
186 | return auth;
187 | }
188 | }
189 | }
190 |
191 | private AccessTokenResponse validateAPIKey(KeycloakDeployment deployment, String apiKey) throws AuthenticationException, IOException {
192 | HttpPost post = new HttpPost(deployment.getTokenUrl());
193 |
194 | List params = new ArrayList<>();
195 | params.add(new BasicNameValuePair("grant_type", "password"));
196 | params.add(new BasicNameValuePair("client_id", deployment.getResourceName()));
197 |
198 | //For validation add dummy fields.
199 | params.add(new BasicNameValuePair("username", "dummy"));
200 | params.add(new BasicNameValuePair("password", "dummy"));
201 | post.setEntity(new UrlEncodedFormEntity(params));
202 |
203 | post.addHeader(API_KEY_HEADER, apiKey);
204 |
205 | HttpResponse response = deployment.getClient().execute(post);
206 |
207 | int status = response.getStatusLine().getStatusCode();
208 | HttpEntity entity = response.getEntity();
209 |
210 | if (status != 200) {
211 | throw new BadCredentialsException("API Key is invalid");
212 | }
213 |
214 | if (entity == null) {
215 | throw new AuthenticationServiceException("Didn't receive expected response from Keycloak API validation.");
216 | }
217 |
218 | InputStream is = entity.getContent();
219 |
220 | ByteArrayOutputStream os = new ByteArrayOutputStream();
221 | int c;
222 | while ((c = is.read()) != -1) {
223 | os.write(c);
224 | }
225 | byte[] bytes = os.toByteArray();
226 | String json = new String(bytes);
227 |
228 | return JsonSerialization.readValue(json, AccessTokenResponse.class);
229 |
230 | }
231 | }
232 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 |
2 | Apache License
3 | Version 2.0, January 2004
4 | http://www.apache.org/licenses/
5 |
6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7 |
8 | 1. Definitions.
9 |
10 | "License" shall mean the terms and conditions for use, reproduction,
11 | and distribution as defined by Sections 1 through 9 of this document.
12 |
13 | "Licensor" shall mean the copyright owner or entity authorized by
14 | the copyright owner that is granting the License.
15 |
16 | "Legal Entity" shall mean the union of the acting entity and all
17 | other entities that control, are controlled by, or are under common
18 | control with that entity. For the purposes of this definition,
19 | "control" means (i) the power, direct or indirect, to cause the
20 | direction or management of such entity, whether by contract or
21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
22 | outstanding shares, or (iii) beneficial ownership of such entity.
23 |
24 | "You" (or "Your") shall mean an individual or Legal Entity
25 | exercising permissions granted by this License.
26 |
27 | "Source" form shall mean the preferred form for making modifications,
28 | including but not limited to software source code, documentation
29 | source, and configuration files.
30 |
31 | "Object" form shall mean any form resulting from mechanical
32 | transformation or translation of a Source form, including but
33 | not limited to compiled object code, generated documentation,
34 | and conversions to other media types.
35 |
36 | "Work" shall mean the work of authorship, whether in Source or
37 | Object form, made available under the License, as indicated by a
38 | copyright notice that is included in or attached to the work
39 | (an example is provided in the Appendix below).
40 |
41 | "Derivative Works" shall mean any work, whether in Source or Object
42 | form, that is based on (or derived from) the Work and for which the
43 | editorial revisions, annotations, elaborations, or other modifications
44 | represent, as a whole, an original work of authorship. For the purposes
45 | of this License, Derivative Works shall not include works that remain
46 | separable from, or merely link (or bind by name) to the interfaces of,
47 | the Work and Derivative Works thereof.
48 |
49 | "Contribution" shall mean any work of authorship, including
50 | the original version of the Work and any modifications or additions
51 | to that Work or Derivative Works thereof, that is intentionally
52 | submitted to Licensor for inclusion in the Work by the copyright owner
53 | or by an individual or Legal Entity authorized to submit on behalf of
54 | the copyright owner. For the purposes of this definition, "submitted"
55 | means any form of electronic, verbal, or written communication sent
56 | to the Licensor or its representatives, including but not limited to
57 | communication on electronic mailing lists, source code control systems,
58 | and issue tracking systems that are managed by, or on behalf of, the
59 | Licensor for the purpose of discussing and improving the Work, but
60 | excluding communication that is conspicuously marked or otherwise
61 | designated in writing by the copyright owner as "Not a Contribution."
62 |
63 | "Contributor" shall mean Licensor and any individual or Legal Entity
64 | on behalf of whom a Contribution has been received by Licensor and
65 | subsequently incorporated within the Work.
66 |
67 | 2. Grant of Copyright License. Subject to the terms and conditions of
68 | this License, each Contributor hereby grants to You a perpetual,
69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70 | copyright license to reproduce, prepare Derivative Works of,
71 | publicly display, publicly perform, sublicense, and distribute the
72 | Work and such Derivative Works in Source or Object form.
73 |
74 | 3. Grant of Patent License. Subject to the terms and conditions of
75 | this License, each Contributor hereby grants to You a perpetual,
76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77 | (except as stated in this section) patent license to make, have made,
78 | use, offer to sell, sell, import, and otherwise transfer the Work,
79 | where such license applies only to those patent claims licensable
80 | by such Contributor that are necessarily infringed by their
81 | Contribution(s) alone or by combination of their Contribution(s)
82 | with the Work to which such Contribution(s) was submitted. If You
83 | institute patent litigation against any entity (including a
84 | cross-claim or counterclaim in a lawsuit) alleging that the Work
85 | or a Contribution incorporated within the Work constitutes direct
86 | or contributory patent infringement, then any patent licenses
87 | granted to You under this License for that Work shall terminate
88 | as of the date such litigation is filed.
89 |
90 | 4. Redistribution. You may reproduce and distribute copies of the
91 | Work or Derivative Works thereof in any medium, with or without
92 | modifications, and in Source or Object form, provided that You
93 | meet the following conditions:
94 |
95 | (a) You must give any other recipients of the Work or
96 | Derivative Works a copy of this License; and
97 |
98 | (b) You must cause any modified files to carry prominent notices
99 | stating that You changed the files; and
100 |
101 | (c) You must retain, in the Source form of any Derivative Works
102 | that You distribute, all copyright, patent, trademark, and
103 | attribution notices from the Source form of the Work,
104 | excluding those notices that do not pertain to any part of
105 | the Derivative Works; and
106 |
107 | (d) If the Work includes a "NOTICE" text file as part of its
108 | distribution, then any Derivative Works that You distribute must
109 | include a readable copy of the attribution notices contained
110 | within such NOTICE file, excluding those notices that do not
111 | pertain to any part of the Derivative Works, in at least one
112 | of the following places: within a NOTICE text file distributed
113 | as part of the Derivative Works; within the Source form or
114 | documentation, if provided along with the Derivative Works; or,
115 | within a display generated by the Derivative Works, if and
116 | wherever such third-party notices normally appear. The contents
117 | of the NOTICE file are for informational purposes only and
118 | do not modify the License. You may add Your own attribution
119 | notices within Derivative Works that You distribute, alongside
120 | or as an addendum to the NOTICE text from the Work, provided
121 | that such additional attribution notices cannot be construed
122 | as modifying the License.
123 |
124 | You may add Your own copyright statement to Your modifications and
125 | may provide additional or different license terms and conditions
126 | for use, reproduction, or distribution of Your modifications, or
127 | for any such Derivative Works as a whole, provided Your use,
128 | reproduction, and distribution of the Work otherwise complies with
129 | the conditions stated in this License.
130 |
131 | 5. Submission of Contributions. Unless You explicitly state otherwise,
132 | any Contribution intentionally submitted for inclusion in the Work
133 | by You to the Licensor shall be under the terms and conditions of
134 | this License, without any additional terms or conditions.
135 | Notwithstanding the above, nothing herein shall supersede or modify
136 | the terms of any separate license agreement you may have executed
137 | with Licensor regarding such Contributions.
138 |
139 | 6. Trademarks. This License does not grant permission to use the trade
140 | names, trademarks, service marks, or product names of the Licensor,
141 | except as required for reasonable and customary use in describing the
142 | origin of the Work and reproducing the content of the NOTICE file.
143 |
144 | 7. Disclaimer of Warranty. Unless required by applicable law or
145 | agreed to in writing, Licensor provides the Work (and each
146 | Contributor provides its Contributions) on an "AS IS" BASIS,
147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148 | implied, including, without limitation, any warranties or conditions
149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150 | PARTICULAR PURPOSE. You are solely responsible for determining the
151 | appropriateness of using or redistributing the Work and assume any
152 | risks associated with Your exercise of permissions under this License.
153 |
154 | 8. Limitation of Liability. In no event and under no legal theory,
155 | whether in tort (including negligence), contract, or otherwise,
156 | unless required by applicable law (such as deliberate and grossly
157 | negligent acts) or agreed to in writing, shall any Contributor be
158 | liable to You for damages, including any direct, indirect, special,
159 | incidental, or consequential damages of any character arising as a
160 | result of this License or out of the use or inability to use the
161 | Work (including but not limited to damages for loss of goodwill,
162 | work stoppage, computer failure or malfunction, or any and all
163 | other commercial damages or losses), even if such Contributor
164 | has been advised of the possibility of such damages.
165 |
166 | 9. Accepting Warranty or Additional Liability. While redistributing
167 | the Work or Derivative Works thereof, You may choose to offer,
168 | and charge a fee for, acceptance of support, warranty, indemnity,
169 | or other liability obligations and/or rights consistent with this
170 | License. However, in accepting such obligations, You may act only
171 | on Your own behalf and on Your sole responsibility, not on behalf
172 | of any other Contributor, and only if You agree to indemnify,
173 | defend, and hold each Contributor harmless for any liability
174 | incurred by, or claims asserted against, such Contributor by reason
175 | of your accepting any such warranty or additional liability.
176 |
177 | END OF TERMS AND CONDITIONS
178 |
179 | APPENDIX: How to apply the Apache License to your work.
180 |
181 | To apply the Apache License to your work, attach the following
182 | boilerplate notice, with the fields enclosed by brackets "[]"
183 | replaced with your own identifying information. (Don't include
184 | the brackets!) The text should be enclosed in the appropriate
185 | comment syntax for the file format. We also recommend that a
186 | file or class name and description of purpose be included on the
187 | same "printed page" as the copyright notice for easier
188 | identification within third-party archives.
189 |
190 | Copyright [yyyy] [name of copyright owner]
191 |
192 | Licensed under the Apache License, Version 2.0 (the "License");
193 | you may not use this file except in compliance with the License.
194 | You may obtain a copy of the License at
195 |
196 | http://www.apache.org/licenses/LICENSE-2.0
197 |
198 | Unless required by applicable law or agreed to in writing, software
199 | distributed under the License is distributed on an "AS IS" BASIS,
200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201 | See the License for the specific language governing permissions and
202 | limitations under the License.
203 |
--------------------------------------------------------------------------------