Java Code Examples for javax.ws.rs.container.ContainerRequestContext#setSecurityContext()
The following examples show how to use
javax.ws.rs.container.ContainerRequestContext#setSecurityContext() .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SampleAuthorizationFilter.java From doctorkafka with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String userHeader = requestContext.getHeaderString(USER_HEADER); String groupsHeader = requestContext.getHeaderString(GROUPS_HEADER); DrKafkaSecurityContext ctx = null; if (userHeader != null && groupsHeader != null) { Set<String> userGroups = new HashSet<>(Arrays.asList(groupsHeader.split(","))); SetView<String> intersection = Sets.intersection(allowedAdminGroups, userGroups); if (intersection.size() > 0) { ctx = new DrKafkaSecurityContext(new UserPrincipal(userHeader), ADMIN_ROLE_SET); requestContext.setSecurityContext(ctx); LOG.info("Received authenticated request, created context:" + ctx); return; } } ctx = new DrKafkaSecurityContext(new UserPrincipal(userHeader), EMPTY_ROLE_SET); requestContext.setSecurityContext(ctx); LOG.info("Received annonymous request, bypassing authorizer"); }
Example 2
Source File: SecurityFilter.java From divide with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext request) throws IOException { log.info("Filter(): " + request.getUriInfo().getPath()); String path = request.getUriInfo().getPath(); if(!path.startsWith("/auth/user/data") && !path.startsWith("/auth/user/data/")) if ( path.startsWith("auth") || path.startsWith("/auth") || securityManager.getSafePaths().contains(path) ) { log.info("Auth Skipped : (" + path +")"); return; } UserContext context = authenticate(request); if (context != null) { log.info("Authenticated: " + context.getUser().getEmailAddress()); } else { log.info("Authentication Failed"); } request.setProperty(Session.SESSION_KEY,context); request.setSecurityContext(context); }
Example 3
Source File: AllowAllAuthInterceptor.java From enmasse with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) { String username = Optional.ofNullable(requestContext.getHeaderString("X-Remote-User")).orElse("system:anonymous"); requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return RbacSecurityContext.getUserPrincipal(username, ""); } @Override public boolean isUserInRole(String role) { return true; } @Override public boolean isSecure() { return true; } @Override public String getAuthenticationScheme() { return "dummy"; } }); }
Example 4
Source File: StreamlineKerberosRequestFilter.java From streamline with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { Principal principal = httpRequest.getUserPrincipal(); String scheme = requestContext.getUriInfo().getRequestUri().getScheme(); LOG.debug("Method: {}, AuthType: {}, RemoteUser: {}, UserPrincipal: {}, Scheme: {}", httpRequest.getMethod(), httpRequest.getAuthType(), httpRequest.getRemoteUser(), principal, scheme); if (principal == null || !httpRequest.getAuthType().equalsIgnoreCase(KERBEROS_AUTH)) { throw new WebserviceAuthorizationException("Not authorized"); } SecurityContext securityContext = new StreamlineSecurityContext(principal, scheme, KERBEROS_AUTH); LOG.debug("SecurityContext {}", securityContext); requestContext.setSecurityContext(securityContext); }
Example 5
Source File: CategoriesResourceNotAuthenticatedTest.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return null; } @Override public boolean isUserInRole(String string) { return false; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return "BASIC"; } }); }
Example 6
Source File: ApisResourceNotAuthenticatedTest.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return null; } @Override public boolean isUserInRole(String string) { return false; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return "BASIC"; } }); }
Example 7
Source File: ApiPageResourceNotAuthenticatedTest.java From gravitee-management-rest-api with Apache License 2.0 | 6 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return null; } @Override public boolean isUserInRole(String string) { return false; } @Override public boolean isSecure() { return false; } @Override public String getAuthenticationScheme() { return "BASIC"; } }); }
Example 8
Source File: OidcIdTokenRequestFilter.java From cxf with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { MultivaluedMap<String, String> form = toFormData(requestContext); String idTokenParamValue = form.getFirst(tokenFormParameter); if (idTokenParamValue == null) { requestContext.abortWith(Response.status(401).build()); return; } IdToken idToken = idTokenReader.getIdToken(idTokenParamValue, consumer); JAXRSUtils.getCurrentMessage().setContent(IdToken.class, idToken); OidcSecurityContext oidcSecCtx = new OidcSecurityContext(idToken); oidcSecCtx.setRoleClaim(roleClaim); requestContext.setSecurityContext(oidcSecCtx); }
Example 9
Source File: JaxrsBearerTokenFilterImpl.java From keycloak with Apache License 2.0 | 5 votes |
protected void propagateSecurityContext(JaxrsHttpFacade facade, ContainerRequestContext request, KeycloakDeployment resolvedDeployment, BearerTokenRequestAuthenticator bearer) { RefreshableKeycloakSecurityContext skSession = new RefreshableKeycloakSecurityContext(resolvedDeployment, null, bearer.getTokenString(), bearer.getToken(), null, null, null); // Not needed to do resteasy specifics as KeycloakSecurityContext can be always retrieved from SecurityContext by typecast SecurityContext.getUserPrincipal to KeycloakPrincipal // ResteasyProviderFactory.pushContext(KeycloakSecurityContext.class, skSession); facade.setSecurityContext(skSession); String principalName = AdapterUtils.getPrincipalName(resolvedDeployment, bearer.getToken()); final KeycloakPrincipal<RefreshableKeycloakSecurityContext> principal = new KeycloakPrincipal<RefreshableKeycloakSecurityContext>(principalName, skSession); SecurityContext anonymousSecurityContext = getRequestSecurityContext(request); final boolean isSecure = anonymousSecurityContext.isSecure(); final Set<String> roles = AdapterUtils.getRolesFromSecurityContext(skSession); SecurityContext ctx = new SecurityContext() { @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return roles.contains(role); } @Override public boolean isSecure() { return isSecure; } @Override public String getAuthenticationScheme() { return "OAUTH_BEARER"; } }; request.setSecurityContext(ctx); }
Example 10
Source File: AuthenticationEndpoint.java From divide with Apache License 2.0 | 5 votes |
@GET @Path("/recover/{token}") @Produces(MediaType.APPLICATION_JSON) public Response recoverFromOneTimeToken(@Context ContainerRequestContext context, @PathParam("token") String token) { try{ Credentials user = authServerLogic.getUserFromRecoveryToken(token); context.setSecurityContext(new UserContext(context.getUriInfo(),user)); return Response.ok(user).build(); }catch (ServerDAO.DAOException e) { e.printStackTrace(); logger.severe(ExceptionUtils.getStackTrace(e)); return fromDAOExpection(e); } }
Example 11
Source File: SecurityContextFilter.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return (authentication instanceof AnonymousAuthenticationToken) ? null : authentication; } @Override public boolean isUserInRole(final String role) { return SecurityContextHolder.getContext().getAuthentication().getAuthorities() .stream().anyMatch((Predicate<GrantedAuthority>) grantedAuthority -> grantedAuthority.getAuthority().equalsIgnoreCase(role)); } @Override public boolean isSecure() { return requestContext.getUriInfo().getRequestUri().getScheme().equalsIgnoreCase("https"); } @Override public String getAuthenticationScheme() { return requestContext.getUriInfo().getRequestUri().getScheme(); } }); }
Example 12
Source File: SecurityFilterTest.java From servicetalk with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestCtx) { if ("true".equals(requestCtx.getUriInfo().getQueryParameters().getFirst("none"))) { return; } requestCtx.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return new JMXPrincipal("foo"); } @Override public boolean isUserInRole(final String role) { return false; } @Override public boolean isSecure() { return true; } @Override public String getAuthenticationScheme() { return "bar"; } }); }
Example 13
Source File: AbstractBasicAuthSecurityContextFilter.java From servicetalk with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestCtx) { final SecurityContext securityContext = securityContext(requestCtx); if (securityContext != null) { requestCtx.setSecurityContext(securityContext); } }
Example 14
Source File: SecurityContextFilter.java From gravitee-management-rest-api with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); return (authentication instanceof AnonymousAuthenticationToken) ? null : authentication; } @Override public boolean isUserInRole(final String role) { return SecurityContextHolder.getContext().getAuthentication().getAuthorities() .stream().anyMatch((Predicate<GrantedAuthority>) grantedAuthority -> grantedAuthority.getAuthority().equalsIgnoreCase(role)); } @Override public boolean isSecure() { return requestContext.getUriInfo().getRequestUri().getScheme().equalsIgnoreCase("https"); } @Override public String getAuthenticationScheme() { return requestContext.getUriInfo().getRequestUri().getScheme(); } }); }
Example 15
Source File: KeycloakAuthFilter.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) { validateRequest(requestContext); HttpServletRequest request = (HttpServletRequest) requestContext.getProperty(HttpServletRequest.class.getName()); final Optional<P> principal; try { principal = authenticator.authenticate(request); if (principal.isPresent()) { requestContext.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return principal.get(); } @Override public boolean isUserInRole(String role) { return authorizer.authorize(principal.get(), role); } @Override public boolean isSecure() { return requestContext.getSecurityContext().isSecure(); } @Override public String getAuthenticationScheme() { return SecurityContext.BASIC_AUTH; } }); return; } } catch (AuthenticationException e) { LOGGER.warn("Error authenticating credentials", e); throw new InternalServerErrorException(); } // TODO: re-enable / check if 302 has been returned // throw new WebApplicationException(unauthorizedHandler.buildResponse(prefix, realm)); }
Example 16
Source File: ServletSecurityUtils.java From presto with Apache License 2.0 | 5 votes |
public static void setAuthenticatedIdentity(ContainerRequestContext request, Identity authenticatedIdentity) { request.setProperty(AUTHENTICATED_IDENTITY, authenticatedIdentity); boolean secure = request.getSecurityContext().isSecure(); Principal principal = authenticatedIdentity.getPrincipal().orElse(null); request.setSecurityContext(new SecurityContext() { @Override public Principal getUserPrincipal() { return principal; } @Override public boolean isUserInRole(String role) { return false; } @Override public boolean isSecure() { return secure; } @Override public String getAuthenticationScheme() { return "presto"; } }); }
Example 17
Source File: TokenSecurityContextFilter.java From openscoring with GNU Affero General Public License v3.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { SecurityContext requestSecurityContext = requestContext.getSecurityContext(); SecurityContext securityContext = new SecurityContext(){ @Override public Principal getUserPrincipal(){ return Anonymous.INSTANCE; } @Override public boolean isUserInRole(String role){ String token = getToken(); String roleToken; switch(role){ case Roles.USER: roleToken = getUserToken(); break; case Roles.ADMIN: roleToken = getAdminToken(); break; default: return false; } return (roleToken).equals(token) || (roleToken).equals(""); } @Override public boolean isSecure(){ return requestSecurityContext != null && requestSecurityContext.isSecure(); } @Override public String getAuthenticationScheme(){ return "TOKEN"; } private String getToken(){ Map<String, Cookie> cookies = requestContext.getCookies(); MultivaluedMap<String, String> headers = requestContext.getHeaders(); Cookie tokenCookie = cookies.get("token"); if(tokenCookie != null){ return tokenCookie.getValue(); } String authorizationHeader = headers.getFirst(HttpHeaders.AUTHORIZATION); if(authorizationHeader != null && authorizationHeader.startsWith("Bearer ")){ return authorizationHeader.substring("Bearer ".length()); } return null; } }; requestContext.setSecurityContext(securityContext); }
Example 18
Source File: AuthenticationFilter.java From clouditor with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) { // ignore filter for classes that do not have @RolesAllowed var rolesAllowed = resourceInfo.getResourceClass().getAnnotation(RolesAllowed.class); if (rolesAllowed == null) { return; } // ignore filter for OPTIONS requests (pre-flight requests) if (Objects.equals(requestContext.getMethod(), "OPTIONS")) { return; } String authorization = requestContext.getHeaderString(HEADER_AUTHORIZATION); if (authorization == null || authorization.isEmpty()) { // try cookies var cookie = requestContext.getCookies().get("authentication"); if (cookie != null) { authorization = cookie.getValue(); } } if (authorization == null || !authorization.startsWith("Bearer")) { throw new NotAuthorizedException("No token was specified"); } String[] rr = authorization.split(" "); if (rr.length != 2) { throw new NotAuthorizedException("Invalid authentication format"); } String token = rr[1]; try { User user = authenticationService.verifyToken(token); LOGGER.debug( "Authenticated API access to {} as {}", requestContext.getUriInfo().getPath(), user.getName()); var ctx = new UserContext(user, requestContext.getSecurityContext().isSecure()); requestContext.setSecurityContext(ctx); var authorized = false; for (var role : rolesAllowed.value()) { if (ctx.isUserInRole(role)) { authorized = true; break; } } if (!authorized) { throw new ForbiddenException( "User " + user.getName() + " does not have appropriate role to view resource."); } } catch (NotAuthorizedException | ForbiddenException ex) { // log the error LOGGER.error( "API access to {} was denied: {}", requestContext.getUriInfo().getPath(), ex.getMessage()); // re-throw it throw ex; } }
Example 19
Source File: JwtAuthFilter.java From trellis with Apache License 2.0 | 4 votes |
@Override public void filter(final ContainerRequestContext ctx) throws IOException { LOGGER.trace("JWT Auth Token: {}", jwt); ctx.setSecurityContext(new WebIdSecurityContext(ctx.getSecurityContext(), jwt, admins)); }
Example 20
Source File: AwsSecurityContextFilter.java From jrestless with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { requestContext.setSecurityContext(createSecurityContext()); }