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:no.kantega.publishing.security.action.LoginAction.java

public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String username = request.getParameter("j_username");
    String domain = request.getParameter("j_domain");
    String password = request.getParameter("j_password");
    String redirect = defaultString(request.getParameter("redirect"), Aksess.getContextPath());
    String rememberMe = request.getParameter("remember_me");

    if (loginRequireSsl && !request.isSecure()) {
        return redirectToSecure(request);
    }//w  w w  . j ava  2  s.co m

    // If login page is secure, redirect to secure page after logging in
    if (request.isSecure() && redirect.startsWith("http:")) {
        redirect = redirect.replaceFirst("http:", "https:");
    }

    // Checks if no roles exists and redirects to setup page
    if (!rolesExists) {
        return new ModelAndView(new RedirectView(Aksess.getContextPath() + "/CreateInitialUser.action"));
    }

    ResetPasswordTokenManager resetPasswordTokenManager = getResetPasswordTokenManager();

    Map<String, Object> model = new HashMap<>();
    model.put("redirect", StringEscapeUtils.escapeHtml4(redirect));
    model.put("username", StringEscapeUtils.escapeHtml4(username));
    model.put("loginLayout", getLoginLayout());

    if (Aksess.isSecurityAllowPasswordReset() && resetPasswordTokenManager != null) {
        model.put("allowPasswordReset", true);
    }

    if (username != null && password != null) {
        Identity identity = DefaultIdentity.withDomainAndUserId(domain, username);

        boolean blockedUser = userLoginRestrictor.isBlocked(username);
        boolean blockedIp = ipLoginRestrictor.isBlocked(request.getRemoteAddr());

        if (blockedUser || blockedIp) {
            // User or ip should be blocked, to many login attempts
            if (blockedUser) {
                model.put("blockedUser", Boolean.TRUE);
                log.info("Too many attempts. User is blocked from login:" + username);
            } else {
                model.put("blockedIP", Boolean.TRUE);
                log.info("Too many attempts. IP-adress is blocked from login:" + request.getRemoteAddr());
            }
        } else {
            PasswordManager passwordManager = getPasswordManager(domain);

            if (passwordManager == null) {
                throw new ConfigurationException("PasswordManager == null for domain " + domain + "");
            }
            if (passwordManager.verifyPassword(identity, password)) {
                log.info("Verified password for " + identity.getUserId());
                if (twoFactorAuthenticationEnabled()) {
                    return handleTwoFactorAuthentication(identity, model);
                } else {
                    LoginHelper.registerSuccessfulLogin(userLoginRestrictor, ipLoginRestrictor, request,
                            username, domain);

                    boolean rememberMeEnabled = configuration.getBoolean("security.login.rememberme.enabled",
                            false);
                    if (rememberMeEnabled && rememberMe != null && rememberMe.equals("on")) {
                        rememberMeHandler.rememberUser(response, username, domain);
                    }

                    return new ModelAndView(new RedirectView(redirect));
                }
            } else {
                // Register failed login
                userLoginRestrictor.registerLoginAttempt(username, false);
                ipLoginRestrictor.registerLoginAttempt(request.getRemoteAddr(), false);

                eventLog.log(username, request.getRemoteAddr(), Event.FAILED_LOGIN, username, null);
                model.put("loginfailed", Boolean.TRUE);
            }
        }
    }

    return new ModelAndView(loginView, model);
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testShowGetLoginNoRelayState() throws WSSecurityException {
    String samlRequest = authNRequestGet;
    idpEndpoint.setStrictSignature(false);
    HttpServletRequest request = mock(HttpServletRequest.class);

    when(request.isSecure()).thenReturn(true);

    Response response = idpEndpoint.showGetLogin(samlRequest, null, signatureAlgorithm, signature, request);
    assertThat(response.getEntity().toString(), containsString("SAMLRequest"));
    assertThat(response.getEntity().toString(), containsString("ACSURL"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testShowGetLogin() throws WSSecurityException {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);

    when(request.isSecure()).thenReturn(true);

    Response response = idpEndpoint.showGetLogin(samlRequest, relayState, signatureAlgorithm, signature,
            request);//  ww  w. j av  a  2 s. co  m

    assertThat(response.getEntity().toString(), containsString("SAMLRequest"));
    assertThat(response.getEntity().toString(), containsString("RelayState"));
    assertThat(response.getEntity().toString(), containsString("ACSURL"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testUnsupportedAuthMethod() {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");

    Response response = idpEndpoint.processLogin(samlRequest, relayState, "notsupported", signatureAlgorithm,
            signature, SamlProtocol.Binding.SOAP.getUri(), request);

    assertThat(response.getStatus(), is(400));
}

From source file:be.fedict.eid.idp.protocol.openid.AbstractOpenIDProtocolService.java

private IncomingRequest doAssociation(HttpServletRequest request, HttpServletResponse response,
        ServerManager serverManager, ParameterList parameterList)
        throws IOException, MessageException, AssociationException {

    /*//from   w ww .  ja  v a  2 s  . co m
     * If not running over SSL, only allow DH
     */
    if (!request.isSecure()) {
        AssociationRequest associationRequest = AssociationRequest.createAssociationRequest(parameterList);
        AssociationSessionType associationSessionType = associationRequest.getType();
        if (associationSessionType.getHAlgorithm() == null) {
            throw new AssociationException("Not running over " + "SSL requires DH.");
        }
    }

    LOG.debug("associate");
    Message message = serverManager.associationResponse(parameterList);
    String keyValueFormEncoding = message.keyValueFormEncoding();
    LOG.debug("form encoding: " + keyValueFormEncoding);
    PrintWriter printWriter = response.getWriter();
    printWriter.print(keyValueFormEncoding);
    return null;
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testShowPostLogin() throws WSSecurityException {
    idpEndpoint.setStrictSignature(false);
    String samlRequest = authNRequestPost;
    relayState = "94697cdc-e64f-4edf-b26a-52c14c2314dd";
    HttpServletRequest request = mock(HttpServletRequest.class);

    when(request.isSecure()).thenReturn(true);

    Response response = idpEndpoint.showPostLogin(samlRequest, relayState, request);

    assertThat(response.getEntity().toString(), containsString("SAMLRequest"));
    assertThat(response.getEntity().toString(), containsString("RelayState"));
    assertThat(response.getEntity().toString(), containsString("ACSURL"));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testProcessLoginGuest() throws CertificateEncodingException {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");

    Response response = idpEndpoint.processLogin(samlRequest, relayState, Idp.GUEST, signatureAlgorithm,
            signature, SamlProtocol.REDIRECT_BINDING, request);

    assertThat(response.getEntity().toString(), containsString(ssoSAMLResponse));
    assertThat(response.getEntity().toString(), containsString("RelayState="));
}

From source file:org.codice.ddf.security.idp.server.IdpEndpointTest.java

@Test
public void testProcessLoginBasic() {
    String samlRequest = authNRequestGet;
    HttpServletRequest request = mock(HttpServletRequest.class);

    when(request.isSecure()).thenReturn(true);
    when(request.getRequestURL()).thenReturn(requestURL);
    when(request.getAttribute(ContextPolicy.ACTIVE_REALM)).thenReturn("*");
    //admin:admin
    when(request.getHeader(HttpHeaders.AUTHORIZATION)).thenReturn("Basic YWRtaW46YWRtaW4=");

    Response response = idpEndpoint.processLogin(samlRequest, relayState, Idp.USER_PASS, signatureAlgorithm,
            signature, SamlProtocol.REDIRECT_BINDING, request);

    assertThat(response.getEntity().toString(), containsString(ssoSAMLResponse));
    assertThat(response.getEntity().toString(), containsString("RelayState="));
}

From source file:org.tolven.restful.UserFilter.java

@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;
    HttpSession session = request.getSession();
    //      LoginContext loginContext = (LoginContext) session.getAttribute("loginContext");
    Principal principal = request.getUserPrincipal();
    // If we have a principal, then we can proceed
    if (principal != null) {
        chain.doFilter(servletRequest, servletResponse);
        return;//  w  ww .j ava2  s  . c o  m
    }
    // before we accept a password, must ensure that this is a secure session
    if (!request.isSecure()) {
        response.setStatus(403);
        return;
    }
    String authorizationHeader = request.getHeader("Authorization");
    // See if we have the username/password
    if (authorizationHeader != null && authorizationHeader.startsWith("Basic ")) {
        Base64 decoder = new Base64();
        byte[] decoded = decoder.decode(authorizationHeader.substring(6).getBytes());
        String[] usernamePassword = new String(decoded).split(":");
        //WebAuthentication webA = new WebAuthentication();
        //boolean loginStatus = webA.login(usernamePassword[0], usernamePassword[1]);
        //if (!loginStatus) {
        //   response.setStatus(403);
        //   System.out.println( "Login for " + usernamePassword[0] + " - failed");
        //   return;
        //}
        System.out.println("Login for " + usernamePassword[0] + " - succeeded");
        //principal = new TolvenPrincipal(usernamePassword[0]);
        Subject subject = new Subject();
        subject.getPrincipals().add(principal);
        //            loginContext = new LoginContext("tolvenLDAP", subject, new CB(usernamePassword[0], usernamePassword[1].toCharArray()));
        //            loginContext.login();
        // Success
        //         session.setAttribute("loginContext", loginContext);
        chain.doFilter(servletRequest, servletResponse);
    } else {
        // Ask for password now
        response.setStatus(401);
        response.setHeader("WWW-Authenticate", "Basic realm=\"tolvenLDAP\"");
    }
}

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

/**
 * Retrieves the access configuration for this NiFi.
 *
 * @param httpServletRequest the servlet request
 * @return A accessConfigurationEntity/*w w  w  . j  a  v a2s . c  o m*/
 */
@GET
@Consumes(MediaType.WILDCARD)
@Produces(MediaType.APPLICATION_JSON)
@Path("config")
@ApiOperation(value = "Retrieves the access configuration for this NiFi", response = AccessConfigurationEntity.class)
public Response getLoginConfig(@Context HttpServletRequest httpServletRequest) {

    final AccessConfigurationDTO accessConfiguration = new AccessConfigurationDTO();

    // specify whether login should be supported and only support for secure requests
    accessConfiguration.setSupportsLogin(loginIdentityProvider != null && httpServletRequest.isSecure());

    // create the response entity
    final AccessConfigurationEntity entity = new AccessConfigurationEntity();
    entity.setConfig(accessConfiguration);

    // generate the response
    return clusterContext(generateOkResponse(entity)).build();
}