@Override public boolean isUserInRole(String role) { return authorizer.authorize(principal.get(), role); }
@Override protected void configure() { bind(new PrincipalClassProvider<>(principalClass)).to(PrincipalClassProvider.class); bind(AuthValueFactoryProvider.class).to(ValueParamProvider.class).in(Singleton.class); } }
@Override protected void configure() { bind(new PrincipalClassSetProvider<>(principalClassSet)).to(PrincipalClassSetProvider.class); bind(PolymorphicAuthValueFactoryProvider.class).to(ValueParamProvider.class).in(Singleton.class); } }
@Override public void run(HelloWorldConfiguration configuration, Environment environment) { final PersonDAO dao = new PersonDAO(hibernateBundle.getSessionFactory()); final Template template = configuration.buildTemplate(); environment.healthChecks().register("template", new TemplateHealthCheck(template)); environment.admin().addTask(new EchoTask()); environment.jersey().register(DateRequiredFeature.class); environment.jersey().register(new AuthDynamicFeature(new BasicCredentialAuthFilter.Builder<User>() .setAuthenticator(new ExampleAuthenticator()) .setAuthorizer(new ExampleAuthorizer()) .setRealm("SUPER SECRET STUFF") .buildAuthFilter())); environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); environment.jersey().register(RolesAllowedDynamicFeature.class); environment.jersey().register(new HelloWorldResource(template)); environment.jersey().register(new ViewResource()); environment.jersey().register(new ProtectedResource()); environment.jersey().register(new PeopleResource(dao)); environment.jersey().register(new PersonResource(dao)); environment.jersey().register(new FilteredResource()); } }
@PermitAll @GET public String showSecret(@Auth User user) { return String.format("Hey there, %s. You know the secret! %d", user.getName(), user.getId()); }
/** * Creates a new cached authenticator. * * @param metricRegistry the application's registry of metrics * @param authenticator the underlying authenticator * @param builder a {@link Caffeine} */ public CachingAuthenticator(final MetricRegistry metricRegistry, final Authenticator<C, P> authenticator, final Caffeine<Object, Object> builder) { this.cacheMisses = metricRegistry.meter(name(authenticator.getClass(), "cache-misses")); this.gets = metricRegistry.timer(name(authenticator.getClass(), "gets")); this.cache = builder.recordStats().build(key -> { cacheMisses.mark(); final Optional<P> optPrincipal = authenticator.authenticate(key); if (!optPrincipal.isPresent()) { // Prevent caching of unknown credentials throw new InvalidCredentialsException(); } return optPrincipal; }); }
@Override public void filter(ContainerRequestContext requestContext) throws IOException { final BasicCredentials credentials = getCredentials(requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION)); if (!authenticate(requestContext, credentials, SecurityContext.BASIC_AUTH)) { throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm)); } }
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { String credentials = getCredentials(requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION)); // If Authorization header is not used, check query parameter where token can be passed as well if (credentials == null) { credentials = requestContext.getUriInfo().getQueryParameters().getFirst(OAUTH_ACCESS_TOKEN_PARAM); } if (!authenticate(requestContext, credentials, SecurityContext.BASIC_AUTH)) { throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm)); } }
@Override public Optional<P> authenticate(C credentials) throws AuthenticationException { try (Timer.Context context = gets.time()) { return cache.get(credentials); } catch (CompletionException e) { final Throwable cause = e.getCause(); if (cause instanceof InvalidCredentialsException) { return Optional.empty(); } if (cause instanceof AuthenticationException) { throw (AuthenticationException) cause; } throw new AuthenticationException(cause); } }
@Nullable @Override protected Function<ContainerRequest, ?> createValueProvider(Parameter parameter) { if (!parameter.isAnnotationPresent(Auth.class)) { return null; } else if (principalClass.equals(parameter.getRawType())) { return request -> new PrincipalContainerRequestValueFactory(request).provide(); } else { final boolean isOptionalPrincipal = parameter.getRawType() == Optional.class && ParameterizedType.class.isAssignableFrom(parameter.getType().getClass()) && principalClass == ((ParameterizedType) parameter.getType()).getActualTypeArguments()[0]; return isOptionalPrincipal ? request -> new OptionalPrincipalContainerRequestValueFactory(request).provide() : null; } }
@Override public void configure(ResourceInfo resourceInfo, FeatureContext context) { final AnnotatedMethod am = new AnnotatedMethod(resourceInfo.getResourceMethod()); final Annotation[][] parameterAnnotations = am.getParameterAnnotations(); final Class<?>[] parameterTypes = am.getParameterTypes(); // First, check for any @Auth annotations on the method. for (int i = 0; i < parameterAnnotations.length; i++) { for (final Annotation annotation : parameterAnnotations[i]) { if (annotation instanceof Auth) { // Optional auth requires that a concrete AuthFilter be provided. if (parameterTypes[i].equals(Optional.class) && authFilter != null) { context.register(new WebApplicationExceptionCatchingFilter(authFilter)); return; } else { registerAuthFilter(context); return; } } } } // Second, check for any authorization annotations on the class or method. // Note that @DenyAll shouldn't be attached to classes. final boolean annotationOnClass = (resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class) != null) || (resourceInfo.getResourceClass().getAnnotation(PermitAll.class) != null); final boolean annotationOnMethod = am.isAnnotationPresent(RolesAllowed.class) || am.isAnnotationPresent(DenyAll.class) || am.isAnnotationPresent(PermitAll.class); if (annotationOnClass || annotationOnMethod) { registerAuthFilter(context); } }
/** * Builds an instance of the filter with a provided authenticator, * an authorizer, a prefix, and a realm. * * @return a new instance of the filter */ public T buildAuthFilter() { requireNonNull(realm, "Realm is not set"); requireNonNull(prefix, "Prefix is not set"); requireNonNull(authenticator, "Authenticator is not set"); requireNonNull(authorizer, "Authorizer is not set"); requireNonNull(unauthorizedHandler, "Unauthorized handler is not set"); final T authFilter = newInstance(); authFilter.authorizer = authorizer; authFilter.authenticator = authenticator; authFilter.prefix = prefix; authFilter.realm = realm; authFilter.unauthorizedHandler = unauthorizedHandler; return authFilter; }
@Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { WebApplicationException firstException = null; for (@SuppressWarnings("rawtypes") AuthFilter authFilter : handlers) { final SecurityContext securityContext = containerRequestContext.getSecurityContext(); try { authFilter.filter(containerRequestContext); if (securityContext != containerRequestContext.getSecurityContext()) { return; } } catch (WebApplicationException e) { if (firstException == null) { firstException = e; } } } throw firstException; } }
if (type == Optional.class) { final ContainerRequestFilter filter = authFilterMap.get(paramType); context.register(new WebApplicationExceptionCatchingFilter(filter)); return; } else {
@GET @PermitAll @Path("guest") public String showSecret(@Auth User user) { return String.format("Hey there, %s. You know the secret! %d", user.getName(), user.getId()); }
/** * Creates a new cached authorizer. * * @param metricRegistry the application's registry of metrics * @param authorizer the underlying authorizer * @param builder a {@link CaffeineSpec} */ public CachingAuthorizer( final MetricRegistry metricRegistry, final Authorizer<P> authorizer, final Caffeine<Object, Object> builder) { this.underlying = authorizer; this.cacheMisses = metricRegistry.meter(name(authorizer.getClass(), "cache-misses")); this.getsTimer = metricRegistry.timer(name(authorizer.getClass(), "gets")); this.cache = builder.recordStats().build(key -> { cacheMisses.mark(); return underlying.authorize(key.left, key.right); }); }
@Nullable @Override protected Function<ContainerRequest, ?> createValueProvider(Parameter parameter) { if (!parameter.isAnnotationPresent(Auth.class)) { return null; } else if (principalClassSet.contains(parameter.getRawType())) { return request -> new PrincipalContainerRequestValueFactory(request).provide(); } else { final boolean isOptionalPrincipal = parameter.getRawType() == Optional.class && ParameterizedType.class.isAssignableFrom(parameter.getType().getClass()) && principalClassSet.contains(((ParameterizedType) parameter.getType()).getActualTypeArguments()[0]); return isOptionalPrincipal ? request -> new OptionalPrincipalContainerRequestValueFactory(request).provide() : null; } }
@RolesAllowed("ADMIN") @GET @Path("admin") public String showAdminSecret(@Auth User user) { return String.format("Hey there, %s. It looks like you are an admin. %d", user.getName(), user.getId()); } }
@GET @RolesAllowed("ADMIN") @Path("admin") public String showAdminSecret(@Auth User user) { return String.format("Hey there, %s. It looks like you are an admin. %d", user.getName(), user.getId()); }
@Timed @DELETE @Path("/pin/") public void removePin(@Auth Account account) { account.setPin(null); accounts.update(account); }