├── .gitignore ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ └── org │ └── whispersystems │ └── dropwizard │ └── simpleauth │ ├── AuthDynamicFeature.java │ ├── AuthFilter.java │ ├── AuthPrincipal.java │ ├── AuthSecurityContext.java │ ├── AuthValueFactoryProvider.java │ ├── Authenticator.java │ ├── BasicCredentialAuthFilter.java │ └── WebApplicationExceptionCatchingFilter.java └── test └── java └── org └── whispersystems └── dropwizard └── simpleauth ├── AuthDynamicFeatureTest.java └── BasicCredentialAuthFilterTest.java /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | *.iml 3 | .idea 4 | -------------------------------------------------------------------------------- /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 2010-2013 Coda Hale and Yammer, Inc., 2014-2015 Dropwizard Team 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. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # dropwizard-simpleauth 2 | 3 | A Dropwizard library that lets you use simple `@Auth` annotations for authenticating multiple 4 | types, without having to deal with `@RolesAllowed` style authorizations. 5 | 6 | Install from maven central: 7 | 8 | ``` 9 | 10 | org.whispersystems 11 | dropwizard-simpleauth 12 | ${latest_version} 13 | 14 | ``` 15 | 16 | ## The details 17 | 18 | This library allows writing an authenticated Dropwizard resource to look like this: 19 | 20 | ``` 21 | @Path("/api/v1/mail") 22 | public class MailResource { 23 | 24 | @Timed 25 | @POST 26 | @Path("/{destination}/") 27 | @Consumes(MediaType.APPLICATION_JSON_TYPE) 28 | public void sendMessage(@Auth User sender, 29 | @PathParam("destination") String destination, 30 | @Valid Message message) 31 | { 32 | ... 33 | } 34 | 35 | @Timed 36 | @DELETE 37 | @Path("/{messageId}/") 38 | public void sendMessage(@Auth Admin admin, 39 | @PathParam("messageId") long messageId) 40 | { 41 | ... 42 | } 43 | 44 | 45 | } 46 | ``` 47 | 48 | No "authorization" tags like `@AllowAll`, `@DenyAll`, `@RolesAllowed` are used. Instead, 49 | the `@Auth` tag allows you to authenticate multiple different "principal" types (in this example 50 | both `User` and `Admin`), neither of which have to extend `Principal`. 51 | 52 | ## Registering authenticators 53 | 54 | To support authenticating multiple types, register multiple `AuthFilter`s: 55 | 56 | ````` 57 | @Override 58 | public void run(ExampleConfiguration configuration, 59 | Environment environment) 60 | { 61 | environment.jersey().register(new AuthDynamicFeature( 62 | new BasicCredentialAuthFilter.Builder() 63 | .setAuthenticator(new UserAuthenticator()) 64 | .setPrincipal(User.class) 65 | .buildAuthFilter(), 66 | new BasicCredentialAuthFilter.Builder() 67 | .setAuthenticator(new AdminAuthenticator()) 68 | .setPrincipal(Admin.class) 69 | .buildAuthFilter())); 70 | 71 | environment.jersey().register(new AuthValueFactoryProvider.Binder()); 72 | } 73 | ````` 74 | 75 | That's it! -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 4.0.0 7 | 8 | 9 | 3.0.0 10 | 11 | 12 | org.whispersystems 13 | dropwizard-simpleauth 14 | 0.4.0 15 | 16 | dropwizard-simpleauth 17 | A Dropwizard library for simple @Auth 18 | https://github.com/WhisperSystems/dropwizard-simpleauth 19 | 20 | 21 | 22 | Apache 23 | http://www.apache.org/licenses/LICENSE-2.0 24 | repo 25 | 26 | 27 | 28 | 29 | 30 | Moxie Marlinspike 31 | 32 | 33 | 34 | 35 | https://github.com/WhisperSystems/dropwizard-simpleauth 36 | scm:git:https://github.com/WhisperSystems/dropwizard-simpleauth.git 37 | scm:git:https://github.com/WhisperSystems/dropwizard-simpleauth.git 38 | 39 | 40 | 41 | 1.3.1 42 | 43 | 44 | 45 | 46 | io.dropwizard 47 | dropwizard-auth 48 | ${dropwizard.version} 49 | 50 | 51 | junit 52 | junit 53 | 4.12 54 | test 55 | 56 | 57 | org.mockito 58 | mockito-all 59 | 1.10.19 60 | test 61 | 62 | 63 | 64 | 65 | 66 | 67 | ossrh 68 | https://oss.sonatype.org/content/repositories/snapshots 69 | 70 | 71 | ossrh 72 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 73 | 74 | 75 | 76 | 77 | 78 | 79 | org.apache.maven.plugins 80 | maven-compiler-plugin 81 | 82 | 1.8 83 | 1.8 84 | 85 | 86 | 87 | org.apache.maven.plugins 88 | maven-source-plugin 89 | 2.2.1 90 | 91 | 92 | attach-sources 93 | 94 | jar 95 | 96 | 97 | 98 | 99 | 100 | org.apache.maven.plugins 101 | maven-javadoc-plugin 102 | 2.9.1 103 | 104 | 105 | attach-javadocs 106 | 107 | jar 108 | 109 | 110 | 111 | 112 | 113 | org.apache.maven.plugins 114 | maven-gpg-plugin 115 | 1.5 116 | 117 | 00B2CAB8 118 | 119 | 120 | 121 | sign-artifacts 122 | verify 123 | 124 | sign 125 | 126 | 127 | 128 | 129 | 130 | org.apache.maven.plugins 131 | maven-jar-plugin 132 | 2.4 133 | 134 | 135 | 136 | true 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/AuthDynamicFeature.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import org.glassfish.jersey.server.model.AnnotatedMethod; 4 | 5 | import javax.ws.rs.container.DynamicFeature; 6 | import javax.ws.rs.container.ResourceInfo; 7 | import javax.ws.rs.core.FeatureContext; 8 | import java.lang.annotation.Annotation; 9 | import java.lang.reflect.ParameterizedType; 10 | import java.lang.reflect.Type; 11 | import java.util.Optional; 12 | 13 | import io.dropwizard.auth.Auth; 14 | 15 | public class AuthDynamicFeature implements DynamicFeature { 16 | 17 | private AuthFilter[] authFilters; 18 | 19 | public AuthDynamicFeature(AuthFilter... authFilters) { 20 | this.authFilters = authFilters; 21 | } 22 | 23 | @Override 24 | public void configure(ResourceInfo resourceInfo, FeatureContext context) { 25 | AnnotatedMethod annotatedMethod = new AnnotatedMethod(resourceInfo.getResourceMethod()); 26 | Annotation[][] parameterAnnotations = annotatedMethod.getParameterAnnotations(); 27 | Class[] parameterTypes = annotatedMethod.getParameterTypes (); 28 | Type[] parameterGenericTypes = annotatedMethod.getGenericParameterTypes(); 29 | 30 | verifyAuthAnnotations(parameterAnnotations); 31 | 32 | for (int i=0;i 1) { 66 | throw new IllegalArgumentException("Only one @Auth tag supported per resource method!"); 67 | } 68 | } 69 | 70 | } 71 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/AuthFilter.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import com.google.common.base.Preconditions; 4 | 5 | import javax.annotation.Priority; 6 | import javax.ws.rs.Priorities; 7 | import javax.ws.rs.container.ContainerRequestFilter; 8 | 9 | import java.lang.reflect.Type; 10 | import java.util.Optional; 11 | 12 | import io.dropwizard.auth.DefaultUnauthorizedHandler; 13 | import io.dropwizard.auth.UnauthorizedHandler; 14 | 15 | @Priority(Priorities.AUTHENTICATION) 16 | public abstract class AuthFilter implements ContainerRequestFilter { 17 | 18 | protected String prefix; 19 | protected String realm; 20 | protected Authenticator authenticator; 21 | protected Class

principalType; 22 | protected UnauthorizedHandler unauthorizedHandler = new DefaultUnauthorizedHandler(); 23 | 24 | 25 | public boolean supports(Type clazz) { 26 | return clazz.equals(principalType); 27 | } 28 | 29 | /** 30 | * Abstract builder for auth filters. 31 | * 32 | * @param the type of credentials that the filter accepts 33 | * @param

the type of the principal that the filter accepts 34 | */ 35 | public abstract static class AuthFilterBuilder> { 36 | 37 | private String realm = "realm"; 38 | private String prefix = "Basic"; 39 | private Authenticator authenticator; 40 | private Class

principalType; 41 | 42 | /** 43 | * Sets the given realm 44 | * 45 | * @param realm a realm 46 | * @return the current builder 47 | */ 48 | public AuthFilterBuilder setRealm(String realm) { 49 | this.realm = realm; 50 | return this; 51 | } 52 | 53 | /** 54 | * Sets the given prefix 55 | * 56 | * @param prefix a prefix 57 | * @return the current builder 58 | */ 59 | public AuthFilterBuilder setPrefix(String prefix) { 60 | this.prefix = prefix; 61 | return this; 62 | } 63 | 64 | /** 65 | * Sets the given authenticator 66 | * 67 | * @param authenticator an {@link io.dropwizard.auth.Authenticator} 68 | * @return the current builder 69 | */ 70 | public AuthFilterBuilder setAuthenticator(Authenticator authenticator) { 71 | this.authenticator = authenticator; 72 | return this; 73 | } 74 | 75 | public AuthFilterBuilder setPrincipal(Class

principalType) { 76 | this.principalType = principalType; 77 | return this; 78 | } 79 | 80 | /** 81 | * Builds an instance of the filter with a provided authenticator, 82 | * an authorizer, a prefix, and a realm. 83 | * 84 | * @return a new instance of the filter 85 | */ 86 | public T buildAuthFilter() { 87 | Preconditions.checkArgument(realm != null, "Realm is not set"); 88 | Preconditions.checkArgument(prefix != null, "Prefix is not set"); 89 | Preconditions.checkArgument(authenticator != null, "Authenticator is not set"); 90 | 91 | T authFilter = newInstance(); 92 | authFilter.authenticator = authenticator; 93 | authFilter.prefix = prefix; 94 | authFilter.realm = realm; 95 | authFilter.principalType = principalType; 96 | return authFilter; 97 | } 98 | 99 | protected abstract T newInstance(); 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/AuthPrincipal.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import javax.security.auth.Subject; 4 | import java.security.Principal; 5 | 6 | public class AuthPrincipal implements Principal { 7 | 8 | private final Object authenticated; 9 | 10 | public AuthPrincipal(Object authenticated) { 11 | this.authenticated = authenticated; 12 | } 13 | 14 | @Override 15 | public String getName() { 16 | return null; 17 | } 18 | 19 | @Override 20 | public boolean implies(Subject subject) { 21 | return false; 22 | } 23 | 24 | public Object getAuthenticated() { 25 | return authenticated; 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/AuthSecurityContext.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import javax.ws.rs.core.SecurityContext; 4 | import java.security.Principal; 5 | 6 | public class AuthSecurityContext

implements SecurityContext { 7 | 8 | private final AuthPrincipal principal; 9 | private final boolean secure; 10 | 11 | public AuthSecurityContext(P principal, boolean secure) { 12 | this.principal = new AuthPrincipal(principal); 13 | this.secure = secure; 14 | } 15 | 16 | @Override 17 | public Principal getUserPrincipal() { 18 | return principal; 19 | } 20 | 21 | @Override 22 | public boolean isUserInRole(String role) { 23 | return false; 24 | } 25 | 26 | @Override 27 | public boolean isSecure() { 28 | return secure; 29 | } 30 | 31 | @Override 32 | public String getAuthenticationScheme() { 33 | return SecurityContext.BASIC_AUTH; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/AuthValueFactoryProvider.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import org.glassfish.hk2.api.InjectionResolver; 4 | import org.glassfish.hk2.api.ServiceLocator; 5 | import org.glassfish.hk2.api.TypeLiteral; 6 | import org.glassfish.hk2.utilities.binding.AbstractBinder; 7 | import org.glassfish.jersey.server.internal.inject.AbstractContainerRequestValueFactory; 8 | import org.glassfish.jersey.server.internal.inject.AbstractValueFactoryProvider; 9 | import org.glassfish.jersey.server.internal.inject.MultivaluedParameterExtractorProvider; 10 | import org.glassfish.jersey.server.internal.inject.ParamInjectionResolver; 11 | import org.glassfish.jersey.server.model.Parameter; 12 | import org.glassfish.jersey.server.spi.internal.ValueFactoryProvider; 13 | 14 | import javax.inject.Inject; 15 | import javax.inject.Singleton; 16 | import java.security.Principal; 17 | import java.util.Optional; 18 | 19 | import io.dropwizard.auth.Auth; 20 | 21 | @Singleton 22 | public class AuthValueFactoryProvider extends AbstractValueFactoryProvider { 23 | 24 | @Inject 25 | public AuthValueFactoryProvider(MultivaluedParameterExtractorProvider mpep, 26 | ServiceLocator injector) 27 | { 28 | super(mpep, injector, Parameter.Source.UNKNOWN); 29 | } 30 | 31 | @Override 32 | public AbstractContainerRequestValueFactory createValueFactory(final Parameter parameter) { 33 | if (parameter.getAnnotation(Auth.class) == null) { 34 | return null; 35 | } 36 | 37 | if (parameter.getRawType() == Optional.class) { 38 | return new OptionalContainerRequestValueFactory(parameter); 39 | } else { 40 | return new StandardContainerReqeustValueFactory(parameter); 41 | } 42 | } 43 | 44 | private static class StandardContainerReqeustValueFactory extends AbstractContainerRequestValueFactory { 45 | private final Parameter parameter; 46 | 47 | StandardContainerReqeustValueFactory(Parameter parameter) { 48 | this.parameter = parameter; 49 | } 50 | 51 | /** 52 | * @return {@link Principal} stored on the request, or {@code null} if no object was found. 53 | */ 54 | public Object provide() { 55 | Principal principal = getContainerRequest().getSecurityContext().getUserPrincipal(); 56 | 57 | if (principal == null) { 58 | throw new IllegalStateException("Cannot inject a custom principal into unauthenticated request"); 59 | } 60 | 61 | if (!(principal instanceof AuthPrincipal)) { 62 | throw new IllegalArgumentException("Cannot inject a non-AuthPrincipal into request"); 63 | } 64 | 65 | if (!parameter.getRawType().isAssignableFrom(((AuthPrincipal)principal).getAuthenticated().getClass())) { 66 | throw new IllegalArgumentException("Authenticated principal is of the wrong type!"); 67 | } 68 | 69 | return parameter.getRawType().cast(((AuthPrincipal) principal).getAuthenticated()); 70 | } 71 | } 72 | 73 | private static class OptionalContainerRequestValueFactory extends AbstractContainerRequestValueFactory { 74 | private final Parameter parameter; 75 | 76 | OptionalContainerRequestValueFactory(Parameter parameter) { 77 | this.parameter = parameter; 78 | } 79 | 80 | /** 81 | * @return {@link Principal} stored on the request, or {@code null} if no object was found. 82 | */ 83 | public Object provide() { 84 | Principal principal = getContainerRequest().getSecurityContext().getUserPrincipal(); 85 | 86 | if (principal != null && !(principal instanceof AuthPrincipal)) { 87 | throw new IllegalArgumentException("Cannot inject a non-AuthPrincipal into request"); 88 | } 89 | 90 | if (principal == null) return Optional.empty(); 91 | else return Optional.of(((AuthPrincipal)principal).getAuthenticated()); 92 | } 93 | } 94 | 95 | @Singleton 96 | private static class AuthInjectionResolver extends ParamInjectionResolver { 97 | 98 | /** 99 | * Create new {@link Auth} annotation injection resolver. 100 | */ 101 | public AuthInjectionResolver() { 102 | super(AuthValueFactoryProvider.class); 103 | } 104 | } 105 | 106 | /** 107 | * Injection binder for {@link AuthValueFactoryProvider} and {@link AuthInjectionResolver}. 108 | * 109 | */ 110 | public static class Binder extends AbstractBinder { 111 | 112 | public Binder() {} 113 | 114 | @Override 115 | protected void configure() { 116 | bind(AuthValueFactoryProvider.class).to(ValueFactoryProvider.class).in(Singleton.class); 117 | bind(AuthInjectionResolver.class).to(new TypeLiteral>() { 118 | }).in(Singleton.class); 119 | } 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/Authenticator.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | 4 | import java.util.Optional; 5 | 6 | import io.dropwizard.auth.AuthenticationException; 7 | 8 | /** 9 | * An interface for classes which authenticate user-provided credentials and return principal 10 | * objects. 11 | * 12 | * @param the type of credentials the authenticator can authenticate 13 | * @param

the type of principals the authenticator returns 14 | */ 15 | public interface Authenticator { 16 | /** 17 | * Given a set of user-provided credentials, return an optional principal. 18 | * 19 | * If the credentials are valid and map to a principal, returns an {@code Optional.of(p)}. 20 | * 21 | * If the credentials are invalid, returns an {@code Optional.absent()}. 22 | * 23 | * @param credentials a set of user-provided credentials 24 | * @return either an authenticated principal or an absent optional 25 | * @throws AuthenticationException if the credentials cannot be authenticated due to an 26 | * underlying error 27 | */ 28 | Optional

authenticate(C credentials) throws AuthenticationException; 29 | } -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/BasicCredentialAuthFilter.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import com.google.common.io.BaseEncoding; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | 7 | import javax.annotation.Priority; 8 | import javax.ws.rs.InternalServerErrorException; 9 | import javax.ws.rs.Priorities; 10 | import javax.ws.rs.WebApplicationException; 11 | import javax.ws.rs.container.ContainerRequestContext; 12 | import javax.ws.rs.core.HttpHeaders; 13 | import java.io.IOException; 14 | import java.nio.charset.StandardCharsets; 15 | import java.util.Optional; 16 | 17 | import io.dropwizard.auth.AuthenticationException; 18 | import io.dropwizard.auth.basic.BasicCredentials; 19 | 20 | @Priority(Priorities.AUTHENTICATION) 21 | public class BasicCredentialAuthFilter

extends AuthFilter { 22 | 23 | private static final Logger LOGGER = LoggerFactory.getLogger(BasicCredentialAuthFilter.class); 24 | 25 | private BasicCredentialAuthFilter() {} 26 | 27 | @Override 28 | public void filter(final ContainerRequestContext requestContext) throws IOException { 29 | final String header = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION); 30 | 31 | try { 32 | if (header != null) { 33 | final int space = header.indexOf(' '); 34 | if (space > 0) { 35 | final String method = header.substring(0, space); 36 | if (prefix.equalsIgnoreCase(method)) { 37 | final String decoded = new String( 38 | BaseEncoding.base64().decode(header.substring(space + 1)), 39 | StandardCharsets.UTF_8); 40 | final int i = decoded.indexOf(':'); 41 | if (i > 0) { 42 | final String username = decoded.substring(0, i); 43 | final String password = decoded.substring(i + 1); 44 | final BasicCredentials credentials = new BasicCredentials(username, password); 45 | try { 46 | Optional

principal = authenticator.authenticate(credentials); 47 | 48 | if (principal.isPresent()) { 49 | requestContext.setSecurityContext(new AuthSecurityContext

(principal.get(), false)); 50 | return; 51 | } 52 | } catch (AuthenticationException e) { 53 | LOGGER.warn("Error authenticating credentials", e); 54 | throw new InternalServerErrorException(); 55 | } 56 | } 57 | } 58 | } 59 | } 60 | } catch (IllegalArgumentException e) { 61 | LOGGER.warn("Error decoding credentials", e); 62 | } 63 | 64 | throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm)); 65 | } 66 | 67 | public static class Builder

extends AuthFilter.AuthFilterBuilder> { 68 | 69 | @Override 70 | protected BasicCredentialAuthFilter

newInstance() { 71 | return new BasicCredentialAuthFilter<>(); 72 | } 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/org/whispersystems/dropwizard/simpleauth/WebApplicationExceptionCatchingFilter.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import com.google.common.annotations.VisibleForTesting; 4 | import com.google.common.base.Preconditions; 5 | 6 | import java.io.IOException; 7 | 8 | import javax.annotation.Priority; 9 | import javax.ws.rs.Priorities; 10 | import javax.ws.rs.WebApplicationException; 11 | import javax.ws.rs.container.ContainerRequestContext; 12 | import javax.ws.rs.container.ContainerRequestFilter; 13 | 14 | /** 15 | * A {@link ContainerRequestFilter} decorator which catches any {@link 16 | * WebApplicationException WebApplicationExceptions} thrown by an 17 | * underlying {@code ContextRequestFilter}. 18 | */ 19 | @Priority(Priorities.AUTHENTICATION) 20 | class WebApplicationExceptionCatchingFilter implements ContainerRequestFilter { 21 | private final ContainerRequestFilter underlying; 22 | 23 | public WebApplicationExceptionCatchingFilter(ContainerRequestFilter underlying) { 24 | Preconditions.checkNotNull(underlying, "Underlying ContainerRequestFilter is not set"); 25 | this.underlying = underlying; 26 | } 27 | 28 | @Override 29 | public void filter(ContainerRequestContext requestContext) throws IOException { 30 | try { 31 | underlying.filter(requestContext); 32 | } catch (WebApplicationException err) { 33 | // Pass through. 34 | } 35 | } 36 | 37 | @VisibleForTesting 38 | ContainerRequestFilter getUnderlying() { 39 | return underlying; 40 | } 41 | } -------------------------------------------------------------------------------- /src/test/java/org/whispersystems/dropwizard/simpleauth/AuthDynamicFeatureTest.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | 4 | import org.junit.Test; 5 | import org.mockito.ArgumentCaptor; 6 | 7 | import javax.ws.rs.container.ContainerRequestFilter; 8 | import javax.ws.rs.container.ResourceInfo; 9 | import javax.ws.rs.core.FeatureContext; 10 | 11 | import java.util.Optional; 12 | 13 | import io.dropwizard.auth.Auth; 14 | import io.dropwizard.auth.AuthenticationException; 15 | import io.dropwizard.auth.basic.BasicCredentials; 16 | import static junit.framework.TestCase.assertEquals; 17 | import static junit.framework.TestCase.assertTrue; 18 | import static org.mockito.Mockito.*; 19 | 20 | public class AuthDynamicFeatureTest { 21 | 22 | @Test 23 | public void testPrincipalTypes() throws NoSuchMethodException { 24 | AuthFilter stringPrincipal = new BasicCredentialAuthFilter.Builder().setRealm("Hmm") 25 | .setPrincipal(String.class) 26 | .setAuthenticator(new StringAuthenticator()) 27 | .buildAuthFilter(); 28 | 29 | AuthFilter integerPrincipal = new BasicCredentialAuthFilter.Builder().setRealm("Hmm") 30 | .setPrincipal(Integer.class) 31 | .setAuthenticator(new IntegerAuthenticator()) 32 | .buildAuthFilter(); 33 | 34 | AuthDynamicFeature dynamicFeature = new AuthDynamicFeature(stringPrincipal, integerPrincipal); 35 | ResourceInfo resourceInfo = mock(ResourceInfo.class ); 36 | FeatureContext featureContext = mock(FeatureContext.class); 37 | 38 | when(resourceInfo.getResourceMethod()).thenReturn(MockMethod.class.getDeclaredMethod("stringAuthParam", String.class)); 39 | 40 | dynamicFeature.configure(resourceInfo, featureContext); 41 | verify(featureContext).register(eq(stringPrincipal)); 42 | reset(featureContext); 43 | 44 | when(resourceInfo.getResourceMethod()).thenReturn(MockMethod.class.getDeclaredMethod("integerAuthParam", Integer.class)); 45 | 46 | dynamicFeature.configure(resourceInfo, featureContext); 47 | verify(featureContext).register(eq(integerPrincipal)); 48 | reset(featureContext); 49 | 50 | when(resourceInfo.getResourceMethod()).thenReturn(MockMethod.class.getDeclaredMethod("optionalStringAuthParam", Optional.of("test").getClass())); 51 | 52 | dynamicFeature.configure(resourceInfo, featureContext); 53 | 54 | ArgumentCaptor stringOptionalCaptor = ArgumentCaptor.forClass(ContainerRequestFilter.class); 55 | verify(featureContext).register(stringOptionalCaptor.capture()); 56 | assertTrue(stringOptionalCaptor.getValue() instanceof WebApplicationExceptionCatchingFilter); 57 | assertEquals(((WebApplicationExceptionCatchingFilter)stringOptionalCaptor.getValue()).getUnderlying(), stringPrincipal); 58 | 59 | reset(featureContext); 60 | 61 | when(resourceInfo.getResourceMethod()).thenReturn(MockMethod.class.getDeclaredMethod("optionalIntegerAuthParam", Optional.of(1).getClass())); 62 | 63 | dynamicFeature.configure(resourceInfo, featureContext); 64 | 65 | ArgumentCaptor integerOptionalCaptor = ArgumentCaptor.forClass(ContainerRequestFilter.class); 66 | verify(featureContext, times(1)).register(integerOptionalCaptor.capture()); 67 | assertTrue(integerOptionalCaptor.getValue() instanceof WebApplicationExceptionCatchingFilter); 68 | assertEquals(((WebApplicationExceptionCatchingFilter)integerOptionalCaptor.getValue()).getUnderlying(), integerPrincipal); 69 | } 70 | 71 | @Test 72 | public void testMultipleAuthTags() throws NoSuchMethodException { 73 | AuthDynamicFeature dynamicFeature = new AuthDynamicFeature(new AuthFilter[0]); 74 | ResourceInfo resourceInfo = mock(ResourceInfo.class ); 75 | FeatureContext featureContext = mock(FeatureContext.class); 76 | 77 | when(resourceInfo.getResourceMethod()).thenReturn(MockMethod.class.getDeclaredMethod("multipleAuthParams", String.class, String.class)); 78 | 79 | try { 80 | dynamicFeature.configure(resourceInfo, featureContext); 81 | throw new AssertionError("Shouldn't support multiple auth tags!"); 82 | } catch (Exception e) { 83 | // Good 84 | } 85 | 86 | when(resourceInfo.getResourceMethod()).thenReturn(MockMethod.class.getDeclaredMethod("multipleOptionalAuthParams", Optional.of("foo").getClass(), Optional.of("bar").getClass())); 87 | 88 | try { 89 | dynamicFeature.configure(resourceInfo, featureContext); 90 | throw new AssertionError("Shouldn't support multiple auth tags!"); 91 | } catch (Exception e) { 92 | // Good 93 | } 94 | 95 | } 96 | 97 | @SuppressWarnings("OptionalUsedAsFieldOrParameterType") 98 | private static class MockMethod { 99 | public void multipleAuthParams(@Auth String foo, @Auth String bar) {} 100 | public void stringAuthParam(@Auth String foo) {} 101 | public void integerAuthParam(@Auth Integer bar) {} 102 | public void optionalStringAuthParam(@Auth Optional foo) {} 103 | public void optionalIntegerAuthParam(@Auth Optional bar) {} 104 | public void multipleOptionalAuthParams(@Auth Optional foo, @Auth Optional bar) {} 105 | } 106 | 107 | private static class StringAuthenticator implements Authenticator { 108 | @Override 109 | public Optional authenticate(BasicCredentials credentials) 110 | throws AuthenticationException 111 | { 112 | if (credentials.getUsername().equals("user") && 113 | credentials.getPassword().equals("password")) 114 | return Optional.of("user"); 115 | 116 | return Optional.empty(); 117 | } 118 | } 119 | 120 | private static class IntegerAuthenticator implements Authenticator { 121 | 122 | @Override 123 | public Optional authenticate(BasicCredentials credentials) throws AuthenticationException { 124 | return Optional.of(1); 125 | } 126 | } 127 | 128 | } 129 | -------------------------------------------------------------------------------- /src/test/java/org/whispersystems/dropwizard/simpleauth/BasicCredentialAuthFilterTest.java: -------------------------------------------------------------------------------- 1 | package org.whispersystems.dropwizard.simpleauth; 2 | 3 | import org.junit.Test; 4 | import org.mockito.ArgumentCaptor; 5 | 6 | import javax.ws.rs.WebApplicationException; 7 | import javax.ws.rs.container.ContainerRequestContext; 8 | import javax.ws.rs.core.HttpHeaders; 9 | import javax.ws.rs.core.MultivaluedHashMap; 10 | import javax.ws.rs.core.MultivaluedMap; 11 | import javax.ws.rs.core.SecurityContext; 12 | 13 | import java.io.IOException; 14 | import java.util.Optional; 15 | 16 | import io.dropwizard.auth.AuthenticationException; 17 | import io.dropwizard.auth.basic.BasicCredentials; 18 | import static org.junit.Assert.assertEquals; 19 | import static org.junit.Assert.assertTrue; 20 | import static org.mockito.Mockito.*; 21 | 22 | public class BasicCredentialAuthFilterTest { 23 | 24 | @Test 25 | public void testValidAuth() throws IOException { 26 | AuthFilter authFilter = new BasicCredentialAuthFilter.Builder().setAuthenticator(new StringAuthenticator()) 27 | .setPrincipal(String.class) 28 | .setRealm("Hmm") 29 | .buildAuthFilter(); 30 | 31 | MultivaluedMap headers = new MultivaluedHashMap() {{ 32 | add(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpmb28="); 33 | }}; 34 | 35 | ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class); 36 | when(containerRequestContext.getHeaders()).thenReturn(headers); 37 | 38 | authFilter.filter(containerRequestContext); 39 | 40 | ArgumentCaptor captor = ArgumentCaptor.forClass(SecurityContext.class); 41 | verify(containerRequestContext).setSecurityContext(captor.capture()); 42 | 43 | assertTrue(captor.getValue().getUserPrincipal() instanceof AuthPrincipal); 44 | assertEquals(((AuthPrincipal) captor.getValue().getUserPrincipal()).getAuthenticated(), "user"); 45 | } 46 | 47 | @Test 48 | public void testInvalidAuth() throws Exception { 49 | AuthFilter authFilter = new BasicCredentialAuthFilter.Builder().setAuthenticator(new StringAuthenticator()) 50 | .setPrincipal(String.class) 51 | .setRealm("Hmm") 52 | .buildAuthFilter(); 53 | 54 | MultivaluedMap headers = new MultivaluedHashMap() {{ 55 | add(HttpHeaders.AUTHORIZATION, "Basic dXNlcjpiYXo="); 56 | }}; 57 | 58 | ContainerRequestContext containerRequestContext = mock(ContainerRequestContext.class); 59 | when(containerRequestContext.getHeaders()).thenReturn(headers); 60 | 61 | try { 62 | authFilter.filter(containerRequestContext); 63 | throw new AssertionError("Shouldn't succeed"); 64 | } catch (WebApplicationException wae) { 65 | verify(containerRequestContext, times(0)).setSecurityContext(any(SecurityContext.class)); 66 | assertEquals(wae.getResponse().getStatus(), 401); 67 | } 68 | } 69 | 70 | 71 | private static class StringAuthenticator implements Authenticator { 72 | 73 | @Override 74 | public Optional authenticate(BasicCredentials credentials) throws AuthenticationException { 75 | if (credentials.getUsername().equals("user") && credentials.getPassword().equals("foo")) { 76 | return Optional.of("user"); 77 | } 78 | 79 | return Optional.empty(); 80 | } 81 | } 82 | } 83 | --------------------------------------------------------------------------------