List of usage examples for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED
int SC_UNAUTHORIZED
To view the source code for javax.servlet.http HttpServletResponse SC_UNAUTHORIZED.
Click Source Link
From source file:airport.web.controller.ServicesController.java
@RequestMapping(value = "/service/statistics/private", produces = "application/json") public Statistics serviceStatisticsPrivate(HttpServletRequest request, HttpServletResponse response) { User user = new User(); HttpSession httpSession = request.getSession(); user.setId(httpSession.getId());// w w w .j a va2s.c o m 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/statistics/private"); } return null; } if (LOG.isInfoEnabled()) { LOG.info("user get private statistics. Session id : " + httpSession.getId() + ". User : " + user + ". URL : /service/statistics/private"); } return serviceStatistics.getStatisticsUser(user); }
From source file:net.java.jaspicoil.SimpleBasicServerAuthModule.java
private AuthStatus sendErrorAndAuthenticateRequest(HttpServletRequest request, HttpServletResponse response, String message) {/* w w w . ja v a 2 s . c om*/ response.setHeader(AUTHENTICATE_HEADER, createAuthenticateValue(getRealm(request))); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); LOG.fine(message); return AuthStatus.SEND_CONTINUE; }
From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java
@RequestMapping(method = RequestMethod.DELETE, value = "/itinerary/{itineraryId}") public @ResponseBody Boolean deleteItinerary(HttpServletResponse response, @PathVariable String itineraryId) throws Exception { try {/*from ww w. j a v a2 s.c o m*/ String userId = getUserId(); if (userId == null) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } Map<String, Object> pars = new TreeMap<String, Object>(); pars.put("clientId", itineraryId); ItineraryObject res = domainStorage.searchDomainObject(pars, ItineraryObject.class); if (res == null) { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return false; } if (!userId.equals(res.getUserId())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } domainStorage.deleteItinerary(itineraryId); SavedTrip st = new SavedTrip(new Date(), res, RequestMethod.DELETE.toString()); domainStorage.saveSavedTrips(st); return true; } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return false; }
From source file:net.centro.rtb.monitoringcenter.MonitoringCenterServlet.java
@Override protected void doGet(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { httpServletResponse.setHeader("Cache-Control", "must-revalidate,no-cache,no-store"); httpServletResponse.setHeader("Pragma", "no-cache"); httpServletResponse.setHeader("Expires", "Tue, 11 Oct 1977 12:34:56 GMT"); if (!checkAuthorization(httpServletRequest)) { httpServletResponse.setHeader("WWW-Authenticate", "Basic realm=\"Centro Monitoring Center\""); httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return;/*from w w w .j a va2 s . c o m*/ } final String path = httpServletRequest.getPathInfo(); if (path == null || path.equals("/")) { handlePathDescriptions(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_METRICS)) { handleMetrics(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_HEALTHCHECKS)) { handleHealthChecks(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_PING)) { handlePing(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_THREADDUMP)) { handleThreadDump(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_SYSTEM_INFO)) { handleSystemInfo(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_NODE_INFO)) { handleNodeInfo(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_SERVER_INFO)) { handleServerInfo(httpServletRequest, httpServletResponse); } else if (path.startsWith(PATH_APP_INFO)) { handleAppInfo(httpServletRequest, httpServletResponse); } else { httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND); } }
From source file:jp.mathes.databaseWiki.web.DbwServlet.java
private void handleHttp(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("UTF-8"); resp.setCharacterEncoding("UTF-8"); String user = null;//from w w w . j av a2 s. c o m String password = null; if (req.getHeader("Authorization") != null) { String[] split = req.getHeader("Authorization").split(" "); String userpw = ""; if (split.length > 1) { userpw = new String(Base64.decodeBase64(split[1])); } user = StringUtils.substringBefore(userpw, ":"); password = StringUtils.substringAfter(userpw, ":"); resp.setStatus(HttpServletResponse.SC_OK); resp.setContentType("application/xhtml+xml; charset=UTF-8"); try { this.handleAction(req, resp, user, password); } catch (InstantiationException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not instantiate database backend: " + e.getMessage()); } catch (IllegalAccessException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Illegal Access: " + e.getMessage()); } catch (ClassNotFoundException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Could not find database backend: " + e.getMessage()); } catch (TemplateException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Template error: " + e.getMessage()); } catch (BackendException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Database error: " + e.getMessage()); } catch (PluginException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Rendering error: " + e.getMessage()); } } else { resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED); resp.setHeader("WWW-Authenticate", "Basic realm=\"databaseWiki\""); } }
From source file:edu.stanford.epad.epadws.security.EPADSessionOperations.java
public static EPADSessionResponse authenticateUser(HttpServletRequest httpRequest) { String username = extractUserNameFromAuthorizationHeader(httpRequest); String password = extractPasswordFromAuthorizationHeader(httpRequest); if (username == null || username.length() == 0) { username = httpRequest.getParameter("username"); password = httpRequest.getParameter("password"); }//from w w w .java 2 s .c om EPADSession session = null; try { if (username != null && password == null && httpRequest.getParameter("adminuser") != null) { session = EPADSessionOperations.createProxySession(username, httpRequest.getParameter("adminuser"), httpRequest.getParameter("adminpassword")); } else if (username == null && httpRequest.getAuthType().equals("WebAuth") && httpRequest.getRemoteUser() != null) { if (password != null && password.equals(EPADConfig.webAuthPassword)) session = EPADSessionOperations.createPreAuthenticatedSession(httpRequest.getRemoteUser()); } else { session = EPADSessionOperations.createNewEPADSession(username, password); } EPADSessionResponse response = new EPADSessionResponse(HttpServletResponse.SC_OK, session.getSessionId(), ""); log.info("Session ID " + response.response + " generated for user " + username); return response; } catch (Exception x) { EPADSessionResponse response = new EPADSessionResponse(HttpServletResponse.SC_UNAUTHORIZED, null, x.getMessage()); return response; } }
From source file:org.openrepose.common.auth.openstack.AuthenticationServiceClient.java
@Override public String getBase64EndpointsStringForHeaders(String userToken, String format, String tracingHeader) throws AuthServiceException { final Map<String, String> headers = new HashMap<>(); //defaulting to json format if ("xml".equalsIgnoreCase(format)) { format = MediaType.APPLICATION_XML; } else {// w w w . ja v a 2 s .c o m format = MediaType.APPLICATION_JSON; } String rawEndpointsData; try { //telling the service what format to send the endpoints to us in headers.put(ACCEPT_HEADER, format); headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, false)); if (tracingHeader != null) { headers.put(CommonHttpHeader.TRACE_GUID.toString(), tracingHeader); } ServiceClientResponse serviceClientResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken, targetHostUri + TOKENS + userToken + ENDPOINTS, headers); switch (serviceClientResponse.getStatus()) { case HttpServletResponse.SC_OK: rawEndpointsData = convertStreamToBase64String(serviceClientResponse.getData()); break; case HttpServletResponse.SC_UNAUTHORIZED: LOG.error("Unable to get endpoints for user: " + serviceClientResponse.getStatus() + " :admin token expired. Retrieving new admin token and retrying endpoints retrieval..."); headers.put(AUTH_TOKEN_HEADER, getAdminToken(tracingHeader, true)); serviceClientResponse = akkaServiceClient.get(ENDPOINTS_PREFIX + userToken, targetHostUri + TOKENS + userToken + ENDPOINTS, headers); if (serviceClientResponse.getStatus() == HttpServletResponse.SC_ACCEPTED) { rawEndpointsData = convertStreamToBase64String(serviceClientResponse.getData()); } else { delegationMessage.set("Unable to get endpoints for user: " + userToken + " with configured admin credentials"); LOG.error("Still unable to get endpoints: " + serviceClientResponse.getStatus()); throw new AuthServiceException( "Unable to retrieve service catalog for user with configured Admin credentials"); } break; case HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE: case FilterDirector.SC_TOO_MANY_REQUESTS: // (413 | 429) delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: " + serviceClientResponse.getStatus()); throw buildAuthServiceOverLimitException(serviceClientResponse); default: delegationMessage.set("Unable to get endpoints for token: " + userToken + ". Status code: " + serviceClientResponse.getStatus()); LOG.error("Unable to get endpoints for token. Status code: " + serviceClientResponse.getStatus()); throw new AuthServiceException("Unable to retrieve service catalog for user. Response from " + targetHostUri + ": " + serviceClientResponse.getStatus()); } } catch (AkkaServiceClientException e) { throw new AuthServiceException("Unable to get endpoints.", e); } return rawEndpointsData; }
From source file:contestWebsite.MainPage.java
@Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { VelocityEngine ve = new VelocityEngine(); ve.setProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH, "html/pages, html/snippets, html/templates"); ve.init();//from w ww .j a va 2 s. c om VelocityContext context = new VelocityContext(); Pair<Entity, UserCookie> infoAndCookie = init(context, req); UserCookie userCookie = infoAndCookie.y; Entity user = userCookie != null ? userCookie.authenticateUser() : null; boolean loggedIn = (boolean) context.get("loggedIn"); DatastoreService datastore = DatastoreServiceFactory.getDatastoreService(); if (loggedIn && !userCookie.isAdmin()) { Entity contestInfo = infoAndCookie.x; String endDateStr = (String) contestInfo.getProperty("editEndDate"); String startDateStr = (String) contestInfo.getProperty("editStartDate"); Date endDate = new Date(); Date startDate = new Date(); try { endDate = new SimpleDateFormat("MM/dd/yyyy").parse(endDateStr); startDate = new SimpleDateFormat("MM/dd/yyyy").parse(startDateStr); } catch (ParseException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Incorrect date format"); } if (new Date().after(endDate) || new Date().before(startDate)) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Registration editing deadline passed."); } else { Query query = new Query("registration") .setFilter(new FilterPredicate("email", FilterOperator.EQUAL, user.getProperty("user-id"))); Entity registration = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)).get(0); String studentData = req.getParameter("studentData"); JSONArray regData = null; try { regData = new JSONArray(studentData); } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } long price = (Long) infoAndCookie.x.getProperty("price"); int cost = (int) (0 * price); for (int i = 0; i < regData.length(); i++) { try { JSONObject studentRegData = regData.getJSONObject(i); for (Subject subject : Subject.values()) { cost += price * (studentRegData.getBoolean(subject.toString()) ? 1 : 0); } } catch (JSONException e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); return; } } registration.setProperty("cost", cost); registration.setProperty("studentData", new Text(studentData)); Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { datastore.put(registration); txn.commit(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } resp.sendRedirect("/?updated=1"); } } else if (loggedIn && userCookie.isAdmin()) { String username = req.getParameter("email").toLowerCase(); Query query = new Query("user") .setFilter(new FilterPredicate("user-id", FilterOperator.EQUAL, username)); List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1)); if (users.size() >= 1) { Transaction txn = datastore.beginTransaction(TransactionOptions.Builder.withXG(true)); try { query = new Query("authToken").setKeysOnly(); Filter tokenFilter = new FilterPredicate("token", FilterOperator.EQUAL, URLDecoder.decode(userCookie.getValue(), "UTF-8")); Filter expiredFilter = new FilterPredicate("expires", FilterOperator.LESS_THAN, new Date()); query.setFilter(CompositeFilterOperator.or(tokenFilter, expiredFilter)); datastore.delete( datastore.prepare(query).asList(FetchOptions.Builder.withDefaults()).get(0).getKey()); userCookie.setMaxAge(0); userCookie.setValue(""); resp.addCookie(userCookie); SecureRandom random = new SecureRandom(); String authToken = new BigInteger(130, random).toString(32); Entity token = new Entity("authToken"); token.setProperty("user-id", username); token.setProperty("token", authToken); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.MINUTE, 60); token.setProperty("expires", new Date(calendar.getTimeInMillis())); Cookie cookie = new Cookie("authToken", authToken); cookie.setValue(authToken); resp.addCookie(cookie); datastore.put(token); datastore.put(user); resp.sendRedirect("/"); txn.commit(); } catch (Exception e) { e.printStackTrace(); resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString()); } finally { if (txn.isActive()) { txn.rollback(); } } } else { resp.sendRedirect("/?error=1"); } } else { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "User account required for that operation"); } }
From source file:com.adito.core.actions.AuthenticatedAction.java
void sendAuthorizationError(HttpServletResponse response) throws IOException { response.setHeader("WWW-Authenticate", "Basic realm=\"" + Branding.PRODUCT_NAME + "\""); response.sendError(HttpServletResponse.SC_UNAUTHORIZED); }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private Account authenticate(HttpServletRequest req, HttpServletResponse resp, String responseSchema) throws ServletException, IOException { //The basic auth header looks like this: //Authorization: Basic emltYnJhXFx1c2VyMTp0ZXN0MTIz //The base64 encoded credentials can be either <domain>\<user>:<pass> or just <user>:<pass> String auth = req.getHeader(BASIC_AUTH_HEADER); log.debug("auth header: %s", auth); if (auth == null || !auth.toLowerCase().startsWith("basic ")) { log.warn("No basic auth header in the request"); resp.addHeader(WWW_AUTHENTICATE_HEADER, WWW_AUTHENTICATE_VALUE); // resp.addHeader(WWW_AUTHENTICATE_HEADER, NTLM); // resp.addHeader(WWW_AUTHENTICATE_HEADER, NEGOTIATE); sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); return null; }/* ww w. j a v a 2 s .c o m*/ // 6 comes from "Basic ".length(); String cred = new String(Base64.decodeBase64(auth.substring(6).getBytes())); int bslash = cred.indexOf('\\'); int colon = cred.indexOf(':'); if (colon == -1 || colon <= bslash + 1) { log.warn("Invalid basic auth credentials"); sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Invalid basic auth credentials"); return null; } String domain = bslash > 0 ? cred.substring(0, bslash) : ""; String userPassedIn = cred.substring(bslash + 1, colon); String user = cred.substring(bslash + 1, colon); String pass = cred.substring(colon + 1); log.debug("user=%s, domain=%s", user, domain); if (pass.length() == 0) { log.warn("Empty password"); sendError(resp, HttpServletResponse.SC_BAD_REQUEST, "Empty password"); return null; } if (domain.length() > 0 && user.indexOf('@') == -1) { if (domain.charAt(0) != '@') { user += '@'; } user += domain; } try { Provisioning prov = Provisioning.getInstance(); if (user.indexOf('@') == -1) { String defaultDomain = prov.getConfig().getAttr(Provisioning.A_zimbraDefaultDomainName, null); if (defaultDomain == null) { log.warn("Ldap access error; user=" + user); sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "ldap access error"); return null; } user = user + "@" + defaultDomain; } Account account = prov.get(AccountBy.name, user); if (account == null) { log.warn("User not found; user=" + user); resp.addHeader(WWW_AUTHENTICATE_HEADER, WWW_AUTHENTICATE_VALUE); sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or password"); return null; } try { Map<String, Object> authCtxt = new HashMap<String, Object>(); authCtxt.put(AuthContext.AC_ORIGINATING_CLIENT_IP, ZimbraServlet.getOrigIp(req)); authCtxt.put(AuthContext.AC_REMOTE_IP, ZimbraServlet.getClientIp(req)); authCtxt.put(AuthContext.AC_ACCOUNT_NAME_PASSEDIN, userPassedIn); authCtxt.put(AuthContext.AC_USER_AGENT, req.getHeader("User-Agent")); prov.authAccount(account, pass, AuthContext.Protocol.zsync, authCtxt); } catch (ServiceException x) { log.warn("User password mismatch; user=" + user); resp.addHeader(WWW_AUTHENTICATE_HEADER, WWW_AUTHENTICATE_VALUE); sendError(resp, HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or password"); return null; } if (isEwsClient(responseSchema) && !account.getBooleanAttr(Provisioning.A_zimbraFeatureEwsEnabled, false)) { log.info("User account not enabled for ZimbraEWS; user=" + user); sendError(resp, HttpServletResponse.SC_FORBIDDEN, "Account not enabled for ZimbraEWS"); return null; } if (!isEwsClient(responseSchema) && !account.getBooleanAttr(Provisioning.A_zimbraFeatureMobileSyncEnabled, false)) { log.info("User account not enabled for ZimbraSync; user=" + user); sendError(resp, HttpServletResponse.SC_FORBIDDEN, "Account not enabled for ZimbraSync"); return null; } return account; } catch (ServiceException x) { log.warn("Account access error; user=" + user, x); sendError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Account access error; user=" + user); return null; } }