Java Code Examples for javax.ws.rs.container.ContainerRequestContext#getSecurityContext()
The following examples show how to use
javax.ws.rs.container.ContainerRequestContext#getSecurityContext() .
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: LoggingResourceFilter.java From brooklyn-server with Apache License 2.0 | 6 votes |
private void logRequest(ContainerRequestContext requestContext, LogLevel level) { if (!isLogEnabled(LOG, level)) return; String method = requestContext.getMethod(); String path = requestContext.getUriInfo().getPath(); requestContext.getSecurityContext(); SecurityContext securityContext = requestContext.getSecurityContext(); Principal userPrincipal = (securityContext != null) ? requestContext.getSecurityContext().getUserPrincipal() : null; String userName = (userPrincipal != null) ? userPrincipal.getName() : "<no-user>"; String remoteAddr = servletRequest.getRemoteAddr(); StringBuilder message = new StringBuilder("Request received: ") .append(method) .append(" ") .append(path) .append(" from ") .append(userName) .append(" @ ") .append(remoteAddr); log(LOG, level, message.toString()); }
Example 2
Source File: RateLimitingFilter.java From blog-tutorials with MIT License | 6 votes |
@Transactional @Override public void filter(ContainerRequestContext requestContext) throws IOException { SecurityContext securityContext = requestContext.getSecurityContext(); String username = securityContext.getUserPrincipal().getName(); User user = entityManager.createQuery("SELECT u FROM User u WHERE u.username=:username", User.class).setParameter( "username", username).getSingleResult(); if (user.getAmountOfApiCalls() >= user.getMaxApiCallsPerMinute()) { requestContext.abortWith(Response.status(Response.Status.TOO_MANY_REQUESTS).build()); } user.setAmountOfApiCalls(user.getAmountOfApiCalls() + 1); System.out.println(user); }
Example 3
Source File: ChainedAuthFilter.java From dropwizard-java8 with Apache License 2.0 | 6 votes |
@Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { WebApplicationException firstException = null; for (AuthFilter authFilter : handlers) { SecurityContext securityContext = containerRequestContext.getSecurityContext(); try { authFilter.filter(containerRequestContext); if (securityContext != containerRequestContext.getSecurityContext()) { return; } } catch (WebApplicationException e) { if (firstException == null) { firstException = e; } } } throw firstException; }
Example 4
Source File: KeycloakAuthFilter.java From keycloak-dropwizard-integration with Apache License 2.0 | 5 votes |
public void validateRequest(final ContainerRequestContext requestContext) { if (requestContext.getSecurityContext().getUserPrincipal() != null) { // the user is already authenticated, further processing is not necessary return; } Request request = Request.getBaseRequest((ServletRequest) requestContext.getProperty(HttpServletRequest.class.getName())); JaxrsHttpFacade facade = new JaxrsHttpFacade(requestContext, requestContext.getSecurityContext()); request.setAttribute(AdapterDeploymentContext.class.getName(), deploymentContext); KeycloakDeployment deployment = deploymentContext.resolveDeployment(facade); if (deployment == null || !deployment.isConfigured()) { return; } AdapterTokenStore tokenStore = getTokenStore(request, facade, deployment); tokenStore.checkCurrentToken(); JettyRequestAuthenticator authenticator = createRequestAuthenticator(request, facade, deployment, tokenStore); AuthOutcome outcome = authenticator.authenticate(); if (outcome == AuthOutcome.AUTHENTICATED) { return; } AuthChallenge challenge = authenticator.getChallenge(); if (challenge != null) { challenge.challenge(facade); if (!adapterConfig.isBearerOnly()) { // create session and set cookie for client facade.getResponse().setCookie("JSESSIONID", request.getSession().getId(), "/", null, -1, false, false); } facade.getResponse().end(); } }
Example 5
Source File: EntitlementContextFilter.java From brooklyn-server with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { String userName = null; // first see if there is a principal SecurityContext securityContext = requestContext.getSecurityContext(); Principal user = securityContext.getUserPrincipal(); if (user!=null) { userName = user.getName(); } else { // now look in session attribute - because principals hard to set from javax filter if (request!=null) { MultiSessionAttributeAdapter s = MultiSessionAttributeAdapter.of(request, false); if (s!=null) { userName = Strings.toString(s.getAttribute( BrooklynSecurityProviderFilterHelper.AUTHENTICATED_USER_SESSION_ATTRIBUTE)); } } } if (userName != null) { EntitlementContext oldEntitlement = Entitlements.getEntitlementContext(); if (oldEntitlement!=null && !userName.equals(oldEntitlement.user())) { throw new IllegalStateException("Illegal entitement context switch, from user "+oldEntitlement.user()+" to "+userName); } String uri = request.getRequestURI(); String remoteAddr = request.getRemoteAddr(); String uid = RequestTaggingRsFilter.getTag(); WebEntitlementContext entitlementContext = new WebEntitlementContext(userName, remoteAddr, uri, uid); Entitlements.setEntitlementContext(entitlementContext); } }
Example 6
Source File: HammockKeycloakJaxrsFilter.java From hammock with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext containerRequestContext) throws IOException { SecurityContext securityContext = containerRequestContext.getSecurityContext(); JaxrsHttpFacade facade = new JaxrsHttpFacade(containerRequestContext, securityContext); if (handlePreauth(facade)) { return; } KeycloakDeployment resolvedDeployment = deploymentContext.resolveDeployment(facade); nodesRegistrationManagement.tryRegister(resolvedDeployment); bearerAuthentication(facade, containerRequestContext, resolvedDeployment); }
Example 7
Source File: RolesAllowedAdminInterceptor.java From jweb-cms with GNU Affero General Public License v3.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { RolesAllowed rolesAllowed = resourceInfo.getResourceMethod().getDeclaredAnnotation(RolesAllowed.class); if (rolesAllowed == null || rolesAllowed.value().length == 0) { return; } SecurityContext securityContext = requestContext.getSecurityContext(); for (String role : rolesAllowed.value()) { if (!securityContext.isUserInRole(role)) { throw new AdminForbiddenException("invalid permission"); } } }
Example 8
Source File: JerseyGuiceModule.java From soabase with Apache License 2.0 | 5 votes |
@Provides @RequestScoped public SecurityContext providesSecurityContext() { ContainerRequestContext context = filter.getContainerRequestContext(); return (context != null) ? context.getSecurityContext() : null; }
Example 9
Source File: BasicAuthFilter.java From trellis with Apache License 2.0 | 5 votes |
@Override public void filter(final ContainerRequestContext requestContext) { final boolean secure = requestContext.getSecurityContext() != null && requestContext.getSecurityContext().isSecure(); final String credentials = getCredentials(requestContext); if (credentials != null) { final Principal principal = authenticate(credentials); if (principal == null) throw new NotAuthorizedException(challenge); requestContext.setSecurityContext(new BasicAuthSecurityContext(principal, admins, secure)); } }
Example 10
Source File: ResponseFilter.java From divide with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { SecurityContext context = requestContext.getSecurityContext(); if(context != null && context instanceof UserContext){ UserContext userContext = (UserContext)context; Credentials user = userContext.getUser(); if(user!=null && user.getAuthToken() != null){ responseContext.getHeaders().add("Authorization", user.getAuthToken()); } } }
Example 11
Source File: GSuiteGroupAuthorizationFilter.java From g-suite-identity-sync with Apache License 2.0 | 5 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { OidcSecurityContext secCtx = (OidcSecurityContext) requestContext.getSecurityContext(); OidcClientTokenContext tokenCtx = secCtx.getOidcContext(); IdToken idToken = tokenCtx.getIdToken(); String email = idToken.getEmail(); String userDomain = idToken.getStringProperty("hd"); String appDomain = gsuiteDirService.getDomainName(); if (appDomain == null) { throw serverError(SERVICE_UNAVAILABLE, "E002", "Service not configured!"); } boolean internal = gsuiteDirService.getDomainName().equalsIgnoreCase(userDomain); boolean external = false; Set<String> roles = new HashSet<>(); String masterRole = null; if (internal) { roles.add(AuthzRole.INTERNAL); masterRole = AuthzRole.INTERNAL; } else if (externalUsersCache.get().contains(email)) { roles.add(AuthzRole.EXTERNAL); masterRole = AuthzRole.EXTERNAL; external = true; } if (adminUsersCache.get().contains(email)) { roles.add(AuthzRole.ADMIN); masterRole = AuthzRole.ADMIN; } if (internal || external) { } else { LOG.error("Unauthorized access from {}", userDomain); ServerError err = new ServerError("E001", "Sorry you are not allowed to enter this site"); requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build()); } secCtx.getOidcContext().getUserInfo().setProperty("securityRoles", roles); secCtx.getOidcContext().getUserInfo().setProperty("masterRole", masterRole); secCtx.setRoleClaim("masterRole"); }
Example 12
Source File: OidcClientCodeRequestFilter.java From cxf with Apache License 2.0 | 5 votes |
@Override protected ClientTokenContext createTokenContext(ContainerRequestContext rc, ClientAccessToken at, MultivaluedMap<String, String> requestParams, MultivaluedMap<String, String> state) { if (rc.getSecurityContext() instanceof OidcSecurityContext) { return ((OidcSecurityContext)rc.getSecurityContext()).getOidcContext(); } OidcClientTokenContextImpl ctx = new OidcClientTokenContextImpl(); if (at != null) { if (idTokenReader == null) { throw new OAuthServiceException(OAuthConstants.SERVER_ERROR); } IdToken idToken = idTokenReader.getIdToken(at, requestParams.getFirst(OAuthConstants.AUTHORIZATION_CODE_VALUE), getConsumer()); // Validate the properties set up at the redirection time. validateIdToken(idToken, state); ctx.setIdToken(idToken); if (userInfoClient != null) { ctx.setUserInfo(userInfoClient.getUserInfo(at, ctx.getIdToken(), getConsumer())); } OidcSecurityContext oidcSecCtx = new OidcSecurityContext(ctx); oidcSecCtx.setRoleClaim(roleClaim); rc.setSecurityContext(oidcSecCtx); } return ctx; }
Example 13
Source File: AuthorizationFilter.java From iaf with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { if(requestContext.getMethod().equalsIgnoreCase("OPTIONS")) { //Preflight in here? return; } Message message = JAXRSUtils.getCurrentMessage(); Method method = (Method)message.get("org.apache.cxf.resource.method"); if(method == null) { log.error("Unable to fetch method from CXF Message"); requestContext.abortWith(SERVER_ERROR); } if(method.isAnnotationPresent(DenyAll.class)) { //Functionality has been disallowed. requestContext.abortWith(FORBIDDEN); return; } if(method.isAnnotationPresent(PermitAll.class)) { //No authorization required. return; } //Presume `PermitAll` when RolesAllowed annotation is not set if(method.isAnnotationPresent(RolesAllowed.class)) { SecurityContext securityContext = requestContext.getSecurityContext(); if(securityContext.getUserPrincipal() == null) { if(!login(requestContext)) { //Not logged in. Manually trying to authenticate the user requestContext.abortWith(UNAUTHORIZED); return; } else { System.out.println("manually logged in user [" + securityContext.getUserPrincipal().getName()+"]"); } } RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class); Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value())); System.out.println("Checking authentication for user ["+securityContext.getUserPrincipal().getName()+"] uri ["+method.getAnnotation(javax.ws.rs.Path.class).value()+"] roles " + rolesSet.toString()); //Verifying username and password if(!doAuth(securityContext, rolesSet)) { requestContext.abortWith(FORBIDDEN); return; } } }
Example 14
Source File: RequestPac4JSecurityContext.java From jax-rs-pac4j with Apache License 2.0 | 4 votes |
public RequestPac4JSecurityContext(ContainerRequestContext request) { this(request.getSecurityContext()); }
Example 15
Source File: LoggingResourceFilter.java From brooklyn-server with Apache License 2.0 | 4 votes |
private void logResponse(ContainerRequestContext requestContext, ContainerResponseContext responseContext, Duration requestDuration, LogLevel level) { if (!isLogEnabled(LOG, level)) return; int status = responseContext.getStatus(); String method = requestContext.getMethod(); String path = requestContext.getUriInfo().getPath(); requestContext.getSecurityContext(); MultivaluedMap<String, String> queryParams = requestContext.getUriInfo().getQueryParameters(); SecurityContext securityContext = requestContext.getSecurityContext(); Principal userPrincipal = (securityContext != null) ? requestContext.getSecurityContext().getUserPrincipal() : null; String userName = (userPrincipal != null) ? userPrincipal.getName() : "<no-user>"; String remoteAddr = servletRequest.getRemoteAddr(); boolean includeHeaders = (responseContext.getStatus() / 100 == 5) || LOG.isTraceEnabled(); StringBuilder message = new StringBuilder("Request completed: ") .append("status ") .append(status) .append(" in ") .append(requestDuration) .append(", ") .append(method) .append(" ") .append(path) .append(" from ") .append(userName) .append(" @ ") .append(remoteAddr); if (!queryParams.isEmpty()) { message.append(", queryParams: {"); message.append(Joiner.on(", ").withKeyValueSeparator("=").join(queryParams)); message.append("}"); } if (requestContext.getLength() > 0) { // TODO `getLength` is based on the presence of `Content-Length` header, rather than the measured length. int len = requestContext.getLength(); message.append(", mediaType=").append(requestContext.getMediaType()) .append(" (length=").append(len).append(")"); } if (includeHeaders) { MultivaluedMap<String, String> headers = requestContext.getHeaders(); message.append(", headers={"); if (!headers.isEmpty()) { boolean first = true; for (Map.Entry<String, List<String>> entry : headers.entrySet()) { if (first) { first = false; } else { message.append(", "); } String headerName = entry.getKey(); message.append(headerName).append(": "); if (CENSORED_HEADERS.contains(headerName)) { message.append("******"); } else { message.append(entry.getValue()); } } } message.append("}"); } log(LOG, level, message.toString()); }
Example 16
Source File: JsonWebTokenAuthFilterTest.java From jobson with Apache License 2.0 | 4 votes |
@Test public void testSecurityContextIsAssignedToPrincipalReturnedByAuthenticator() throws AuthenticationException, IOException { final String username = TestHelpers.generateRandomString(); final Principal injectedPrincipal = new PrincipalImpl(username); final Authenticator<String, Principal> authenticator = mock(Authenticator.class); when(authenticator.authenticate(any())).thenReturn(Optional.of(injectedPrincipal)); final JsonWebTokenAuthFilter filter = createAuthFilterWithAuthenticator(authenticator); final ContainerRequestContext request = createDummyRequest(); filter.filter(request); final SecurityContext securityContext = request.getSecurityContext(); final String returnedName = securityContext.getUserPrincipal().getName(); assertThat(returnedName).isEqualTo(username); }
Example 17
Source File: UserPrincipalContextFilter.java From mapr-music with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext context) throws IOException { SecurityContext securityContext = context.getSecurityContext(); ResteasyProviderFactory.pushContext(Principal.class, securityContext.getUserPrincipal()); }
Example 18
Source File: NetworkSecurityContextFilter.java From openscoring with GNU Affero General Public License v3.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext){ HttpServletRequest request = getRequest(); SecurityContext requestSecurityContext = requestContext.getSecurityContext(); SecurityContext securityContext = new SecurityContext(){ @Override public Principal getUserPrincipal(){ return Anonymous.INSTANCE; } @Override public boolean isUserInRole(String role){ String address = getAddress(); Set<String> roleAddresses; switch(role){ case Roles.USER: roleAddresses = getUserAddresses(); break; case Roles.ADMIN: roleAddresses = getAdminAddresses(); break; default: return false; } return (roleAddresses).contains(address) || (roleAddresses).contains("*"); } @Override public boolean isSecure(){ return requestSecurityContext != null && requestSecurityContext.isSecure(); } @Override public String getAuthenticationScheme(){ return "REMOTE_ADDR"; } private String getAddress(){ if(request == null){ return null; } return request.getRemoteAddr(); } }; requestContext.setSecurityContext(securityContext); }
Example 19
Source File: SecurityContextFilter.java From quarkus with Apache License 2.0 | 4 votes |
@Override public void filter(ContainerRequestContext requestContext) throws IOException { SecurityContext modified = requestContext.getSecurityContext(); if (modified instanceof ServletSecurityContext || modified instanceof QuarkusResteasySecurityContext) { //an original security context, it has not been modified return; } Set<Credential> oldCredentials = old.getCredentials(); Map<String, Object> oldAttributes = old.getAttributes(); SecurityIdentity newIdentity = new SecurityIdentity() { @Override public Principal getPrincipal() { return modified.getUserPrincipal(); } @Override public boolean isAnonymous() { return modified.getUserPrincipal() == null; } @Override public Set<String> getRoles() { throw new UnsupportedOperationException( "retrieving all roles not supported when JAX-RS security context has been replaced"); } @Override public boolean hasRole(String role) { return modified.isUserInRole(role); } @Override public <T extends Credential> T getCredential(Class<T> credentialType) { for (Credential cred : getCredentials()) { if (credentialType.isAssignableFrom(cred.getClass())) { return (T) cred; } } return null; } @Override public Set<Credential> getCredentials() { return oldCredentials; } @Override public <T> T getAttribute(String name) { return (T) oldAttributes.get(name); } @Override public Map<String, Object> getAttributes() { return oldAttributes; } @Override public Uni<Boolean> checkPermission(Permission permission) { return Uni.createFrom().nullItem(); } }; currentIdentityAssociation.setIdentity(newIdentity); }
Example 20
Source File: ClientCodeRequestFilter.java From cxf with Apache License 2.0 | 4 votes |
protected void checkSecurityContextStart(ContainerRequestContext rc) { SecurityContext sc = rc.getSecurityContext(); if (sc == null || sc.getUserPrincipal() == null) { throw ExceptionUtils.toNotAuthorizedException(null, null); } }