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.attribyte.essem.BasicAuth.java

@Override
public void sendUnauthorized(final String index, final HttpServletResponse response) throws IOException {
    response.setHeader(WWW_AUTHENTICATE_HEADER, "Basic realm=" + "\"" + index + "\"");
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

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

private void sendRequest(String url, HttpEntity postBody, CallingContext cc)
        throws ODKExternalServiceException {
    try {//from ww  w.j a  va  2 s .  c o m

        HttpResponse resp = super.sendHttpRequest(POST, url, postBody, null, cc);
        WebUtils.readResponse(resp);

        // get response
        int statusCode = resp.getStatusLine().getStatusCode();
        String reason = resp.getStatusLine().getReasonPhrase();
        if (reason == null) {
            reason = BasicConsts.EMPTY_STRING;
        }
        if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) {
            throw new ODKExternalServiceCredentialsException(reason + " (" + statusCode + ")");
        } else if (statusCode != HttpServletResponse.SC_OK) {
            throw new ODKExternalServiceException(reason + " (" + statusCode + ")");
        }
    } catch (ODKExternalServiceException e) {
        throw e; // don't wrap these...
    } catch (Exception e) {
        throw new ODKExternalServiceException(e);// wrap...
    }
}

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

@RequestMapping(method = RequestMethod.DELETE, value = "/app/{capp:.*}/notification/{id}")
public @ResponseBody boolean deleteByApp(HttpServletRequest request, HttpServletResponse response,
        HttpSession session, @PathVariable("id") String id, @PathVariable("capp") String capp)
        throws DataException, IOException, NotFoundException, SmartCampusException {

    String userId = getUserId();/*from  ww w .  j  a v  a 2  s. co m*/
    if (userId == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }

    return notificationManager.deleteByApp(id, capp);
}

From source file:com.iorga.iraj.security.AbstractSecurityFilter.java

@Override
public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
        throws IOException, ServletException {
    // Extraction of the authentication header
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    final HttpServletResponse httpResponse = (HttpServletResponse) response;

    // First test if we will by pass the security with a token
    String bypassSecurityToken = httpRequest
            .getHeader(SecurityUtils.ADDITIONAL_BYPASS_SECURITY_TOKEN_HEADER_NAME);
    if (StringUtils.isEmpty(bypassSecurityToken)) {
        // check in the parameters
        bypassSecurityToken = httpRequest
                .getParameter(SecurityUtils.ADDITIONAL_BYPASS_SECURITY_TOKEN_HEADER_NAME);
    }//ww  w .ja  va2s  .c  o m
    if (StringUtils.isNotEmpty(bypassSecurityToken)) {
        // bypass security check
        String[] tokenParts = bypassSecurityToken.split(":");
        if (tokenParts.length != 2) {
            sendError(HttpServletResponse.SC_BAD_REQUEST, "Wrong token format", httpResponse);
        }
        String accessKeyId = tokenParts[0];
        String token = tokenParts[1];
        try {
            final TokenContext tokenContext = bypassSecurityTokenStore.removeToken(token);
            if (StringUtils.equals(accessKeyId, tokenContext.getPrincipalName())) {
                final S securityContext = findSecurityContext(accessKeyId);
                if (securityContext != null) {
                    // marking the request in order to filter it out later
                    httpRequest.setAttribute(SecurityUtils.SECURITY_BYPASSED_BY_TOKEN_ATTRIBUTE_NAME,
                            Boolean.TRUE);
                    doFilterWhenSecurityOK(httpRequest, httpResponse, chain, accessKeyId, securityContext);
                } else {
                    rejectAccessKeyId(accessKeyId, httpResponse);
                }
            } else {
                sendError(HttpServletResponse.SC_BAD_REQUEST, "Token is not yours", httpResponse);
            }
        } catch (Exception e) {
            sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid token", httpResponse, e);
        }
    } else {
        // classical security check
        final String authorizationHeader = httpRequest.getHeader(SecurityUtils.AUTHORIZATION_HEADER_NAME);
        if (authorizationHeader == null) {
            sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    "Need " + SecurityUtils.AUTHORIZATION_HEADER_NAME + " header", httpResponse);
        } else {
            final Matcher matcher = AUTHORIZATION_HEADER_PATTERN.matcher(authorizationHeader);
            if (matcher.find()) {
                final String accessKeyId = matcher.group(1);
                final String signature = matcher.group(2);
                String date = httpRequest.getHeader("Date");
                // Handle the additional date header
                final String additionalDate = httpRequest.getHeader(SecurityUtils.ADDITIONAL_DATE_HEADER_NAME);
                if (additionalDate != null) {
                    date = additionalDate;
                }
                try {
                    final S securityContext = findSecurityContext(accessKeyId);
                    if (securityContext != null) {
                        if (handleParsedDate(DateUtil.parseDate(date), securityContext, httpRequest,
                                httpResponse)) {
                            // Let's process the signature in order to compare it
                            final String secretAccessKey = securityContext.getSecretAccessKey();
                            try {
                                final MultiReadHttpServletRequest multiReadHttpRequest = new MultiReadHttpServletRequest(
                                        httpRequest);
                                final String serverSignature = SecurityUtils.computeSignature(secretAccessKey,
                                        new HttpServletRequestToSign(multiReadHttpRequest));
                                if (serverSignature.equalsIgnoreCase(signature)) {
                                    doFilterWhenSecurityOK(multiReadHttpRequest, httpResponse, chain,
                                            accessKeyId, securityContext);
                                } else {
                                    rejectSignature(signature, serverSignature, httpResponse);
                                }
                            } catch (final NoSuchAlgorithmException e) {
                                throw new ServletException(e);
                            } catch (final InvalidKeyException e) {
                                sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid key", httpResponse, e);
                            }
                        }
                    } else {
                        rejectAccessKeyId(accessKeyId, httpResponse);
                    }
                } catch (final ParseException e) {
                    sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid date", httpResponse,
                            "Have to parse '" + date + "'", e);
                } finally {
                    doFinallyAfterFindSecurityContext();
                }
            } else {
                sendError(HttpServletResponse.SC_BAD_REQUEST, "Request incorrectly formated", httpResponse,
                        "Got " + authorizationHeader);
            }
        }
    }
}

From source file:com.sun.socialsite.web.rest.servlets.UploadServlet.java

/**
 * Note: using SuppressWarnings annotation because the Commons FileUpload API is
 * not genericized./*from   w w w.ja v  a 2  s . c o m*/
 */
@Override
@SuppressWarnings(value = "unchecked")
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    try {

        // ensure calling app/gadget has perm to use SocialSite API
        SecurityToken token = new AuthInfo(req).getSecurityToken();
        Factory.getSocialSite().getPermissionManager().checkPermission(requiredPerm, token);

        GroupManager gmgr = Factory.getSocialSite().getGroupManager();
        ProfileManager pmgr = Factory.getSocialSite().getProfileManager();
        int errorCode = -1;
        Group group = null;
        Profile profile = null;

        // parse URL to get route and subjectId
        String route = null;
        String subjectId = "";
        if (req.getPathInfo() != null) {
            String[] pathInfo = req.getPathInfo().split("/");
            route = pathInfo[1];
            subjectId = pathInfo[2];
        }

        // first, figure out destination profile or group and check the
        // caller's permission to upload an image for that profile or group

        if ("profile".equals(route)) {
            if (token.getViewerId().equals(subjectId)) {
                profile = pmgr.getProfileByUserId(subjectId);
            } else {
                errorCode = HttpServletResponse.SC_UNAUTHORIZED;
            }

        } else if ("group".equals(route)) {
            group = gmgr.getGroupByHandle(subjectId);
            if (group != null) {
                // ensure called is group ADMIN or founder
                Profile viewer = pmgr.getProfileByUserId(token.getViewerId());
                GroupRelationship grel = gmgr.getMembership(group, viewer);
                if (grel == null || (grel.getRelcode() != GroupRelationship.Relationship.ADMIN
                        && grel.getRelcode() != GroupRelationship.Relationship.FOUNDER)) {
                } else {
                    errorCode = HttpServletResponse.SC_UNAUTHORIZED;
                }
            } else {
                // group not found
                errorCode = HttpServletResponse.SC_NOT_FOUND;
            }
        }

        // next, parse out the image and save it in profile or group

        if (errorCode != -1 && group == null && profile == null) {
            errorCode = HttpServletResponse.SC_NOT_FOUND;

        } else if (errorCode == -1) {

            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            FileItem fileItem = null;
            List<FileItem> items = (List<FileItem>) upload.parseRequest(req);
            if (items.size() > 0) {
                fileItem = items.get(0);
            }

            if ((fileItem != null) && (types.contains(fileItem.getContentType()))) {

                // read incomining image via Commons Upload
                InputStream is = fileItem.getInputStream();
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                Utilities.copyInputToOutput(is, baos);
                byte[] byteArray = baos.toByteArray();

                // save it in the profile or group indicated
                if (profile != null) {
                    profile.setImageType(fileItem.getContentType());
                    profile.setImage(byteArray);
                    pmgr.saveProfile(profile);
                    Factory.getSocialSite().flush();

                } else if (group != null) {
                    group.setImageType(fileItem.getContentType());
                    group.setImage(byteArray);
                    gmgr.saveGroup(group);
                    Factory.getSocialSite().flush();

                } else {
                    // group or profile not indicated properly
                    errorCode = HttpServletResponse.SC_NOT_FOUND;
                }
            }

        }

        if (errorCode == -1) {
            resp.sendError(HttpServletResponse.SC_OK);
            return;
        } else {
            resp.sendError(errorCode);
        }

    } catch (SecurityException sx) {
        log.error("Permission denied", sx);
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);

    } catch (FileUploadException fx) {
        log.error("ERROR uploading profile image", fx);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

    } catch (SocialSiteException ex) {
        log.error("ERROR saving profile image", ex);
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }

}

From source file:edu.indiana.d2i.htrc.oauth2.userinfo.OAuth2UserInfoEndpoint.java

private Response handleBasicAuthFailure() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
            .setError(OAuth2ErrorCodes.INVALID_CLIENT).setErrorDescription("Client Authentication was failed.")
            .buildJSONMessage();/*from   w  ww .  j  a  v  a2  s  .  c  o m*/
    return Response.status(response.getResponseStatus())
            .header(OAuthConstants.HTTP_RESP_HEADER_AUTHENTICATE, OAuthUIUtil.getRealmInfo())
            .entity(response.getBody()).build();
}

From source file:com.cloud.api.ApiServletTest.java

@SuppressWarnings("unchecked")
@Test// ww w.ja  v  a 2s.  c om
public void processRequestInContextUnauthorizedGET() {
    Mockito.when(request.getMethod()).thenReturn("GET");
    Mockito.when(apiServer.verifyRequest(Mockito.anyMap(), Mockito.anyLong())).thenReturn(false);
    servlet.processRequestInContext(request, response);
    Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    Mockito.verify(apiServer, Mockito.never()).handleRequest(Mockito.anyMap(), Mockito.anyString(),
            Mockito.any(StringBuilder.class));
}

From source file:org.bjason.oauth2.TokenResource.java

private Response buildInvalidClientSecretResponse() throws OAuthSystemException {
    OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_UNAUTHORIZED)
            .setError(OAuthError.TokenResponse.UNAUTHORIZED_CLIENT)
            .setErrorDescription(INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
    return Response.status(response.getResponseStatus()).entity(response.getBody()).build();
}

From source file:com.github.mfpdev.sample.googleOTP.GoogleOTPResource.java

@GET
@OAuthSecurity(enabled = false)/*from  ww w  . ja v a  2  s.  c  om*/
@Path("/qrCode/{appId}/{appVersion}")
@ApiOperation(value = "Get the Google Authenticator QR Code URL", notes = "Redirect to the QR code URL, if exist in the user registration.  The QR code should be scanned by the Google Authenticator App", httpMethod = "GET", response = String.class)

@ApiResponses(value = { @ApiResponse(code = 302, message = "Redirect to the QR code URL"),
        @ApiResponse(code = 404, message = "QR code not found"),
        @ApiResponse(code = 401, message = "Unauthorized user") })

public void qrCode(
        @ApiParam(value = "App bundleId or package name", required = true) @PathParam("appId") String appId,
        @ApiParam(value = "App version", required = true) @PathParam("appVersion") String appVersion)
        throws Exception {

    //Get the username and password from the the authorization header
    Map<String, Object> usernamePassword = getEncodedUsernamePassword();

    //If username & password not sent or invalid, return a basic challenge to the client
    if (usernamePassword == null || !securityContext.validateCredentials(USER_LOGIN_SECURITY_CHECK_NAME,
            usernamePassword, request)) {
        response.addHeader("WWW-Authenticate", "Basic realm=\"Please provide your credentials\"");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    }

    // Get the username after passing the basic authentication
    String user = (String) usernamePassword.get(UserLoginSecurityCheck.USER_KEY);

    // Build search criteria to locate the relevant client data by application, version and user
    ClientSearchCriteria criteria = new ClientSearchCriteria().byUser(USER_LOGIN_SECURITY_CHECK_NAME, user)
            .byApplication(appId, appVersion);

    List<ClientData> dataList = securityContext.findClientRegistrationData(criteria);
    GoogleOTPState googleOTPState = null;

    // Get the most recent generated GoogleOTPState object from registration service
    long lastActivityTime = -1;
    for (ClientData clientData : dataList) {
        GoogleOTPState currentGoogleOTPState = clientData.getProtectedAttributes().get(GOOGLE_OTP_STATE_KEY,
                GoogleOTPState.class);
        //Get the last generated key for that user and application
        if (currentGoogleOTPState.getTimeStamp() > lastActivityTime) {
            //Get the latest client in case user logged in to more then one device
            lastActivityTime = currentGoogleOTPState.getTimeStamp();
            googleOTPState = currentGoogleOTPState;
        }
    }

    if (googleOTPState != null) {
        //Redirect to the QR code URL
        throw new RedirectionException(HttpServletResponse.SC_FOUND, new URI(googleOTPState.getQrCodeURL()));
    } else {
        throw new NotFoundException(String.format("Cannot found QR code for user [%s]", user));
    }
}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/weather", produces = "application/json")
public GetWeather serviceWeather(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (!serviceUsers.checkUserOnline(user)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/weather");
        }//from  www . j  ava 2s  .c om

        return null;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("user get weather. Session id : " + httpSession.getId() + ". User : " + user
                + ". URL : /service/weather");
    }

    return serviceWeather.getWeather();
}