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:com.google.gsa.Kerberos.java
/** * Servlet's doPost: processes a POST request. Controls the overall * kerberos silent authentication process. It supports both the Security * Framework's SAML and Forms Based interface. * <p>/* w w w . ja va2 s.c o m*/ * You can find more information on the Security Framework's Kerberos guide * about the scenarios implemented here * * @param request HTTP request * @param response HTTP response * * @throws ServletException * @throws IOException */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { logger.debug("Kerberos servlet"); if (gsaValveConfigPath == null) { if (request.getAttribute("gsaValveConfigPath") == null) { //Read parameter from config file: SAML gsaValveConfigPath = readValveConfigPath(); } else { gsaValveConfigPath = request.getAttribute("gsaValveConfigPath").toString(); } } logger.debug("Valve Config Path is: " + gsaValveConfigPath); // Initialize status code int statusCode = HttpServletResponse.SC_UNAUTHORIZED; //Authentication Processes AuthenticationProcessImpl authenticationProcessCls = null; KerberosAuthenticationProcess krbAuthN = new KerberosAuthenticationProcess(); //Initialize cookies vars Cookie gsaRefererCookie = null; Cookie gsaAuthCookie = null; //Session Cookie arrays Vector<Cookie> krbCookies = new Vector<Cookie>(); Vector<Cookie> nonKrbCookies = new Vector<Cookie>(); //user agent String userAgent = null; //user credentials Credentials creds = null; //User Session and Session ID vars definition UserSession userSession = null; String sessionID = null; String encodedSessionID = null; //Create the credentials store try { this.valveConf = ValveConfigurationInstance.getValveConfig(gsaValveConfigPath); } catch (ValveConfigurationException e) { logger.error("Valve Config instantiation error: " + e); } logger.debug("Creating the credentials store"); creds = new Credentials(); String username = null; //Setting Valve parameters logger.debug("Setting Valve params"); setValveParams(request); //Protection if ((!isKerberos) || (!isNegotiate)) { logger.error( "Configuration error: if you want to use Kerberos silent AuthN, isKerberos and isNegotiate config vars have to be set to true"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Configuration error - Kerberos is not set properly"); return; } Cookie cookies[] = null; // Retrieve cookies cookies = request.getCookies(); // Protection: look for auth and referer cookies if (cookies != null) { // Look for the referer cookie for (int i = 0; i < cookies.length; i++) { // Look for the referer cookie if ((cookies[i].getName()).equals(refererCookieName)) { // Cache cookie gsaRefererCookie = cookies[i]; logger.debug("Referer cookie already exists: " + gsaRefererCookie.getValue()); } else { // Look for the auth cookie if ((cookies[i].getName()).equals(authCookieName)) { // Cache cookie gsaAuthCookie = cookies[i]; logger.debug("Auth cookie already exists: " + gsaAuthCookie.getValue()); } } if ((gsaRefererCookie != null) && (gsaAuthCookie != null)) { // Exit break; } } } // Protection if (!isSAML) { if (gsaRefererCookie == null) { // Raise error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The GSA authentication servlet couldn't read the referer cookie"); // Log error logger.error( "The GSA authentication servlet couldn't read the referer cookie, pls. check the cookie domain value"); // Return return; } } else { //SAML //Get SAML Params relayState = request.getParameter("RelayState"); samlRequest = request.getParameter("SAMLRequest"); //String relayStateCookie = valveConf.getSAMLConfig().getRelayStateCookie(); boolean noParams = false; boolean cookieExist = true; //Protection if ((relayState == null) || (relayState.equals(""))) { noParams = true; } else { if ((samlRequest == null) || (samlRequest.equals(""))) { noParams = true; } } createRefererCookie(gsaRefererCookie); //if ((noParams)&&(!cookieExist)) { if (noParams) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request"); return; } } logger.debug("Let's validate if gsaAuthCookie is present"); if (gsaAuthCookie != null) { if (!isSAML) { //redirect String redirect = gsaRefererCookie.getValue(); logger.debug("redirect is " + redirect); //redirect only if the URL is different than the login one if (!redirect.equals(loginUrl)) { //user properly authenticated logger.debug("The user was properly authenticated. Lets redirect to..." + redirect); // Redirect response.sendRedirect(redirect); } else { logger.debug("It's the login URL. No redirect"); } } else { logger.debug("As this is SAML. Let's obviate the previous authentication cookie"); gsaAuthCookie = null; } } userSession = new UserSession(); Sessions sessions = Sessions.getInstance(); sessions.setMaxSessionAgeMinutes(maxSessionAge); sessions.setSessionTimeoutMinutes(sessionTimeout); if (gsaAuthCookie == null) { logger.debug("gsaAuthCookie does not exist"); isNegotiate = true; // Read User-Agent header userAgent = request.getHeader("User-Agent"); logger.debug("userAgent is... " + userAgent); //check if user is gsa-crawler if (userAgent.startsWith(GSA_CRAWLER_USER)) { logger.debug("User is " + GSA_CRAWLER_USER); //check if user is gsa-crawler and have to authenticate it thru a form if (KrbUsrPwdCrawler) { logger.debug("gsa-crawler has to access thru username and password"); //check if crawler already provided credentials if (request.getParameter("UserIDKrb") == null) { //the login page have to be filled in by the admin user before reaching here. Return error logger.error("The login page [" + KrbUsrPwdCrawlerUrl + "] has to be invoked and its credentials fields filled in before reaching here"); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "It means the GSA Valve Kerberos configuration is not done properly or you just forgot to fill in the Kerberos credentials in the login page"); return; } else { //user already submits credentials logger.debug("Crawler has already sent credentials"); //set isNegotiate equal false (it authenticates the user thru username and pwd credentials) isNegotiate = false; //set Crawler credentials setCrawlerCredentials(request, creds, KrbAdditionalAuthN); //authenticate user statusCode = krbAuthentication(request, response, krbAuthN, krbCookies, gsaRefererCookie.getValue(), creds, isNegotiate); // Protection: check status code if (statusCode != HttpServletResponse.SC_OK) { // Raise error response.sendError(statusCode, "Authentication process failed!"); // Debug if (logger.isDebugEnabled()) logger.debug("Krb Authentication process failed with code: " + statusCode); if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { logger.debug( "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process"); } // Return return; } //check if the additional authN method is available. If so, start authN with these creds as well //N: modification for always lanching the root authN process. Comment out the following line //if (KrbAdditionalAuthN) { statusCode = nonKrbAuthentication(request, response, authenticationProcessCls, nonKrbCookies, gsaRefererCookie.getValue(), creds); //check if the status code is indeterminate if (statusCode == -1) { //the process could not determinate the authorization //as there is no pattern that matches with any repository statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // Protection: check status code if (statusCode != HttpServletResponse.SC_OK) { // Raise error response.sendError(statusCode, "Authentication process failed!"); // Debug if (logger.isDebugEnabled()) logger.debug("Non Krb Authentication process failed with code: " + statusCode); // Return return; } //} } } else { // end KrbUsrPwdCrawler is set. //If KrbUsrPwdCrawler is not set to true, then do nothing (assume content is feeded) //just send back the error as a configuration one (we shouldn't configure Froms-based crawling) response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Configuration error. Review your configuration as you can not define this rule if it's not set properly (see doc on how to set it up using Kerberos config attributes)"); return; } } else { //User is not Crawler logger.debug("User is NOT crawler"); //check if we have double AuthN or not if (!KrbAdditionalAuthN) { logger.debug("Krb silent authN only"); //set isNegotiate equal true (it authenticates the user thru kerberos ticket) isNegotiate = true; String refererCookieValue = null; if (gsaRefererCookie != null) { refererCookieValue = new String(gsaRefererCookie.getValue()); } //authenticate user statusCode = krbAuthentication(request, response, krbAuthN, krbCookies, refererCookieValue, creds, isNegotiate); // Protection: check status code if (statusCode != HttpServletResponse.SC_OK) { // Raise error response.sendError(statusCode, "Authentication process failed!"); // Debug if (logger.isDebugEnabled()) logger.debug("Krb Authentication process failed with code: " + statusCode); if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { logger.debug( "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process"); } // Return return; } else { boolean doesKrbSubjectExist = lookForKrbCreds(creds); if (!doesKrbSubjectExist) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Credentials not valid. Try to close your browser and try it again"); // Log error logger.error("Kerberos Subject is not present when authenticating"); // Return return; } //N: call rootAuthN once we have the Kerberos creds //N: Begin update if (!KrbAdditionalAuthN) { statusCode = nonKrbAuthentication(request, response, authenticationProcessCls, nonKrbCookies, refererCookieValue, creds); //check if the status code is indeterminate if (statusCode == -1) { //the process could not determinate the authorization //as there is no pattern that matches with any repository statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // Protection: check status code if (statusCode != HttpServletResponse.SC_OK) { // Raise error response.sendError(statusCode, "Authentication process failed!"); // Debug if (logger.isDebugEnabled()) logger.debug("Non Krb Authentication process failed with code: " + statusCode); // Return return; } } //N:End update } } else { //Double AuthN required. So that apart from the Krb silent authN, we authN the user as well thru username and pwd logger.debug("Krb and Forms based AuthN mechanisms"); //check if Krb credentials are already set Cookie gsaKrbCookie = getCookie(request, KRB_COOKIE_NAME); //if (gsaKrbCookie != null) { //Kerberos cookie set if (!isKrbProcess(gsaKrbCookie)) { //Kerberos cookie set logger.debug("Krb cookie is set. Krb AuthN already in place"); Subject krbSubj = getKrbSubject(gsaKrbCookie.getValue()); //Protection if (krbSubj == null) { // couldn't localize the subject. response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Credentials not valid. Try to close your browser and try it again"); // Log error logger.error("Kerberos Subject is not present when authenticating"); // Return return; } else { logger.debug("The Krb subject exists. This is the Forms based AuthN part"); //check if parameters are present if (request.getParameter("UserIDKrb") == null) { logger.debug("Login page has not been already invoked"); String redirectUrl = contructKrbLoginURL(); logger.debug("Redirecting to...." + redirectUrl); //redirect to the login page response.sendRedirect(response.encodeRedirectURL(redirectUrl)); // Return return; } else { //user already submits credentials logger.debug("User has already sent credentials"); createCredsDoubleAuthN(request, creds, krbSubj); logger.debug("User Credentials created. Let's authenticate the user without Krb"); statusCode = nonKrbAuthentication(request, response, authenticationProcessCls, nonKrbCookies, gsaRefererCookie.getValue(), creds); //check if the status code is indeterminate if (statusCode == -1) { //the process could not determinate the authorization //as there is no pattern that matches with any repository statusCode = HttpServletResponse.SC_UNAUTHORIZED; } // Protection: check status code if (statusCode != HttpServletResponse.SC_OK) { // Raise error response.sendError(statusCode, "Authentication process failed!"); // Debug if (logger.isDebugEnabled()) logger.debug( "Non Krb Authentication process failed with code: " + statusCode); // Return return; } boolean resultDelete = deleteKrbSubject(gsaKrbCookie.getValue()); if (!resultDelete) { logger.error("Not KrbSubj found when deleting it"); } } } } else { //Krb cookie does not exist logger.debug( "Krb cookie does not exist. Let's silently authenticate the user thru Krb firstly"); logger.debug("Krb silent authN only"); //set isNegotiate equal true (it authenticates the user thru kerberos ticket) isNegotiate = true; //authenticate user statusCode = krbAuthentication(request, response, krbAuthN, krbCookies, gsaRefererCookie.getValue(), creds, isNegotiate); // Protection: check status code if (statusCode != HttpServletResponse.SC_OK) { // Raise error response.sendError(statusCode, "Authentication process failed!"); // Debug if (logger.isDebugEnabled()) logger.debug("Krb Authentication process failed with code: " + statusCode); if (statusCode == HttpServletResponse.SC_UNAUTHORIZED) { logger.debug( "Note: this 401 could not be an error as sending 401 could be part of the Negotiation process"); } // Return return; } else { Cookie krbCookie = krbCookies.elementAt(0); String krbAuthCookieValue = krbCookie.getValue(); logger.debug("Krb cookie value: " + krbAuthCookieValue); if (krbAuthCookieValue == null) { logger.error("Krb cookie not present"); // Raise error response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Kerberos cookie not present"); // Return return; } else { addKrbCookie(response, krbCookie); addKrbSubject(krbAuthCookieValue, krbAuthN.getUserSubject()); logger.debug( "The User Krb identity is already present. Let's authenticate the user thru username/password"); //redirect to Login page String redirectUrl = contructKrbLoginURL(); response.sendRedirect(response.encodeRedirectURL(redirectUrl)); logger.debug("Redirect to.... " + redirectUrl); return; } } } } } logger.debug("Krb and/or Forms based AuthN OK. Let's create the session"); //set username and cookies username = creds.getCredential(KRB5_ID).getUsername(); //creation time var long creationTime = System.currentTimeMillis(); //Setting session values sessionID = UserIDEncoder.getID(username, creationTime); encodedSessionID = URLEncoder.encode(sessionID, encoder); logger.debug("Krb Username is... " + username); // setSession boolean sessionOk = settingSession(userSession, gsaAuthCookie, creds, username, krbAuthN, creationTime, encodedSessionID, krbCookies, nonKrbCookies); logger.debug("Session is .... " + sessionOk); if (!sessionOk) { //SAML statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.setStatus(statusCode); // Log error logger.error("Kerberos Subject has not been created properly"); // Return return; } else { //Store Session in the Session Map sessions.addSession(sessionID, userSession); sessions.setMaxSessionAgeMinutes(maxSessionAge); if (isSessionEnabled) { sessions.setSessionTimeoutMinutes(sessionTimeout); } else { sessions.setSessionTimeoutMinutes(-1); } logger.debug("User Session created"); // Add internal authentication cookie response.addCookie(gsaAuthCookie); logger.debug("Auth cookie added"); // Debug if (logger.isDebugEnabled()) logger.debug("Authentication process successful"); if (!isSAML) { // Debug if (logger.isDebugEnabled()) logger.debug("Redirecting user to: " + gsaRefererCookie.getValue()); // Redirect response.sendRedirect(gsaRefererCookie.getValue()); } else { try { redirectingSAML(response, cookies, sessionID); } catch (ValveConfigurationException e) { logger.error("Configuration error: " + e.getMessage(), e); response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } } } } //end of AuthN cases }
From source file:eu.trentorise.smartcampus.communicatorservice.controller.NotificationController.java
@RequestMapping(method = RequestMethod.GET, value = "/user/notification/{id}") public @ResponseBody Notification getNotificationByUser(HttpServletRequest request, HttpServletResponse response, HttpSession session, @PathVariable("id") String id) throws DataException, IOException, NotFoundException, SmartCampusException { String userId = getUserId();/*from w ww.jav a 2 s . c om*/ if (userId == null) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED); return null; } return notificationManager.getByIdAndUser(id, userId); }
From source file:com.github.thorqin.webapi.oauth2.OAuthServer.java
public static void responseGetResourceFailed(HttpServletResponse response, OAuthError error, String errorDescription, String errorUri) { String headContent = "Bearer "; headContent += "error=\"" + error.toString().toLowerCase() + "\""; if (errorDescription != null) headContent += "error_description=\"" + errorDescription + "\""; if (errorUri != null) headContent += "error_uri=\"" + errorUri + "\""; response.setHeader("WWW-Authenticate", headContent); switch (error) { case INVALID_REQUEST: response.setStatus(HttpServletResponse.SC_BAD_REQUEST); break;/* www. ja v a2 s.c om*/ case UNAUTHORIZED_CLIENT: response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); break; case ACCESS_DENIED: case UNSUPPORTED_RESPONSE_TYPE: case INVALID_SCOPE: response.setStatus(HttpServletResponse.SC_FORBIDDEN); break; case SERVER_ERROR: response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); break; case TEMPORARILY_UNAVAILABLE: response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE); break; } }
From source file:com.formtek.dashlets.sitetaskmgr.SiteTaskInstancesGet.java
@Override protected Map<String, Object> buildModel(WorkflowModelBuilder modelBuilder, WebScriptRequest req, Status status, Cache cache) {/*from w w w .j a v a 2 s.c o m*/ Map<String, String> params = req.getServiceMatch().getTemplateVars(); Map<String, Object> filters = new HashMap<String, Object>(4); // site is in filters, but we also need to check appropriate privileges to run // members of the site are given access String site = getSite(req); logger.debug("Finding tasks for site: " + site); // authority is not included into filters list as it will be taken into account before filtering String authority = getAuthority(req); // state is also not included into filters list, for the same reason WorkflowTaskState state = getState(req); // look for a workflow instance id String workflowInstanceId = params.get(VAR_WORKFLOW_INSTANCE_ID); // get list of properties to include in the response List<String> properties = getProperties(req); // Get sort parameters, if defined String sortColumn = getSort(req); String sortDirection = getDir(req); int sortStart = getStartIndex(req); int sortCount = getResultCount(req); logger.debug("Sort column and direction: " + sortColumn + " : " + sortDirection); logger.debug("Sort start and count: " + sortStart + " : " + sortCount); // If User is not authorized to view this workflow, exit if (!SiteWFUtil.canUserViewWorkflow(site, workflowService, nodeService, authenticationService, authorityService)) { throw new WebScriptException(HttpServletResponse.SC_UNAUTHORIZED, "User is not authorized to view workflows for this site: " + site); } // get filter param values filters.put(PARAM_PRIORITY, req.getParameter(PARAM_PRIORITY)); filters.put(PARAM_SITE, req.getParameter(PARAM_SITE)); filters.put(PARAM_TASKTYPE, req.getParameter(PARAM_TASKTYPE)); processDateFilter(req, PARAM_DUE_BEFORE, filters); processDateFilter(req, PARAM_DUE_AFTER, filters); String excludeParam = req.getParameter(PARAM_EXCLUDE); if (excludeParam != null && excludeParam.length() > 0) { filters.put(PARAM_EXCLUDE, new ExcludeFilter(excludeParam)); } List<WorkflowTask> allTasks; if (workflowInstanceId != null) { // a workflow instance id was provided so query for tasks WorkflowTaskQuery taskQuery = new WorkflowTaskQuery(); taskQuery.setActive(null); taskQuery.setProcessId(workflowInstanceId); taskQuery.setTaskState(state); taskQuery.setOrderBy(new OrderBy[] { OrderBy.TaskDue_Asc }); if (authority != null) { taskQuery.setActorId(authority); } allTasks = workflowService.queryTasks(taskQuery); } else { // default task state to IN_PROGRESS if not supplied if (state == null) { state = WorkflowTaskState.IN_PROGRESS; } // no workflow instance id is present so get all tasks if (authority != null) { List<WorkflowTask> tasks = workflowService.getAssignedTasks(authority, state); allTasks = new ArrayList<WorkflowTask>(tasks.size()); allTasks.addAll(tasks); // sort tasks by due date // Collections.sort(allTasks, taskComparator); } else { // authority was not provided -> return all active tasks in the system WorkflowTaskQuery taskQuery = new WorkflowTaskQuery(); taskQuery.setTaskState(state); taskQuery.setActive(null); List<WorkflowTask> allTasks1 = workflowService.queryTasks(taskQuery); // unmodifiable -- need better solution allTasks = new ArrayList<WorkflowTask>(allTasks1); } // Sort the tasks before filtering sortTasks(allTasks, sortColumn, sortDirection); } // filter results ArrayList<Map<String, Object>> results = new ArrayList<Map<String, Object>>(); for (WorkflowTask task : allTasks) { if (matches(task, filters)) { // Add flag to specify editability by user Map<String, Object> model = modelBuilder.buildSimple(task, properties); // Overwrite the editability value model.put(modelBuilder.TASK_IS_EDITABLE, SiteWFUtil.canUserChangeWorkflow(task.getPath(), site, workflowService, nodeService, authenticationService, authorityService)); results.add(model); } } // create and return results, paginated if necessary return createResultModel1(req, "taskInstances", results); // Get a subet of the results for pagination // if(sortStart>= 0 && sortCount > 0) // { // if(results.size()-sortStart<sortCount) sortCount = results.size()-sortStart; // List<Map<String, Object>> results1 = (List<Map<String, Object>>)results.subList(sortStart, sortCount); // // return createResultModel(req, "taskInstances", results1); // } // else // { // // create and return results, paginated if necessary // return createResultModel(req, "taskInstances", results); // } }
From source file:com.almende.eve.transport.http.DebugServlet.java
@Override public void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws IOException, ServletException { if (!handleSession(req, resp)) { if (!resp.isCommitted()) { resp.sendError(HttpServletResponse.SC_UNAUTHORIZED); }/*from w w w . jav a 2 s . c om*/ resp.flushBuffer(); return; } // retrieve the url and the request body final String body = StringUtil.streamToString(req.getInputStream()); final String url = req.getRequestURI(); final String id = getId(url); if (id == null || id.equals("") || id.equals(myUrl.toASCIIString())) { resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Couldn't parse URL, missing 'id'"); resp.flushBuffer(); return; } String sender = req.getHeader("X-Eve-SenderUrl"); if (sender == null || sender.equals("")) { sender = "web://" + req.getRemoteUser() + "@" + req.getRemoteAddr(); } URI senderUrl = null; try { senderUrl = new URI(sender); } catch (final URISyntaxException e) { LOG.log(Level.WARNING, "Couldn't parse senderUrl:" + sender, e); } final HttpTransport transport = HttpService.get(myUrl, id); if (transport != null) { try { final String response = transport.receive(body, senderUrl); // TODO: It doesn't need to be json, should we handle mime-types // better? resp.addHeader("Content-Type", "application/json"); resp.getWriter().println(response); resp.getWriter().close(); } catch (final IOException e) { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Receiver raised exception:" + e.getMessage()); } } else { resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Couldn't load transport"); } resp.flushBuffer(); }
From source file:com.janrain.backplane.server.BackplaneController.java
/** * Handle auth errors//from w ww . j a v a2s . c o m */ @ExceptionHandler @ResponseBody public Map<String, String> handle(final AuthException e, HttpServletResponse response) { logger.error("Backplane authentication error: " + bpConfig.getDebugException(e)); response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return new HashMap<String, String>() { { put(ERR_MSG_FIELD, e.getMessage()); } }; }
From source file:net.geant.edugain.filter.EduGAINFilter.java
private void fromHome(HttpServletRequest request, HttpServletResponse response) { String target = request.getParameter("TARGET"); AuthenticationResponse eduGAINresponse = null; try {//from w w w. j a v a 2 s .c o m eduGAINresponse = getSAMLResponse(request.getParameter("SAMLResponse").getBytes()); } catch (Exception e) { e.printStackTrace(); try { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unable to parse eduGAIN response"); return; } catch (IOException e1) { this.log.error("Invalid eduGAIN response; unable to forward user to error page"); } } if ((eduGAINresponse != null) && eduGAINresponse.getResult().equals(AuthenticationResponse.EDUGAIN_NAMESPACE_RESULT_ACCEPTED)) { try { Cookie lcook = getCookie(request, response, "statecook"); HashMap attrs = validateCookie(lcook, "statecook"); if ((attrs != null) && (attrs.containsKey("KEY"))) { String key = (String) attrs.get("KEY"); HashMap<String, String> oldRequest = (HashMap<String, String>) this.loadRequest(key); String oldURL = reconstructRequest(oldRequest, response); attrs = parseAttrs(eduGAINresponse); request.getSession().setAttribute("SAMLResponse", eduGAINresponse.toSAML()); attachCookies("lcook", attrs, response, false); attachCookies("statecook", null, response, true); //addAttributes(attrs,request.getSession()); if (!(oldURL.equals("")) && (oldRequest != null) && !(response.isCommitted())) response.sendRedirect(oldURL); else response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unable to load old request"); } else response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Connection timed out"); } catch (IOException ioe) { try { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "State cookie not found"); } catch (IOException e) { this.log.error("State cookie not found"); ioe.printStackTrace(); } } catch (Exception e) { try { e.printStackTrace(); response.sendError(HttpServletResponse.SC_REQUEST_TIMEOUT, "Process timed out"); } catch (IOException e1) { this.log.error("Process timed out"); e1.printStackTrace(); } } } else try { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid authentication at home domain"); } catch (IOException e) { this.log.error("Invalid authentication at home domain"); e.printStackTrace(); } catch (IllegalStateException ex) { this.log.error("Unable to forward user to error page"); ex.printStackTrace(); } }
From source file:com.vcredit.lrh.microservice.gateway.api.redis.SecurityHandlerRedis.java
private void unauthorizedRequest(HttpServletResponse httpServletResponse) throws IOException { JSONObject jSONObject = new JSONObject(); PrintWriter pw = httpServletResponse.getWriter(); // httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED); jSONObject.put("type", LrhConstants.ErrorCodeTypeEnum.RELOGIN.getCode()); jSONObject.put("success", false); jSONObject.put("code", HttpServletResponse.SC_UNAUTHORIZED); jSONObject.put("message", "???"); pw.write(jSONObject.toJSONString()); pw.flush();/*from w w w. ja v a 2 s .c o m*/ }
From source file:com.wadpam.guja.oauth2.web.Oauth2ClientAuthenticationFilter.java
@Override public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { LOGGER.debug("Oauth2 client authentication"); HttpServletRequest request = (HttpServletRequest) req; HttpServletResponse response = (HttpServletResponse) res; // Either the Authorize header or json body is used to provide the client credentials String authHeader = request.getHeader(OAuth2Filter.HEADER_AUTHORIZATION); ClientCredentials credentials = null; if (request.getContentLength() > 0 && (request.getContentType().startsWith(MediaType.APPLICATION_JSON) || request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED))) { HttpBodyRequestWrapper wrappedRequest = new HttpBodyRequestWrapper(request); if (request.getContentType().startsWith(MediaType.APPLICATION_JSON)) { // Parse JSON body credentials = objectMapper.readValue(wrappedRequest.getBody(), ClientCredentials.class); } else if (request.getContentType().startsWith(MediaType.APPLICATION_FORM_URLENCODED)) { // Parse the form encoded request body. Remember to URL decode the parameters Map<String, String> formParams = Splitter.on("&").trimResults().withKeyValueSeparator("=") .split(wrappedRequest.getBody()); formParams = Maps.transformValues(formParams, new Function<String, String>() { @Override// w ww . j av a 2 s . com public String apply(String value) { try { return URLDecoder.decode(value, "UTF-8"); } catch (UnsupportedEncodingException e) { LOGGER.error("Not possible to URL decode {}", e); return value; } } }); LOGGER.debug("URL decoded form body {}", formParams); credentials = new ClientCredentials(); credentials.setClient_id(formParams.get("client_id")); credentials.setClient_secret((formParams.get("client_secret"))); } // Must wrap the request request = wrappedRequest; } // Check for duplicate authentication methods - invalid request if (null != authHeader && null != credentials && null != credentials.getClient_id() && null != credentials.getClient_secret()) { LOGGER.info("Bad request - duplicate client authentication credentials"); // Multiple authentication credentials (400, "invalid_request") errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST); return; } // check for header if (null != authHeader) { LOGGER.debug("{}: {}", OAuth2Filter.HEADER_AUTHORIZATION, authHeader); int beginIndex = authHeader.indexOf(PREFIX_BASIC_AUTHENTICATION); if (-1 < beginIndex) { String baString = authHeader.substring(beginIndex + PREFIX_BASIC_AUTHENTICATION.length()); String storedBaString = getBasicAuthenticationString(); LOGGER.debug("{} equals? {}", baString, storedBaString); if (!baString.equals(storedBaString)) { LOGGER.info("Unauthorized - invalid client credentials"); // Unauthorized (401, "invalid_client") response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else { // Unsupported client authentication method (401, "invalid_client") LOGGER.info("Unauthorized - client authentication method not supported"); response.setHeader(HEADER_WWW_AUTHENTICATE, PREFIX_BEARER); // TODO What should be returned errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else if (null != credentials) { // Check JSON LOGGER.debug(String.format("%s: %s, %s", PREFIX_BASIC_AUTHENTICATION, credentials.getClient_id(), credentials.getClient_secret())); if (null == credentials.getClient_id() && null == credentials.getClient_secret()) { // No client authentication included (401, "invalid_client") LOGGER.info("Unauthorized - no client credentials found"); errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } else if (null == credentials.getClient_id() ^ null == credentials.getClient_secret()) { LOGGER.info("Bad request - missing required parameter"); // Missing client authentication parameter (400, "invalid_request") errorMessage(response, HttpServletResponse.SC_BAD_REQUEST, ERROR_INVALID_REQUEST); return; } else if (!isCredentialsValid(credentials.getClient_id(), credentials.getClient_secret())) { LOGGER.info("Unauthorized - invalid client credentials"); // Unauthorized (401, "invalid_client") errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } } else { // No client authentication included (401, "invalid_client") LOGGER.info("Unauthorized - no client credentials found"); errorMessage(response, HttpServletResponse.SC_UNAUTHORIZED, ERROR_INVALID_CLIENT); return; } chain.doFilter(request, response); }