Search in sources :

Example 6 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project traccar by tananaev.

the class SecurityRequestFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) {
    if (requestContext.getMethod().equals("OPTIONS")) {
        return;
    }
    SecurityContext securityContext = null;
    try {
        String authHeader = requestContext.getHeaderString(AUTHORIZATION_HEADER);
        if (authHeader != null) {
            try {
                String[] auth = decodeBasicAuth(authHeader);
                User user = Context.getPermissionsManager().login(auth[0], auth[1]);
                if (user != null) {
                    Context.getStatisticsManager().registerRequest(user.getId());
                    securityContext = new UserSecurityContext(new UserPrincipal(user.getId()));
                }
            } catch (SQLException e) {
                throw new WebApplicationException(e);
            }
        } else if (request.getSession() != null) {
            Long userId = (Long) request.getSession().getAttribute(SessionResource.USER_ID_KEY);
            if (userId != null) {
                Context.getPermissionsManager().checkUserEnabled(userId);
                Context.getStatisticsManager().registerRequest(userId);
                securityContext = new UserSecurityContext(new UserPrincipal(userId));
            }
        }
    } catch (SecurityException e) {
        Log.warning(e);
    }
    if (securityContext != null) {
        requestContext.setSecurityContext(securityContext);
    } else {
        Method method = resourceInfo.getResourceMethod();
        if (!method.isAnnotationPresent(PermitAll.class)) {
            Response.ResponseBuilder responseBuilder = Response.status(Response.Status.UNAUTHORIZED);
            if (!XML_HTTP_REQUEST.equals(request.getHeader(X_REQUESTED_WITH))) {
                responseBuilder.header(WWW_AUTHENTICATE, BASIC_REALM);
            }
            throw new WebApplicationException(responseBuilder.build());
        }
    }
}
Also used : User(org.traccar.model.User) WebApplicationException(javax.ws.rs.WebApplicationException) SQLException(java.sql.SQLException) Method(java.lang.reflect.Method) Response(javax.ws.rs.core.Response) SecurityContext(javax.ws.rs.core.SecurityContext) PermitAll(javax.annotation.security.PermitAll)

Example 7 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project iaf by ibissource.

the class AuthorizationFilter method filter.

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    SecurityContext securityContext = requestContext.getSecurityContext();
    if (securityContext.getUserPrincipal() == null) {
        // No userPrincipal, authentication is disabled.
        return;
    }
    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 resource method from CXF Message");
        requestContext.abortWith(SERVER_ERROR);
        return;
    }
    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)) {
        RolesAllowed rolesAnnotation = method.getAnnotation(RolesAllowed.class);
        Set<String> rolesSet = new HashSet<String>(Arrays.asList(rolesAnnotation.value()));
        log.info("checking authorisation for user [" + securityContext.getUserPrincipal().getName() + "] on uri [" + method.getAnnotation(javax.ws.rs.Path.class).value() + "] required roles " + rolesSet.toString());
        if (!doAuth(securityContext, rolesSet)) {
            requestContext.abortWith(FORBIDDEN);
            return;
        }
    }
}
Also used : RolesAllowed(javax.annotation.security.RolesAllowed) Message(org.apache.cxf.message.Message) SecurityContext(javax.ws.rs.core.SecurityContext) Method(java.lang.reflect.Method) HashSet(java.util.HashSet)

Example 8 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project keycloak by keycloak.

the class JaxrsBearerTokenFilterImpl method filter.

// REQUEST HANDLING
@Override
public void filter(ContainerRequestContext request) throws IOException {
    SecurityContext securityContext = getRequestSecurityContext(request);
    JaxrsHttpFacade facade = new JaxrsHttpFacade(request, securityContext);
    if (handlePreauth(facade)) {
        return;
    }
    KeycloakDeployment resolvedDeployment = deploymentContext.resolveDeployment(facade);
    nodesRegistrationManagement.tryRegister(resolvedDeployment);
    bearerAuthentication(facade, request, resolvedDeployment);
}
Also used : KeycloakDeployment(org.keycloak.adapters.KeycloakDeployment) SecurityContext(javax.ws.rs.core.SecurityContext) RefreshableKeycloakSecurityContext(org.keycloak.adapters.RefreshableKeycloakSecurityContext)

Example 9 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project ff4j by ff4j.

the class FF4jSecurityContextFilter method filter.

/**
 * Apply the filter : check input request, validate or not with user auth
 *
 * @param containerRequest
 *            The request from Tomcat server
 */
@Override
public ContainerRequest filter(ContainerRequest containerRequest) throws WebApplicationException {
    String method = containerRequest.getMethod();
    String path = containerRequest.getPath(true);
    log.debug("Entering security filter for <" + path + ">");
    // We do allow wadl to be retrieve
    if (method.equals("GET") && (path.equals("application.wadl") || path.equals("application.wadl/xsd0.xsd"))) {
        log.info("Accessing schema and wadl ok");
        return containerRequest;
    }
    // Get the authentification passed in HTTP headers parameters
    String auth = containerRequest.getHeaderValue(HEADER_AUTHORIZATION);
    if (auth == null) {
        handleUnAuthorized("<p>'authorization' parameter is required in header  for authentication (HTTP-Basic or ApiKey)</p>");
    }
    // Identification of an Application with its api key
    if (auth.contains(PARAM_AUTHKEY)) {
        auth = auth.replaceFirst(PARAM_AUTHKEY + "=", "");
        // Checking api Key
        if (!securityConfig.getApiKeys().contains(auth)) {
            handleUnAuthorized("The api key provided '" + auth + "' is invalid ");
        }
        // Positionning Roles
        Set<String> perms = securityConfig.getPermissions().get(auth);
        SecurityContext sc = new FF4jSecurityContext(auth, PARAM_AUTHKEY, perms);
        containerRequest.setSecurityContext(sc);
        log.info("Client successfully logged with an ApiKey");
        return containerRequest;
    }
    // Identification of a final user in HTTP-BASIC MODE
    if (auth.toUpperCase().contains("BASIC")) {
        byte[] decodedBytes = Base64.decode(auth.replaceFirst("[B|b]asic ", ""));
        String[] lap = new String(decodedBytes).split(":", 2);
        if (lap == null || lap.length != 2) {
            handleUnAuthorized("Invalid BASIC Token, cannot parse");
        }
        // Validation login/password
        String expectedPassword = securityConfig.getUsers().get(lap[0]);
        if (expectedPassword == null || !(lap[1].equals(expectedPassword))) {
            handleUnAuthorized("<p>Invalid username or password.</p>");
        }
        // Positionning Roles
        Set<String> perms = securityConfig.getPermissions().get(lap[0]);
        SecurityContext sc = new FF4jSecurityContext(lap[0], "BASIC", perms);
        containerRequest.setSecurityContext(sc);
        log.info("Client successfully logged with a user/pasword pair ");
        return containerRequest;
    }
    handleUnAuthorized("Cannot parse authorisation header attribute, valid are basic and apiKey");
    return null;
}
Also used : SecurityContext(javax.ws.rs.core.SecurityContext)

Example 10 with SecurityContext

use of javax.ws.rs.core.SecurityContext in project minijax by minijax.

the class MinijaxApplication method checkSecurity.

private void checkSecurity(final MinijaxRequestContext context) {
    final Annotation a = context.getResourceMethod().getSecurityAnnotation();
    if (a == null) {
        return;
    }
    final Class<?> c = a.annotationType();
    if (c == PermitAll.class) {
        return;
    }
    if (c == DenyAll.class) {
        throw new ForbiddenException();
    }
    if (c == RolesAllowed.class) {
        final SecurityContext security = context.getSecurityContext();
        if (security == null || security.getUserPrincipal() == null) {
            throw new NotAuthorizedException(Response.status(Status.UNAUTHORIZED).build());
        }
        boolean found = false;
        for (final String role : ((RolesAllowed) a).value()) {
            if (security.isUserInRole(role)) {
                found = true;
                break;
            }
        }
        if (!found) {
            throw new ForbiddenException();
        }
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) RolesAllowed(javax.annotation.security.RolesAllowed) SecurityContext(javax.ws.rs.core.SecurityContext) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) Annotation(java.lang.annotation.Annotation)

Aggregations

SecurityContext (javax.ws.rs.core.SecurityContext)77 Response (javax.ws.rs.core.Response)30 Context (javax.ws.rs.core.Context)18 Test (org.junit.Test)18 List (java.util.List)17 Principal (java.security.Principal)16 LoggerFactory (org.slf4j.LoggerFactory)16 Logger (org.slf4j.Logger)12 ArrayList (java.util.ArrayList)11 Collectors (java.util.stream.Collectors)11 Path (javax.ws.rs.Path)11 IOException (java.io.IOException)10 POST (javax.ws.rs.POST)8 LocalPasswordHandler (com.emc.storageos.systemservices.impl.util.LocalPasswordHandler)6 GET (javax.ws.rs.GET)6 PathParam (javax.ws.rs.PathParam)6 Produces (javax.ws.rs.Produces)6 MediaType (javax.ws.rs.core.MediaType)6 Status (javax.ws.rs.core.Response.Status)6 UriInfo (javax.ws.rs.core.UriInfo)6