Example usage for javax.servlet.http HttpServletRequest isSecure

List of usage examples for javax.servlet.http HttpServletRequest isSecure

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest isSecure.

Prototype

public boolean isSecure();

Source Link

Document

Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.

Usage

From source file:com.lc.storefront.interceptors.beforeview.SeoRobotsFollowBeforeViewHandler.java

@Override
public void beforeView(final HttpServletRequest request, final HttpServletResponse response,
        final ModelAndView modelAndView) {
    // Check to see if the controller has specified a Index/Follow directive for robots
    if (modelAndView != null
            && !modelAndView.getModel().containsKey(ThirdPartyConstants.SeoRobots.META_ROBOTS)) {
        // Build a default directive
        String robotsValue = ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW;

        if (RequestMethod.GET.name().equalsIgnoreCase(request.getMethod())) {
            if (request.isSecure()) {
                robotsValue = ThirdPartyConstants.SeoRobots.NOINDEX_FOLLOW;
            }/*from www  . ja v a  2  s  . c  o  m*/
            //Since no model attribute metaRobots can be set for JSON response, then configure that servlet path in the xml.
            //If its a regular response and this setting has to be overriden then set model attribute metaRobots
            else if (CollectionUtils.contains(getRobotIndexForJSONMapping().keySet().iterator(),
                    request.getServletPath())) {
                robotsValue = getRobotIndexForJSONMapping().get(request.getServletPath());
            } else {
                robotsValue = ThirdPartyConstants.SeoRobots.INDEX_FOLLOW;
            }
        } else if (RequestMethod.POST.name().equalsIgnoreCase(request.getMethod())) {
            robotsValue = ThirdPartyConstants.SeoRobots.NOINDEX_NOFOLLOW;
        }

        modelAndView.addObject(ThirdPartyConstants.SeoRobots.META_ROBOTS, robotsValue);
    }

    if (modelAndView != null && modelAndView.getModel().containsKey("metatags")) {
        final MetaElementData metaElement = new MetaElementData();
        metaElement.setName("robots");
        metaElement.setContent((String) modelAndView.getModel().get(ThirdPartyConstants.SeoRobots.META_ROBOTS));
        ((List<MetaElementData>) modelAndView.getModel().get("metatags")).add(metaElement);
    }
}

From source file:org.kuali.kfs.sys.web.controller.DataObjectRestServiceController.java

protected void validateRequest(FinancialSystemBusinessObjectEntry boe, String namespace, String dataobject,
        HttpServletRequest request) throws Exception {
    // check for https (will be ignored in dev mode), authorization
    if ((!ConfigContext.getCurrentContextConfig().getDevMode() && !request.isSecure())) {
        LOG.debug("HTTPS check failed.");
        throw new AccessDeniedException("Not authorized.");
    }/*from   w w  w  . jav  a 2  s.  c om*/

    if (boe == null) {
        LOG.debug("BusinessObjectEntry is null.");
        throw new NoSuchBeanDefinitionException("Data object not found.");
    }

    if (!namespace.equalsIgnoreCase(KRADUtils.getNamespaceCode(boe.getBusinessObjectClass()))) {
        LOG.debug("Bad namespace for dataobject: " + boe.getBusinessObjectClass());
        throw new NoSuchBeanDefinitionException("Invalid namespace.");
    }

    Boolean isModuleLocked = getParameterService().getParameterValueAsBoolean(namespace,
            KfsParameterConstants.PARAMETER_ALL_DETAIL_TYPE,
            KRADConstants.SystemGroupParameterNames.OLTP_LOCKOUT_ACTIVE_IND);
    boolean notAuthorized = !isAuthorized(boe);
    boolean moduleIsLocked = isModuleLocked != null && isModuleLocked;
    boolean noInquiryDefinition = !boe.hasInquiryDefinition();

    if (notAuthorized || moduleIsLocked || noInquiryDefinition) {
        LOG.debug("notAuthorized: " + notAuthorized);
        LOG.debug("moduleIsLocked: " + moduleIsLocked);
        LOG.debug("noInquiryDefinition: " + noInquiryDefinition);

        throw new AccessDeniedException("Not authorized.");
    }
}

From source file:org.apache.nifi.web.api.AccessResource.java

/**
 * Gets the status the client's access.//from w  ww  .  j a  v a 2 s  .c o m
 *
 * @param httpServletRequest the servlet request
 * @return A accessStatusEntity
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("")
@ApiOperation(value = "Gets the status the client's access", notes = NON_GUARANTEED_ENDPOINT, response = AccessStatusEntity.class)
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 401, message = "Unable to determine access status because the client could not be authenticated."),
        @ApiResponse(code = 403, message = "Unable to determine access status because the client is not authorized to make this request."),
        @ApiResponse(code = 409, message = "Unable to determine access status because NiFi is not in the appropriate state."),
        @ApiResponse(code = 500, message = "Unable to determine access status because an unexpected error occurred.") })
public Response getAccessStatus(@Context HttpServletRequest httpServletRequest) {

    // only consider user specific access over https
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException(
                "User authentication/authorization is only supported when running over HTTPS.");
    }

    final AccessStatusDTO accessStatus = new AccessStatusDTO();

    try {
        final X509Certificate[] certificates = certificateExtractor
                .extractClientCertificate(httpServletRequest);

        // if there is not certificate, consider a token
        if (certificates == null) {
            // look for an authorization token
            final String authorization = httpServletRequest.getHeader(JwtAuthenticationFilter.AUTHORIZATION);

            // if there is no authorization header, we don't know the user
            if (authorization == null) {
                accessStatus.setStatus(AccessStatusDTO.Status.UNKNOWN.name());
                accessStatus.setMessage("No credentials supplied, unknown user.");
            } else {
                try {
                    // Extract the Base64 encoded token from the Authorization header
                    final String token = StringUtils.substringAfterLast(authorization, " ");

                    final JwtAuthenticationRequestToken jwtRequest = new JwtAuthenticationRequestToken(token,
                            httpServletRequest.getRemoteAddr());
                    final NiFiAuthenticationToken authenticationResponse = (NiFiAuthenticationToken) jwtAuthenticationProvider
                            .authenticate(jwtRequest);
                    final NiFiUser nifiUser = ((NiFiUserDetails) authenticationResponse.getDetails())
                            .getNiFiUser();

                    // set the user identity
                    accessStatus.setIdentity(nifiUser.getIdentity());

                    // attempt authorize to /flow
                    accessStatus.setStatus(AccessStatusDTO.Status.ACTIVE.name());
                    accessStatus.setMessage("You are already logged in.");
                } catch (JwtException e) {
                    throw new InvalidAuthenticationException(e.getMessage(), e);
                }
            }
        } else {
            try {
                final X509AuthenticationRequestToken x509Request = new X509AuthenticationRequestToken(
                        httpServletRequest.getHeader(ProxiedEntitiesUtils.PROXY_ENTITIES_CHAIN),
                        principalExtractor, certificates, httpServletRequest.getRemoteAddr());

                final NiFiAuthenticationToken authenticationResponse = (NiFiAuthenticationToken) x509AuthenticationProvider
                        .authenticate(x509Request);
                final NiFiUser nifiUser = ((NiFiUserDetails) authenticationResponse.getDetails()).getNiFiUser();

                // set the user identity
                accessStatus.setIdentity(nifiUser.getIdentity());

                // attempt authorize to /flow
                accessStatus.setStatus(AccessStatusDTO.Status.ACTIVE.name());
                accessStatus.setMessage("You are already logged in.");
            } catch (final IllegalArgumentException iae) {
                throw new InvalidAuthenticationException(iae.getMessage(), iae);
            }
        }
    } catch (final UntrustedProxyException upe) {
        throw new AccessDeniedException(upe.getMessage(), upe);
    } catch (final AuthenticationServiceException ase) {
        throw new AdministrationException(ase.getMessage(), ase);
    }

    // create the entity
    final AccessStatusEntity entity = new AccessStatusEntity();
    entity.setAccessStatus(accessStatus);

    return generateOkResponse(entity).build();
}

From source file:org.nuxeo.ecm.core.io.download.DownloadServiceImpl.java

/**
 * Internet Explorer file downloads over SSL do not work with certain HTTP cache control headers
 * <p>//from   ww w  .  j  av a 2  s . com
 * See http://support.microsoft.com/kb/323308/
 * <p>
 * What is not mentioned in the above Knowledge Base is that "Pragma: no-cache" also breaks download in MSIE over
 * SSL
 */
protected void addCacheControlHeaders(HttpServletRequest request, HttpServletResponse response) {
    String userAgent = request.getHeader("User-Agent");
    boolean secure = request.isSecure();
    if (!secure) {
        String nvh = request.getHeader(NUXEO_VIRTUAL_HOST);
        if (nvh == null) {
            nvh = Framework.getProperty(VH_PARAM);
        }
        if (nvh != null) {
            secure = nvh.startsWith("https");
        }
    }
    String cacheControl;
    if (userAgent != null && userAgent.contains("MSIE") && (secure || forceNoCacheOnMSIE())) {
        cacheControl = "max-age=15, must-revalidate";
    } else {
        cacheControl = "private, must-revalidate";
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
    }
    log.debug("Setting Cache-Control: " + cacheControl);
    response.setHeader("Cache-Control", cacheControl);
}

From source file:org.wso2.carbon.ui.CarbonSecuredHttpContext.java

/**
 * //  ww  w .j  a  v  a  2s.  c om
 * @param requestedURI
 * @param request
 * @param response
 * @param authenticated
 * @param authenticator
 * @return
 * @throws IOException
 */
@SuppressWarnings("deprecation")
private int allowNonSecuredContent(String requestedURI, HttpServletRequest request,
        HttpServletResponse response, boolean authenticated, CarbonUIAuthenticator authenticator)
        throws IOException {
    if (!request.isSecure() && !(requestedURI.endsWith(".html"))) {

        // By passing items required for try-it & IDE plugins
        if (requestedURI.endsWith(".css") || requestedURI.endsWith(".gif") || requestedURI.endsWith(".GIF")
                || requestedURI.endsWith(".jpg") || requestedURI.endsWith(".JPG")
                || requestedURI.endsWith(".png") || requestedURI.endsWith(".PNG")
                || requestedURI.endsWith(".xsl") || requestedURI.endsWith(".xslt")
                || requestedURI.endsWith(".js") || requestedURI.endsWith(".ico")
                || requestedURI.endsWith("/filedownload") || requestedURI.endsWith("/fileupload")
                || requestedURI.contains("/fileupload/")
                || requestedURI.contains("admin/jsp/WSRequestXSSproxy_ajaxprocessor.jsp")
                || requestedURI.contains("registry/atom") || requestedURI.contains("registry/tags")
                || requestedURI.contains("gadgets/") || requestedURI.contains("registry/resource")) {
            return CarbonUILoginUtil.RETURN_TRUE;
        }

        String resourceURI = requestedURI.replaceFirst("/carbon/", "../");

        // By passing the pages which are specified as bypass https
        if (httpUrlsToBeByPassed.containsKey(resourceURI)) {
            if (!authenticated) {
                try {
                    Cookie[] cookies = request.getCookies();
                    if (cookies != null) {
                        for (Cookie cookie : cookies) {
                            if (cookie.getName().equals(CarbonConstants.REMEMBER_ME_COOKE_NAME)
                                    && authenticator != null) {
                                try {
                                    authenticator.authenticateWithCookie(request);
                                } catch (AuthenticationException ignored) {
                                    // We can ignore here and proceed with normal login.
                                    if (log.isDebugEnabled()) {
                                        log.debug(ignored);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                    throw new IOException(e.getMessage(), e);
                }
            }
            return CarbonUILoginUtil.RETURN_TRUE;
        }

        String enableHTTPAdminConsole = CarbonUIServiceComponent.getServerConfiguration()
                .getFirstProperty(CarbonConstants.ENABLE_HTTP_ADMIN_CONSOLE);

        if (enableHTTPAdminConsole == null || "false".equalsIgnoreCase(enableHTTPAdminConsole.trim())) {
            String adminConsoleURL = CarbonUIUtil.getAdminConsoleURL(request);
            if (adminConsoleURL != null) {
                if (log.isTraceEnabled()) {
                    log.trace("Request came to admin console via http.Forwarding to : " + adminConsoleURL);
                }
                response.sendRedirect(adminConsoleURL);
                return CarbonUILoginUtil.RETURN_FALSE;
            }
        }
    }

    return CarbonUILoginUtil.CONTINUE;
}

From source file:ru.org.linux.topic.DeleteTopicController.java

@RequestMapping(value = "/undelete.jsp", method = RequestMethod.GET)
public ModelAndView undeleteForm(HttpServletRequest request, @RequestParam int msgid) throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isModeratorSession()) {
        throw new AccessViolationException("Not authorized");
    }/*from  w ww .j ava2s. c  o  m*/

    Topic message = messageDao.getById(msgid);

    checkUndeletable(message);

    ModelAndView mv = new ModelAndView("undelete");
    mv.getModel().put("message", message);
    mv.getModel().put("preparedMessage",
            prepareService.prepareTopic(message, request.isSecure(), tmpl.getCurrentUser()));

    return mv;
}

From source file:org.jivesoftware.multiplexer.net.http.HttpBindServlet.java

private void createNewSession(HttpServletRequest request, HttpServletResponse response, Element rootNode)
        throws IOException {
    long rid = getLongAttribue(rootNode.attributeValue("rid"), -1);
    if (rid <= 0) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Body missing RID (Request ID)");
        return;// w  w w.java 2 s .  com
    }

    try {
        HttpConnection connection = new HttpConnection(rid, request.isSecure());
        InetAddress address = InetAddress.getByName(request.getRemoteAddr());
        connection.setSession(sessionManager.createSession(address, rootNode, connection));
        respond(response, connection, request.getMethod());
    } catch (HttpBindException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:org.wso2.carbon.device.mgt.iot.input.adapter.http.HTTPMessageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String data = this.inputStreamToString(req.getInputStream());
    if (data == null) {
        log.warn("Event Object is empty/null");
        return;/*w w w .  j a v a  2s.c om*/
    }
    AuthenticationInfo authenticationInfo = null;
    if (exposedTransports.equalsIgnoreCase(HTTPEventAdapterConstants.HTTPS)) {
        if (!req.isSecure()) {
            res.setStatus(403);
            log.error("Only Secured endpoint is enabled for requests");
            return;
        } else {
            authenticationInfo = this.checkAuthentication(req);
            int tenantId = authenticationInfo != null ? authenticationInfo.getTenantId() : -1;
            if (tenantId == -1) {
                res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                res.setStatus(401);
                log.error("Authentication failed for the request");
                return;
            } else if (tenantId != this.tenantId) {
                res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                res.setStatus(401);
                log.error("Authentication failed for the request");
                return;
            }
        }
    } else if (exposedTransports.equalsIgnoreCase(HTTPEventAdapterConstants.HTTP)) {
        if (req.isSecure()) {
            res.setStatus(403);
            log.error("Only unsecured endpoint is enabled for requests");
            return;
        }
    } else {
        authenticationInfo = this.checkAuthentication(req);
        int tenantId = authenticationInfo != null ? authenticationInfo.getTenantId() : -1;
        if (tenantId == -1) {
            res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
            res.setStatus(401);
            log.error("Authentication failed for the request");
            return;
        } else if (tenantId != this.tenantId) {
            res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
            res.setStatus(401);
            log.error("Authentication failed for the request");
            return;
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Message : " + data);
    }

    if (authenticationInfo != null) {
        Map<String, Object> paramMap = new HashMap<>();
        Enumeration<String> reqParameterNames = req.getParameterNames();
        while (reqParameterNames.hasMoreElements()) {
            String paramterName = reqParameterNames.nextElement();
            paramMap.put(paramterName, req.getParameter(paramterName));
        }
        paramMap.put(HTTPEventAdapterConstants.USERNAME_TAG, authenticationInfo.getUsername());
        paramMap.put(HTTPEventAdapterConstants.TENANT_DOMAIN_TAG, authenticationInfo.getTenantDomain());
        paramMap.put(HTTPEventAdapterConstants.SCOPE_TAG, authenticationInfo.getScopes());
        if (contentValidator != null && contentTransformer != null) {
            data = (String) contentTransformer.transform(data, paramMap);
            ContentInfo contentInfo = contentValidator.validate(data, paramMap);
            if (contentInfo != null && contentInfo.isValidContent()) {
                HTTPEventAdapter.executorService.submit(new HTTPRequestProcessor(eventAdaptorListener,
                        (String) contentInfo.getMessage(), tenantId));
            }
        }
    }
}

From source file:org.wso2.carbon.device.mgt.input.adapter.http.HTTPMessageServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {

    String data = this.inputStreamToString(req.getInputStream());
    if (data == null) {
        log.warn("Event Object is empty/null");
        return;/*from   w w  w  .  ja v  a  2 s .c om*/
    }
    AuthenticationInfo authenticationInfo = null;
    if (exposedTransports.equalsIgnoreCase(HTTPEventAdapterConstants.HTTPS)) {
        if (!req.isSecure()) {
            res.setStatus(403);
            log.error("Only Secured endpoint is enabled for requests");
            return;
        } else {
            authenticationInfo = this.checkAuthentication(req);
            int tenantId = authenticationInfo != null ? authenticationInfo.getTenantId() : -1;
            if (tenantId == -1) {
                res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                res.setStatus(401);
                log.error("Authentication failed for the request");
                return;
            } else if (tenantId != this.tenantId) {
                res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
                res.setStatus(401);
                log.error("Authentication failed for the request");
                return;
            }
        }
    } else if (exposedTransports.equalsIgnoreCase(HTTPEventAdapterConstants.HTTP)) {
        if (req.isSecure()) {
            res.setStatus(403);
            log.error("Only unsecured endpoint is enabled for requests");
            return;
        }
    } else {
        authenticationInfo = this.checkAuthentication(req);
        int tenantId = authenticationInfo != null ? authenticationInfo.getTenantId() : -1;
        if (tenantId == -1) {
            res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
            res.setStatus(401);
            log.error("Authentication failed for the request");
            return;
        } else if (tenantId != this.tenantId) {
            res.getOutputStream().write(AUTH_FAILURE_RESPONSE.getBytes());
            res.setStatus(401);
            log.error("Authentication failed for the request");
            return;
        }
    }

    if (log.isDebugEnabled()) {
        log.debug("Message : " + data);
    }

    if (authenticationInfo != null) {
        Map<String, Object> paramMap = new HashMap<>();
        Enumeration<String> reqParameterNames = req.getParameterNames();
        while (reqParameterNames.hasMoreElements()) {
            String paramterName = reqParameterNames.nextElement();
            paramMap.put(paramterName, req.getParameter(paramterName));
        }
        paramMap.put(HTTPEventAdapterConstants.USERNAME_TAG, authenticationInfo.getUsername());
        paramMap.put(HTTPEventAdapterConstants.TENANT_DOMAIN_TAG, authenticationInfo.getTenantDomain());
        paramMap.put(HTTPEventAdapterConstants.SCOPE_TAG, authenticationInfo.getScopes());
        String deviceId = (String) paramMap.get("deviceId");
        String deviceType = (String) paramMap.get("deviceType");
        if (deviceAuthorizer.isAuthorized(authenticationInfo, deviceId, deviceType)) {
            if (contentValidator != null && contentTransformer != null) {
                data = (String) contentTransformer.transform(data, paramMap);
                ContentInfo contentInfo = contentValidator.validate(data, paramMap);
                if (contentInfo != null && contentInfo.isValidContent()) {
                    HTTPEventAdapter.executorService.submit(new HTTPRequestProcessor(eventAdaptorListener,
                            (String) contentInfo.getMessage(), tenantId));
                }
            }
        } else {
            if (log.isDebugEnabled()) {
                log.debug("Unauthorized device with device id" + deviceId + " and device type" + deviceType);
            }
        }
    }
}

From source file:org.apache.nifi.web.api.AccessResource.java

/**
 * Creates a token for accessing the REST API via username/password.
 *
 * @param httpServletRequest the servlet request
 * @param username           the username
 * @param password           the password
 * @return A JWT (string)/*from   w w w  .j  a v  a 2s.c  o  m*/
 */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_PLAIN)
@Path("/token")
@ApiOperation(value = "Creates a token for accessing the REST API via username/password", notes = "The token returned is formatted as a JSON Web Token (JWT). The token is base64 encoded and comprised of three parts. The header, "
        + "the body, and the signature. The expiration of the token is a contained within the body. The token can be used in the Authorization header "
        + "in the format 'Authorization: Bearer <token>'.", response = String.class)
@ApiResponses(value = {
        @ApiResponse(code = 400, message = "NiFi was unable to complete the request because it was invalid. The request should not be retried without modification."),
        @ApiResponse(code = 403, message = "Client is not authorized to make this request."),
        @ApiResponse(code = 409, message = "Unable to create access token because NiFi is not in the appropriate state. (i.e. may not be configured to support username/password login."),
        @ApiResponse(code = 500, message = "Unable to create access token because an unexpected error occurred.") })
public Response createAccessToken(@Context HttpServletRequest httpServletRequest,
        @FormParam("username") String username, @FormParam("password") String password) {

    // only support access tokens when communicating over HTTPS
    if (!httpServletRequest.isSecure()) {
        throw new IllegalStateException("Access tokens are only issued over HTTPS.");
    }

    // if not configuration for login, don't consider credentials
    if (loginIdentityProvider == null) {
        throw new IllegalStateException("Username/Password login not supported by this NiFi.");
    }

    final LoginAuthenticationToken loginAuthenticationToken;

    // ensure we have login credentials
    if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
        throw new IllegalArgumentException("The username and password must be specified.");
    }

    try {
        // attempt to authenticate
        final AuthenticationResponse authenticationResponse = loginIdentityProvider
                .authenticate(new LoginCredentials(username, password));
        long expiration = validateTokenExpiration(authenticationResponse.getExpiration(),
                authenticationResponse.getIdentity());

        // create the authentication token
        loginAuthenticationToken = new LoginAuthenticationToken(authenticationResponse.getIdentity(),
                expiration, authenticationResponse.getIssuer());
    } catch (final InvalidLoginCredentialsException ilce) {
        throw new IllegalArgumentException("The supplied username and password are not valid.", ilce);
    } catch (final IdentityAccessException iae) {
        throw new AdministrationException(iae.getMessage(), iae);
    }

    // generate JWT for response
    final String token = jwtService.generateSignedToken(loginAuthenticationToken);

    // build the response
    final URI uri = URI.create(generateResourceUri("access", "token"));
    return generateCreatedResponse(uri, token).build();
}