Example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Prototype

int SC_UNAUTHORIZED

To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.

Click Source Link

Document

Status code (401) indicating that the request requires HTTP authentication.

Usage

From source file:com.google.gsa.valve.modules.krb.KerberosAuthenticationProcess.java

/**
 * This is the main method that does the Kerberos authentication and 
 * should be invoked by the classes that would like to open a new 
 * authentication process against a Kerberized protected source.
 * <p>//ww  w  .  j ava  2s.c om
 * It behaves differently if the it's set up as a Negotiation process or 
 * the Kerberos credentials are got from the username and password 
 * credentials. It reads "isNegotiate" var and invokes the proper method 
 * that manages Kerberos authentication specifically for each method.
 * <p>
 * If the Kerberos authentication result is OK, a cookie is created with an  
 * encoded information that includes the username to be reused if this is 
 * needed in any other Authn/AuthZ module. It also populates the credentials 
 * vector with the user's Kerberos credential ("krb5") that the caller 
 * process should reuse when authorizing.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    //Vars             
    int responseCode = HttpServletResponse.SC_UNAUTHORIZED;
    Cookie[] cookies = null;

    // Read cookies
    cookies = request.getCookies();

    //Protection
    logger.debug("Checking if user already has Krb credentials. If so, return OK");

    try {
        if (creds != null) {
            if (creds.getCredential(KRB5_ID) != null) {

                logger.debug("Credential found: " + KRB5_ID);

                if (creds.getCredential(KRB5_ID).getSubject() != null) {

                    //user Kerberos subject already created, so user is authenticated                        
                    logger.debug("Kerberos subject already exists. Returning...");

                    // Set status code
                    responseCode = HttpServletResponse.SC_OK;

                    // Return
                    return responseCode;
                }
            }
        }
    } catch (NullPointerException e) {
        logger.debug("Krb subject does not exist. Continue with the process...");
    }

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    try {
        logger.debug("Getting credentials");
        //Get Krb config files            
        krbconfig = valveConf.getKrbConfig().getKrbconfig();
        logger.debug("Krb config file: " + krbconfig);
        krbini = valveConf.getKrbConfig().getKrbini();
        logger.debug("Krb ini file: " + krbini);

        if ((isNegotiate) && (serverSubject == null)) {

            try {

                initializeKerberos();

            } catch (Exception ex) {
                logger.error("Exception during Server Kerberos config initialization: " + ex.getMessage(), ex);
            } finally {
            }

        }

        //Get user credentials
        //First read the u/p the credentails store, in this case using the same as the root login
        Credential userNamePwdCred = null;

        if (isNegotiate) {
            logger.debug("KerbAuth: IsNegotiate");
            responseCode = authNegotiate(request, response);
        } else {
            logger.debug("KerbAuth: It's NOT IsNegotiate with id: " + id);

            try {
                logger.debug("HttpKrb: trying to get creds from repository id: " + id);
                userNamePwdCred = creds.getCredential(id);
            } catch (NullPointerException npe) {
                logger.error("NPE while reading credentials of ID: " + id);
            }

            if (userNamePwdCred == null) {
                logger.debug("HttpKrb: trying to get creds from repository \"root\"");
                userNamePwdCred = creds.getCredential("root");
            }

            //Execute Authentication method with username and password
            responseCode = authUsernamePassword(userNamePwdCred);
        }

        if (responseCode == HttpServletResponse.SC_OK) {
            //create cookie
            createCookie(request, response);
            //add cookie to the cookie array
            authCookies.add(gsaKrbAuthCookie);
            //add Krb credentials
            Credential krb5Cred = new Credential(KRB5_ID);
            krb5Cred.setKrbSubject(getUserSubject());
            krb5Cred.setUsername(getUsername());
            creds.add(krb5Cred);
        }

    } catch (Exception e) {
        logger.debug("Error creating Credentials: " + e.getMessage());
        e.printStackTrace();
        responseCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    }

    return responseCode;
}

From source file:com.liferay.jsonwebserviceclient.JSONWebServiceClientImpl.java

protected String execute(HttpRequestBase httpRequestBase) throws CredentialException, IOException {

    HttpHost httpHost = new HttpHost(_hostName, _hostPort, _protocol);

    try {// www  .  j  av a  2  s.com
        if (_closeableHttpClient == null) {
            afterPropertiesSet();
        }

        HttpResponse httpResponse = _closeableHttpClient.execute(httpHost, httpRequestBase);

        StatusLine statusLine = httpResponse.getStatusLine();

        if (statusLine.getStatusCode() == HttpServletResponse.SC_NOT_FOUND) {

            if (_logger.isWarnEnabled()) {
                _logger.warn("Status code " + statusLine.getStatusCode());
            }

            return null;
        } else if (statusLine.getStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {

            throw new CredentialException("Not authorized to access JSON web service");
        } else if (statusLine.getStatusCode() == HttpServletResponse.SC_SERVICE_UNAVAILABLE) {

            throw new JSONWebServiceUnavailableException("Service unavailable");
        }

        return EntityUtils.toString(httpResponse.getEntity(), Charsets.UTF_8);
    } finally {
        httpRequestBase.releaseConnection();
    }
}

From source file:com.sg.rest.SpringSecurityTest.java

@Test
public void testExpiredAuthToken() throws IOException, Exception {
    String authToken = webSecurityService.generateToken(ACCOUNT_ID,
            Instant.now()//from w  w w  .j  a  v  a  2 s.c o  m
                    .minus(TokenExpirationStandardDurations.WEB_SESSION_TOKEN_EXPIRATION_DURATION.getDuration())
                    .minus(Duration.standardHours(1)),
            TokenExpirationStandardDurations.WEB_SESSION_TOKEN_EXPIRATION_DURATION);

    mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST).header(HttpCustomHeaders.AUTH_TOKEN_HEADER.getHeader(),
            authToken)).andExpect(status().is(HttpServletResponse.SC_UNAUTHORIZED))
            .andExpect(content().contentType(CustomMediaTypes.APPLICATION_JSON_UTF8.getMediatype()))
            .andExpect(jsonPath("$.eventRef.id", not(isEmptyOrNullString()))).andExpect(jsonPath("$.status",
                    is(AuthentificationFailureStatus.TOKEN_AUTHENTICATION_TOKEN_EXPIRED.name())));
}

From source file:org.opendatakit.aggregate.externalservice.OhmageJsonServer.java

/**
 * Uploads a set of submissions to the ohmage system.
 *
 * @throws IOException// w  w w.j  a va2 s.co  m
 * @throws ClientProtocolException
 * @throws ODKExternalServiceException
 * @throws URISyntaxException
 */
public void uploadSurveys(List<OhmageJsonTypes.Survey> surveys, Map<UUID, ByteArrayBody> photos,
        CallingContext cc)
        throws ClientProtocolException, IOException, ODKExternalServiceException, URISyntaxException {

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.STRICT, null, UTF_CHARSET);
    // emit the configured publisher parameters if the values are non-empty...
    String value;
    value = getOhmageCampaignUrn();
    if (value != null && value.length() != 0) {
        StringBody campaignUrn = new StringBody(getOhmageCampaignUrn(), UTF_CHARSET);
        reqEntity.addPart("campaign_urn", campaignUrn);
    }
    value = getOhmageCampaignCreationTimestamp();
    if (value != null && value.length() != 0) {
        StringBody campaignCreationTimestamp = new StringBody(getOhmageCampaignCreationTimestamp(),
                UTF_CHARSET);
        reqEntity.addPart("campaign_creation_timestamp", campaignCreationTimestamp);
    }
    value = getOhmageUsername();
    if (value != null && value.length() != 0) {
        StringBody user = new StringBody(getOhmageUsername(), UTF_CHARSET);
        reqEntity.addPart("user", user);
    }
    value = getOhmageHashedPassword();
    if (value != null && value.length() != 0) {
        StringBody hashedPassword = new StringBody(getOhmageHashedPassword(), UTF_CHARSET);
        reqEntity.addPart("passowrd", hashedPassword);
    }
    // emit the client identity and the json representation of the survey...
    StringBody clientParam = new StringBody(cc.getServerURL());
    reqEntity.addPart("client", clientParam);
    StringBody surveyData = new StringBody(gson.toJson(surveys));
    reqEntity.addPart("survey", surveyData);

    // emit the file streams for all the media attachments
    for (Entry<UUID, ByteArrayBody> entry : photos.entrySet()) {
        reqEntity.addPart(entry.getKey().toString(), entry.getValue());
    }

    HttpResponse response = super.sendHttpRequest(POST, getServerUrl(), reqEntity, null, cc);
    String responseString = WebUtils.readResponse(response);
    int statusCode = response.getStatusLine().getStatusCode();

    if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
        throw new ODKExternalServiceCredentialsException(
                "failure from server: " + statusCode + " response: " + responseString);
    } else if (statusCode >= 300) {
        throw new ODKExternalServiceException(
                "failure from server: " + statusCode + " response: " + responseString);
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.JWSAuthenticationProcessFilterTest.java

@Test
public void testJWSAuthenticationFilterFailInvalidHeader() throws Exception {
    //environement
    String content = "";
    String requestURL = "http://localhost:8080";
    ServletInputStream emptyContent = new DelegatingServletInputStream(
            new ByteArrayInputStream(content.getBytes()));
    ArgumentCaptor<Integer> errorCode = ArgumentCaptor.forClass(Integer.class);
    when(request.getHeader(JWSAuthenticationProcessingFilter.JWS_AUTH_HEADER))
            .thenReturn(JWSAuthenticationProcessingFilter.JWS_AUTH_HEADER_TOKEN_MARK + "invalidHash");
    when(request.getInputStream()).thenReturn(emptyContent);
    when(request.getRequestURL()).thenReturn(new StringBuffer(requestURL));

    //test//ww  w. j  av a  2  s.  c o m
    myJWSFilter.doFilter(request, response, chain);

    //verify
    verify(chain, times(0)).doFilter(any(ServletRequest.class), any(ServletResponse.class));
    verify(response, times(1)).sendError(errorCode.capture());//check sendError is not set
    int errorCodeValue = errorCode.getValue().intValue();
    logger.info("Response error:{}", errorCodeValue);
    Assert.assertEquals("sendError should be:", HttpServletResponse.SC_UNAUTHORIZED, errorCodeValue);

}

From source file:eionet.webq.web.interceptor.CdrAuthorizationInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    String authorization = request.getHeader(AUTHORIZATION_HEADER);
    //        if (true) return PROCEED;
    if (StringUtils.isNotEmpty(authorization) || request.getParameter("auth") != null) {
        // if Basic auth is present in the request, then try to log in to CDR to test if it is valid token for given domain.
        // "auth" parameter is just meant for testing the CDR API in development environment - WebQ asks to authenticate.
        HttpHeaders headers = new HttpHeaders();
        headers.add(AUTHORIZATION_HEADER, authorization);
        //            return PROCEED;
        try {/*  w w w .  j  ava  2  s . c o m*/
            ResponseEntity<String> loginResponse = restOperations.postForEntity(
                    extractCdrUrl(request) + "/" + cdrLoginMethod, new HttpEntity<Object>(headers),
                    String.class);
            LOGGER.info("Response code received from CDR basic authorization request "
                    + loginResponse.getStatusCode());
            return PROCEED;
        } catch (HttpStatusCodeException e) {
            if (e.getStatusCode() != HttpStatus.UNAUTHORIZED) {
                LOGGER.warn("Authorization against CDR failed with unexpected HTTP status code", e);
            }
        }
    } else {
        // if Basic auth is not present, then test if user is already authorised in this domain
        // by using provided cookies to fetch CDR envelope properties page.
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            HttpHeaders headers = new HttpHeaders();
            for (Cookie cookie : cookies) {
                // put ZopeId parameter to request header. It works only when the value is surrounded with quotes.
                headers.add("Cookie", cookiesConverter.convertCookieToString(cookie));
            }
            String urlToFetch = extractCdrEnvelopeUrl(request) + "/" + cdrEnvelopePropertiesMethod;
            //ResponseEntity<String> loginResponse = restOperations.exchange(urlToFetch, HttpMethod.GET,
            //        new HttpEntity<Object>(headers), String.class);

            HttpResponse responseFromCdr = fetchUrlWithoutRedirection(urlToFetch, headers);
            try {
                int statusCode = responseFromCdr.getStatusLine().getStatusCode();

                LOGGER.info("Response code received from CDR envelope request using cookies " + statusCode);
                if (statusCode == HttpStatus.OK.value()) {
                    request.setAttribute(PARSED_COOKIES_ATTRIBUTE,
                            cookiesConverter.convertCookiesToString(cookies));
                    return PROCEED;
                } else if ((statusCode == HttpStatus.MOVED_PERMANENTLY.value()
                        || statusCode == HttpStatus.MOVED_TEMPORARILY.value())
                        && responseFromCdr.getFirstHeader("Location") != null) {
                    // redirect to CDR login page
                    String redirectUrl = extractCdrUrl(request)
                            + responseFromCdr.getFirstHeader("Location").getValue();
                    LOGGER.info("Redirect to " + redirectUrl);
                    response.sendRedirect(redirectUrl);
                }
            } catch (HttpStatusCodeException e) {
                if (e.getStatusCode() != HttpStatus.UNAUTHORIZED) {
                    LOGGER.warn("Fetching CDR envelope page failed with unexpected HTTP status code", e);
                }
            }
        }
    }

    if (isFailureCountsEqualsToAllowedFailuresCount()) {
        request.setAttribute(AUTHORIZATION_FAILED_ATTRIBUTE, AUTHORIZATION_FAILED_ATTRIBUTE);
        session.removeAttribute(AUTHORIZATION_TRY_COUNT);
        return PROCEED;
    }

    increaseFailedAuthorizationsCount();
    response.addHeader("WWW-Authenticate", "Basic realm=\"Please login to use webforms.\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    return STOP_REQUEST_PROPAGATION;
}

From source file:com.googlecode.noweco.calendar.CaldavServlet.java

@SuppressWarnings("unchecked")
@Override/*ww  w . ja  v a  2s .co m*/
public void service(final HttpServletRequest req, final HttpServletResponse resp)
        throws ServletException, IOException {
    String method = req.getMethod();
    if (LOGGER.isDebugEnabled()) {
        List<String> headers = Collections.list((Enumeration<String>) req.getHeaderNames());
        LOGGER.debug("Command : {}, Appel : {}, headers {}",
                new Object[] { method, req.getRequestURI(), headers });
    }

    if (!authent(req)) {
        resp.addHeader("WWW-Authenticate", "BASIC realm=\"Noweco CalDAV\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }
    String requestURI = req.getRequestURI();
    if (requestURI.length() != 0 && requestURI.charAt(0) != '/') {
        // unknown relative URI
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    try {
        if (METHOD_PROPFIND.equals(method)) {
            doPropfind(req, resp);
        } else if (METHOD_REPORT.equals(method)) {
            doReport(req, resp);
        } else {
            super.service(req, resp);
        }
    } catch (Throwable e) {
        LOGGER.error("Unexpected throwable", e);
    }
}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles a request of getting all the collections in the project of the
 * given id. Not yet implemented.//  ww w  .j a va 2s  . co  m
 * 
 * @param idpart
 * @param mimeType
 * @param modifiedSince
 * @param request
 * @throws IOException
 */
@RequestMapping(value = "/{idpart}/collections", method = { RequestMethod.GET })
public void handleProjectCollectionsGetRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp) throws IOException, BizPolicyException {

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {

        String id = util.buildRequestUrl(request);

        //The ID will come back with collections on the end of it since it's part of the request. 
        //It needs to be removed. 
        id = id.substring(0, id.length() - 12);

        Project project = projectService.get(id);

        if (project != null) {
            if (authorizationService.canReadProject(user, project)) {
                resp.setCharacterEncoding("UTF-8");
                resp.setContentType("text/xml");
                Set<Collection> collections = projectBizService.getCollectionsForProject(project, user);
                Bop bop = new Bop();
                bop.setCollections(collections);
                objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        } else {
            try {
                resp.setStatus(HttpStatus.SC_NOT_FOUND);
                resp.getWriter().print("Could not find project with id: " + idpart);
                resp.getWriter().flush();
                resp.getWriter().close();
            } catch (Exception ee) {
                log.debug("Handling exception", ee);
            }
        }
    }
}

From source file:com.lucidworks.security.authentication.server.TestKerberosAuthenticationHandler.java

public void testRequestWithAuthorization() throws Exception {
    String token = KerberosTestUtils.doAsClient(new Callable<String>() {
        @Override/*  w  w  w.  j a  v a  2s .  c  o  m*/
        public String call() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext gssContext = null;
            try {
                String servicePrincipal = KerberosTestUtils.getServerPrincipal();
                Oid oid = KerberosUtil.getOidInstance("NT_GSS_KRB5_PRINCIPAL");
                GSSName serviceName = gssManager.createName(servicePrincipal, oid);
                oid = KerberosUtil.getOidInstance("GSS_KRB5_MECH_OID");
                gssContext = gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);

                byte[] inToken = new byte[0];
                byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                Base64 base64 = new Base64(0);
                return base64.encodeToString(outToken);

            } finally {
                if (gssContext != null) {
                    gssContext.dispose();
                }
            }
        }
    });

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
            .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);

    AuthenticationToken authToken = handler.authenticate(request, response);

    if (authToken != null) {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

        Assert.assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
        Assert.assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
        Assert.assertEquals(getExpectedType(), authToken.getType());
    } else {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java

@RequestMapping(method = RequestMethod.PUT, value = "user/notification/{id}")
public @ResponseBody void updateByUser(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable("id") String id, @RequestBody Notification notification)
        throws DataException, IOException, NotFoundException, SmartCampusException {

    String userId = getUserId();// w w  w. j ava  2  s.  c  om
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }

    notificationManager.updateLabelsByUser(id, userId, notification.getLabelIds());
    notificationManager.starredByUser(id, userId, notification.isStarred());
}