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:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java
@RequestMapping(method = RequestMethod.GET, value = "/itinerary/{itineraryId}") public @ResponseBody BasicItinerary getItinerary(HttpServletResponse response, @PathVariable String itineraryId) throws Exception { try {/*from ww w. j a va2 s . c om*/ 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.searchDomainObjectFixForSpring(pars, // ItineraryObject.class); ItineraryObject res = domainStorage.searchDomainObject(pars, ItineraryObject.class); if (res != null && !userId.equals(res.getUserId())) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return null; } return res; // BasicItinerary itinerary = mapper.convertValue(res, // BasicItinerary.class); // return itinerary; } catch (Exception e) { e.printStackTrace(); response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } return null; }
From source file:dk.dma.msinm.user.security.SecurityServletFilter.java
/** * Checks if the request is an attempt to perform user-password or Auth token authentication. * <p></p>/*from w ww. j a va 2 s .c o m*/ * For user-password login attempts, the request payload will be a JSON credential object. * <p></p> * For auth token login attempts, the request payload will be the token itself. The token * must have an "auth_" prefix, and the associated JWT token must be found in the AuthCache. * * @param request the servlet request * @param response the servlet response * @return the request */ public HttpServletRequest handleJwtUserCredentialsOrAuthTokenLogin(HttpServletRequest request, HttpServletResponse response) throws IOException { String requestBody = WebUtils.readRequestBody(request); // Check if this is a user credential login attempt Credentials credentials = Credentials.fromRequest(requestBody); if (credentials != null) { log.info("Logging in with email " + credentials.getEmail()); // Successful login - create a JWT token try { request = SecurityUtils.login(userService, request, credentials.getEmail(), credentials.getPassword()); JWTToken jwt = jwtService.createSignedJWT(getJwtIssuer(request), (User) request.getUserPrincipal()); WebUtils.nocache(response).setContentType("application/json"); response.getWriter().write(jwt.toJson()); auditor.info("User %s logged in. Issued token %s", credentials.getEmail(), jwt.getToken()); return request; } catch (Exception ex) { } } else { // Check if this is an auth token login attempt try { String token = requestBody.trim(); if (token.startsWith(AuthCache.AUTH_TOKEN_PREFIX) && authCache.getCache().containsKey(token)) { // The tokens are one-off. Remove it as we read it JWTToken jwt = authCache.getCache().remove(token); WebUtils.nocache(response).setContentType("application/json"); response.getWriter().write(jwt.toJson()); auditor.info("User %s logged in via auth token. Issued token %s", jwt.getEmail(), jwt.getToken()); return request; } } catch (Exception ex) { } } response.sendError(HttpServletResponse.SC_UNAUTHORIZED); log.warn("Failed logging in using email and password"); return request; }
From source file:de.innovationgate.wgpublisher.WGPRequestPath.java
protected WGPRequestPath(HttpServletRequest request, HttpServletResponse response, WGPDispatcher dispatcher) throws HttpErrorException, WGException, IOException, URIException { this.core = dispatcher.getCore(); this.queryString = request.getQueryString(); this.completeURL = buildCompleteURL(request); this.publisherURL = WGPDispatcher.getPublisherURL(request); // Extract the base part of the path - Redirect to start.jsp if no path information given this.basePath = this.getBasePath(request, dispatcher); if (this.basePath.equals("") || this.basePath.equals("/")) { if (core.getWgaConfiguration().getDefaultDatabase() == null) { this.pathType = TYPE_REDIRECT; this.resourcePath = this.publisherURL + this.core.getStartPageURL(); return; } else {//from www . j a v a2s.co m this.basePath = "/" + core.getWgaConfiguration().getDefaultDatabase(); } } // Tokenize Path int tildeTokenPos = -1; java.util.StringTokenizer pathTokens = new StringTokenizer(this.basePath, "/"); String token; while (pathTokens.hasMoreTokens()) { token = pathTokens.nextToken(); this.pathElements.add(token); if (token.charAt(0) == '~') { tildeTokenPos = this.pathElements.size() - 1; } } if (this.pathElements.size() < 1) { this.pathType = TYPE_INVALID; return; } // Resolve database this.databaseKey = ((String) this.pathElements.get(0)).toLowerCase(); ; this.database = (WGDatabase) core.getContentdbs().get(this.databaseKey); // if no database under this key, try to recognize a special path command if (this.database == null) { determineSpecialPathCommand(); if (this.database == null) { return; } } // Check if we need to enforce secure app mode URL secureURL = enforceSecureAppMode(database, request); if (secureURL != null) { pathType = TYPE_REDIRECT; resourcePath = secureURL.toString(); return; } // check if db is accessed via right protocol, host and port - Must be before login so it may get redirected to some certauth port URL currentURL = new URL(request.getRequestURL().toString()); URL redirectURL = enforceRedirectionRules(database, currentURL); // currentURL differs from redirectURL - redirect necessary if (redirectURL != null && !dispatcher.isBrowserInterface(request.getSession())) { pathType = TYPE_REDIRECT; resourcePath = redirectURL.toString(); return; } // Handle special db commands "login" and "logout". The only one not requiring to login to the database if (this.pathElements.size() == 2) { if ("login".equals(this.pathElements.get(1))) { this.pathType = TYPE_REDIRECT; String sourceURL = (request.getParameter("redirect") != null ? dispatcher.getCore().getURLEncoder().decode(request.getParameter("redirect")) : WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey); this.resourcePath = dispatcher.getLoginURL(request, database, sourceURL); this.appendQueryString = false; return; } else if ("logout".equals(this.pathElements.get(1))) { this.pathType = TYPE_LOGOUT; if (request.getParameter("redirect") != null) { this.resourcePath = request.getParameter("redirect"); this.appendQueryString = false; } else { this.resourcePath = WGPDispatcher.getPublisherURL(request) + "/" + this.databaseKey; } return; } } // Open the database try { if (pathType == TYPE_STATICTML && "admintml".equals(getPathCommand()) && dispatcher.isAdminLoggedIn(request)) { this.masterLogin = true; } // Prepare HTTP credentials if available String credentials = request.getHeader("Authorization"); if (credentials != null && credentials.trim().toLowerCase().startsWith("basic")) { DBLoginInfo loginInfo = DBLoginInfo.createFromHttpCredentials(credentials); if (loginInfo != null) { // Look if ANY media key uses HTTP login. Only if so we accept this login if (isHttpLoginUsed(database)) { request.setAttribute(REQATTRIB_HTTPLOGIN, loginInfo); } } } this.database = core.openContentDB(database, request, this.masterLogin); } catch (WGUnavailableException e) { throw new HttpErrorException(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "The website is currently unavailable: " + e.getMessage(), getDatabaseKey()); } catch (de.innovationgate.wgpublisher.AuthenticationException e) { throw new HttpErrorException(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage(), null); } catch (AccessException e) { throw new HttpErrorException(HttpServletResponse.SC_FORBIDDEN, e.getMessage(), null); } if (!database.isSessionOpen()) { handleLoginFailure(request, response, dispatcher); this.proceedRequest = false; return; } // If request is static/admin tml we are done here if (pathType == TYPE_STATICTML) { return; } // If only database given, go to home page if (this.pathElements.size() == 1) { this.pathType = TYPE_GOTO_HOMEPAGE; setPermanentRedirect(core.getWgaConfiguration().isUsePermanentRedirect()); return; } // Process tilde tokens if (tildeTokenPos != -1) { String tildeToken = (String) this.pathElements.get(tildeTokenPos); // Url to file attachment via ~file-Syntax if (tildeToken.equalsIgnoreCase("~file")) { this.pathType = TYPE_FILE; List<String> preTildeTokenElems = this.pathElements.subList(1, tildeTokenPos); this.containerKey = (String) preTildeTokenElems.get(preTildeTokenElems.size() - 1); this.fileName = WGUtils.serializeCollection( this.pathElements.subList(tildeTokenPos + 1, this.pathElements.size()), "/"); return; } } // Catch special db-related urls String elem1 = ((String) this.pathElements.get(1)).toLowerCase(); int elementsSize = this.pathElements.size(); if (elementsSize >= 3 && (elem1.equals("css"))) { this.pathType = TYPE_CSS; this.cssjsKey = this.database.toLowerCaseMeta( WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/")); return; } else if (elementsSize >= 3 && (elem1.equals("js"))) { this.pathType = TYPE_JS; this.cssjsKey = this.database.toLowerCaseMeta( WGUtils.serializeCollection(this.pathElements.subList(2, this.pathElements.size()), "/")); return; } else if (elementsSize >= 3 && elem1.equals("file")) { this.pathType = TYPE_FILE; int fileNameIndex = determineFileNameIndex(this.pathElements, 2); this.containerKey = this.database .toLowerCaseMeta(WGUtils.serializeCollection(this.pathElements.subList(2, fileNameIndex), ":")); this.fileName = WGUtils.serializeCollection(this.pathElements.subList(fileNameIndex, elementsSize), "/"); return; } // Find out if we have a title path URL TitlePathManager tpm = (TitlePathManager) database.getAttribute(WGACore.DBATTRIB_TITLEPATHMANAGER); if (tpm != null && tpm.isGenerateTitlePathURLs()) { TitlePathManager.TitlePath url = tpm.parseTitlePathURL(pathElements.subList(1, pathElements.size())); if (url != null) { this.pathType = TYPE_TITLE_PATH; this.titlePathURL = url; this.mediaKey = core.getMediaKey(url.getMediaKey()); if (url.getLanguage() == null) { completePath = false; } } } // Path identified as normal TML request, read media and layout key if (pathType == TYPE_UNKNOWN) { pathType = TYPE_TML; int elementIdx = this.readMediaKey(core, this.pathElements, 1); elementIdx = this.readLayoutKey(core, this.pathElements, elementIdx); if (elementIdx < this.pathElements.size()) { this.contentKey = this.database.toLowerCaseMeta((String) this.pathElements.get(elementIdx)); } if (this.layoutKey == null && this.contentKey == null) { this.pathType = TYPE_INVALID; } } // Retrieve the content if (getPathType() == WGPRequestPath.TYPE_TITLE_PATH) { this.content = getContentByTitlePath(request); if (this.content == null) { pathType = TYPE_UNKNOWN_CONTENT; } // If content was retrieved with struct key we check if the title path is correct. If not we force redirection to the correct version (#00003145) else if (getTitlePathURL().getStructKey() != null) { List<String> correctTitlePath = tpm.buildTitlePath(this.content, mediaKey.getKey(), new RequestLanguageChooser(this.database, request)); if (correctTitlePath == null || !correctTitlePath.equals(getTitlePathURL().getEncodedTitles())) { completePath = false; } } // If title path is configured to include keys but the current tp has no key we force redirection to the version including a key (#00003304). else if (tpm.isIncludeKeys()) { completePath = false; } } else if (getPathType() == TYPE_TML) { if (this.contentKey != null) { URLID contentid = new URLID(this.contentKey, this.database); boolean isBI = WGPDispatcher.isBrowserInterface(request.getSession()) || WGPDispatcher.isAuthoringMode(database.getDbReference(), request.getSession()); this.content = WGPDispatcher.getContentByAnyKey(contentid, database, new RequestLanguageChooser(database, request), isBI); if (this.content != null) { // Look if we really used the parsed content URLID information. if (!contentid.isCompleteFormat()) { completePath = false; } this.requestLanguage = content.getLanguage().getName(); } else { pathType = TYPE_UNKNOWN_CONTENT; } } // Contextless request. If we have no request language we have no complete path and we must determine a language else { if (requestLanguage == null) { completePath = false; LanguageBehaviour langBehaviour = LanguageBehaviourTools.retrieve(database); WGLanguage lang = langBehaviour.requestSelectDatabaseLanguage(database, request); if (lang != null) { this.requestLanguage = lang.getName(); } // Fallback to the database default language else { this.requestLanguage = database.getDefaultLanguage(); } } } } }
From source file:org.apache.axis2.transport.http.server.AxisHttpService.java
protected void doService(final AxisHttpRequest request, final AxisHttpResponse response, final HttpContext context, final MessageContext msgContext) throws HttpException, IOException { if (LOG.isDebugEnabled()) { LOG.debug("Request method: " + request.getMethod()); LOG.debug("Target URI: " + request.getRequestURI()); }/* w w w.j av a 2 s . c o m*/ try { TransportOutDescription transportOut = this.configurationContext.getAxisConfiguration() .getTransportOut(Constants.TRANSPORT_HTTP); TransportInDescription transportIn = this.configurationContext.getAxisConfiguration() .getTransportIn(Constants.TRANSPORT_HTTP); String sessionKey = (String) context.getAttribute(HTTPConstants.COOKIE_STRING); msgContext.setTransportIn(transportIn); msgContext.setTransportOut(transportOut); msgContext.setServerSide(true); msgContext.setProperty(HTTPConstants.COOKIE_STRING, sessionKey); msgContext.setProperty(Constants.Configuration.TRANSPORT_IN_URL, request.getRequestURI()); // set the transport Headers HashMap headerMap = new HashMap(); for (Iterator it = request.headerIterator(); it.hasNext();) { Header header = (Header) it.next(); headerMap.put(header.getName(), header.getValue()); } msgContext.setProperty(MessageContext.TRANSPORT_HEADERS, headerMap); msgContext.setProperty(Constants.Configuration.CONTENT_TYPE, request.getContentType()); msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, response); msgContext.setTo(new EndpointReference(request.getRequestURI())); msgContext.setProperty(RequestResponseTransport.TRANSPORT_CONTROL, new SimpleHTTPRequestResponseTransport()); this.worker.service(request, response, msgContext); } catch (SocketException ex) { // Socket is unreliable. throw ex; } catch (HttpException ex) { // HTTP protocol violation. Transport is unreliable throw ex; } catch (Throwable e) { msgContext.setProperty(MessageContext.TRANSPORT_OUT, response.getOutputStream()); msgContext.setProperty(Constants.OUT_TRANSPORT_INFO, response); MessageContext faultContext = MessageContextBuilder.createFaultMessageContext(msgContext, e); // If the fault is not going along the back channel we should be 202ing if (AddressingHelper.isFaultRedirected(msgContext)) { response.setStatus(HttpStatus.SC_ACCEPTED); } else { String state = (String) msgContext.getProperty(Constants.HTTP_RESPONSE_STATE); if (state != null) { int stateInt = Integer.parseInt(state); response.setStatus(stateInt); if (stateInt == HttpServletResponse.SC_UNAUTHORIZED) { // Unauthorized String realm = (String) msgContext.getProperty(Constants.HTTP_BASIC_AUTH_REALM); response.addHeader("WWW-Authenticate", "basic realm=\"" + realm + "\""); } } else { if (e instanceof AxisFault) { response.sendError(getStatusFromAxisFault((AxisFault) e), e.getMessage()); } else { response.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal server error"); } } } AxisEngine.sendFault(faultContext); } }
From source file:com.janrain.backplane2.server.Backplane2ControllerTest.java
@Test public void testTokenEndPointAnonymousWithClientSecret() throws Exception { //satisfy 13.1.1 refreshRequestAndResponse();// w w w . ja v a 2s. c om request.setRequestURI("/v2/token"); // this could go to either the POST or GET enabled endpoint request.setMethod("POST"); //request.setParameter("grant_type", com.janrain.oauth2.OAuth2.OAUTH2_TOKEN_GRANT_TYPE_CLIENT_CREDENTIALS); //shouldn't contain the client_secret below setOAuthBasicAuthentication(request, "anonymous", "meh"); handlerAdapter.handle(request, response, controller); logger.info("testTokenEndPointAnonymousWithClientSecret() => " + response.getContentAsString()); assertTrue(response.getContentAsString().contains(ERR_RESPONSE)); assertTrue(HttpServletResponse.SC_UNAUTHORIZED == response.getStatus()); }
From source file:com.zimbra.cs.service.UserServlet.java
private void sendError(UserServletContext ctxt, HttpServletRequest req, HttpServletResponse resp, String message) throws IOException { if (resp.isCommitted()) { log.info("Response already committed. Skipping sending error code for response"); return;/*from w ww . j av a2 s . com*/ } if (ctxt != null && !ctxt.cookieAuthHappened && ctxt.basicAuthAllowed() && !ctxt.basicAuthHappened) { resp.addHeader(AuthUtil.WWW_AUTHENTICATE_HEADER, getRealmHeader(req, null)); resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate, req)); } else if (ctxt != null && ctxt.cookieAuthHappened && !ctxt.isCsrfAuthSucceeded() && (req.getMethod().equalsIgnoreCase("POST") || req.getMethod().equalsIgnoreCase("PUT"))) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, L10nUtil.getMessage(MsgKey.errMustAuthenticate, req)); } else { resp.sendError(HttpServletResponse.SC_NOT_FOUND, message); } }
From source file:io.zipi.common.servlet.AuthenticationFilter.java
/** * Sends a response that tells the client that authentication is required. * @param response the response// w ww.java 2s.co m * @throws IOException when an error cannot be sent */ private void sendAuthResponse(HttpServletResponse response) throws IOException { response.setHeader("WWW-Authenticate", String.format("Basic realm=\"%1$s\"", realm)); //$NON-NLS-1$ //$NON-NLS-2$ response.sendError(HttpServletResponse.SC_UNAUTHORIZED); }
From source file:airport.web.controller.ServicesController.java
@RequestMapping(value = "/service/statistics/common", produces = "application/json") public Statistics serviceStatisticsCommon(HttpServletRequest request, HttpServletResponse response) { User user = new User(); HttpSession httpSession = request.getSession(); user.setId(httpSession.getId());/* w w w . ja v a2s .c om*/ 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/common"); } return null; } if (LOG.isInfoEnabled()) { LOG.info("user get common statistics. Session id : " + httpSession.getId() + ". User : " + user + ". URL : /service/statistics/common"); } return serviceStatistics.getStatisticsAll(); }
From source file:au.edu.anu.portal.portlets.tweetal.servlet.TweetalServlet.java
public void retweet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("application/json"); PrintWriter out = response.getWriter(); String userToken = request.getParameter("u"); String userSecret = request.getParameter("s"); long statusId = Long.parseLong(request.getParameter("d")); log.debug("statusId: " + statusId); Twitter twitter = twitterLogic.getTwitterAuthForUser(userToken, userSecret); if (twitter == null) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); return;// ww w. j av a 2s. c o m } try { Status status = null; // update user status status = twitter.retweetStatus(statusId); if (status == null) { log.error("Status is null."); // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } JSONObject json = new JSONObject(); JSONObject statusJSON = getStatusJSON(twitter, status); // return as an array even though only it contains only one element, // so we can reuse the same Trimpath template (Denny) JSONArray statusList = new JSONArray(); statusList.add(statusJSON); json.put("statusList", statusList); if (log.isDebugEnabled()) { log.debug(json.toString(2)); } out.print(json.toString()); } catch (TwitterException e) { log.error("GetTweets: " + e.getStatusCode() + ": " + e.getClass() + e.getMessage()); if (e.getStatusCode() == 401) { // invalid credentials response.sendError(HttpServletResponse.SC_UNAUTHORIZED); } else if (e.getStatusCode() == -1) { // no connection response.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE); } else { // general error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } }