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:jp.mathes.databaseWiki.dav.DavServlet.java

@Override
public void service(final javax.servlet.ServletRequest servletRequest,
        final javax.servlet.ServletResponse servletResponse) throws ServletException, IOException {
    HttpServletRequest req = (HttpServletRequest) servletRequest;
    HttpServletResponse resp = (HttpServletResponse) servletResponse;
    if (req.getHeader("Authorization") != null) {
        resp.setStatus(HttpServletResponse.SC_OK);
        resp.setContentType("application/xhtml+xml");
        try {/*from  www. j av a2s  . co  m*/
            Request request = new ServletRequest(req);
            Response response = new ServletResponse(resp);
            this.httpManager.process(request, response);
        } finally {
            servletResponse.getOutputStream().flush();
            servletResponse.flushBuffer();
        }
    } else {
        resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        resp.setHeader("WWW-Authenticate", "Basic realm=\"databaseWiki\"");
    }
}

From source file:edu.harvard.hms.dbmi.bd2k.irct.cl.filter.SessionFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
        throws IOException, ServletException {

    // Calls to the Security Service can go straight through
    if (!((HttpServletRequest) req).getPathInfo().startsWith("/securityService/")) {
        //Get the session and user information
        HttpSession session = ((HttpServletRequest) req).getSession();
        User user = (User) session.getAttribute("user");

        // Is a user already associated with a session?
        if (user == null) {

            // If no user is associated then validate the authorization
            // header
            String email = validateAuthorizationHeader((HttpServletRequest) req);

            if (email == null) {
                ((HttpServletResponse) res).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                res.getOutputStream().write("{\"message\":\"Session is not authorized\"}".getBytes());
                res.getOutputStream().close();
                return;
            }//from   w  w w.  j a va 2  s .  c o  m

            user = sc.getUser(email);
            Token token = new JWT(((HttpServletRequest) req).getHeader("Authorization"), "", "Bearer",
                    this.clientId);
            SecureSession secureSession = new SecureSession();
            secureSession.setToken(token);
            secureSession.setUser(user);

            session.setAttribute("user", user);
            session.setAttribute("token", token);
            session.setAttribute("secureSession", secureSession);

        }
    } else {
        String name = validateAuthorizationHeader((HttpServletRequest) req);

        if (name != null) {
            HttpSession session = ((HttpServletRequest) req).getSession();

            User user = sc.getUser(name);
            Token token = new JWT(((HttpServletRequest) req).getHeader("Authorization"), "", "Bearer",
                    this.clientId);
            SecureSession secureSession = new SecureSession();
            secureSession.setToken(token);
            secureSession.setUser(user);

            session.setAttribute("user", user);
            session.setAttribute("token", token);
            session.setAttribute("secureSession", secureSession);
        }

    }

    fc.doFilter(req, res);
}

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestController.java

/**
 * @should return unauthorized if not logged in
 * @should return forbidden if logged in
 *///  w w w  .  ja v a  2 s . c om
@ExceptionHandler(APIAuthenticationException.class)
@ResponseBody
public SimpleObject apiAuthenticationExceptionHandler(Exception ex, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    int errorCode;
    String errorDetail;
    if (Context.isAuthenticated()) {
        // user is logged in but doesn't have the relevant privilege -> 403 FORBIDDEN
        errorCode = HttpServletResponse.SC_FORBIDDEN;
        errorDetail = "User is logged in but doesn't have the relevant privilege";
    } else {
        // user is not logged in -> 401 UNAUTHORIZED
        errorCode = HttpServletResponse.SC_UNAUTHORIZED;
        errorDetail = "User is not logged in";
        if (shouldAddWWWAuthHeader(request)) {
            response.addHeader("WWW-Authenticate",
                    "Basic realm=\"OpenMRS at " + RestConstants.URI_PREFIX + "\"");
        }
    }
    response.setStatus(errorCode);
    return RestUtil.wrapErrorResponse(ex, errorDetail);
}

From source file:jp.aegif.nemaki.rest.AuthenticationFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest hreq = (HttpServletRequest) req;
    HttpServletResponse hres = (HttpServletResponse) res;

    boolean auth = login(hreq, hres);
    if (auth) {/*  w ww.  ja v  a 2 s .c  o m*/
        chain.doFilter(req, res);
    } else {
        log.error("REST API Unauthorized!");
        hres.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.craftercms.security.authentication.impl.AuthenticationRequiredHandlerImplTest.java

@Test
public void testSendError() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    MockHttpServletResponse response = new MockHttpServletResponse();
    RequestContext context = new RequestContext(request, response);

    handler.handle(context, new AuthenticationRequiredException(""));

    verify(requestCache).saveRequest(request, response);

    assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getStatus());
    assertTrue(response.isCommitted());/* w  ww. j  a  va 2s  .  c  o  m*/
}

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

@JsonIgnore
@RequestMapping("/service/setting")
public void serviceSetting(HttpServletRequest request, HttpServletResponse response) {
    User user = new User();
    HttpSession httpSession = request.getSession();
    user.setId(httpSession.getId());/*from   www  .jav a 2 s  . co  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/setting");
        }

        return;
    }

    SettingFrontEnd settingFrontEnd = new SettingFrontEnd();

    settingFrontEnd.setCheckSettingMusicAirplane(Integer.valueOf(request.getParameter("musicAirplane")));
    settingFrontEnd.setCheckSettingMusicChat(Integer.valueOf(request.getParameter("musicChat")));
    settingFrontEnd.setCheckSettingMusicService(Integer.valueOf(request.getParameter("musicService")));
    settingFrontEnd.setCheckSettingShowClock(Integer.valueOf(request.getParameter("showClock")));
    settingFrontEnd
            .setCheckSettingShowDispatcherOnline(Integer.valueOf(request.getParameter("showDispatcher")));
    settingFrontEnd.setCheckSettingShowNewMessage(Integer.valueOf(request.getParameter("showNewMessage")));
    settingFrontEnd.setCheckSettingShowProfile(Integer.valueOf(request.getParameter("showProfile")));
    settingFrontEnd.setCheckSettingShowWeather(Integer.valueOf(request.getParameter("showWeather")));

    serviceSetting.setSettingFrontEnd(user, settingFrontEnd);

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

From source file:org.openmrs.module.webservices.rest.web.v1_0.controller.BaseRestControllerTest.java

/**
 * @verifies return unauthorized if not logged in
 * @see BaseRestController#apiAuthenticationExceptionHandler(Exception,
 *      javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
 *///  w  w w . ja v  a 2s. c  o m
@Test
public void apiAuthenticationExceptionHandler_shouldReturnUnauthorizedIfNotLoggedIn() throws Exception {
    Context.logout();

    controller.apiAuthenticationExceptionHandler(new APIAuthenticationException(), request, response);

    assertThat(response.getStatus(), is(HttpServletResponse.SC_UNAUTHORIZED));
}

From source file:com.google.gsa.valve.modules.noauth.HTTPNoAuthenticationProcess.java

/**
 * This method simulates the authentication process against a content 
 * source, so that every document is consider here as public.
 * <p>/*  ww w . j  a v  a  2s.c  om*/
 * Creates the authentication cookie and always return 200, unless there is 
 * any problem processing the request.
 * 
 * @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 {

    Cookie[] cookies = null;

    // Initialize status code
    int statusCode = HttpServletResponse.SC_UNAUTHORIZED;

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

    // Debug
    logger.debug("HTTP No authentication start");

    //
    // Launch the authentication process
    //

    // Protection
    try {

        Cookie extAuthCookie = null;
        extAuthCookie = new Cookie("gsa_basic_noauth", "");

        extAuthCookie.setValue("true");

        String authCookieDomain = null;
        String authCookiePath = null;
        int authMaxAge = -1;

        // Cache cookie properties
        authCookieDomain = (request.getAttribute("authCookieDomain")).toString();
        authCookiePath = (request.getAttribute("authCookiePath")).toString();
        //authMaxAge
        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:");
        }

        // Set extra cookie parameters
        extAuthCookie.setDomain(authCookieDomain);
        extAuthCookie.setPath(authCookiePath);
        extAuthCookie.setMaxAge(authMaxAge);

        // Log info
        if (logger.isDebugEnabled())
            logger.debug("Adding gsa_basic_noauth cookie: " + extAuthCookie.getName() + ":"
                    + extAuthCookie.getValue() + ":" + extAuthCookie.getPath() + ":" + extAuthCookie.getDomain()
                    + ":" + extAuthCookie.getSecure());

        //add sendCookies support
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("HTTP Basic authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // End of the authentication process
    logger.debug("HTTP No Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

From source file:com.mirth.connect.server.servlets.ConfigurationServlet.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // MIRTH-1745
    response.setCharacterEncoding("UTF-8");

    try {//from w  ww  .jav a2 s  . co m
        PrintWriter out = response.getWriter();
        Operation operation = Operations.getOperation(request.getParameter("op"));

        if (operation.equals(Operations.CONFIGURATION_STATUS_GET)) {
            response.setContentType(TEXT_PLAIN);
            out.println(ControllerFactory.getFactory().createConfigurationController().getStatus());
        } else if (!isUserLoggedIn(request)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
        } else {
            ConfigurationController configurationController = ControllerFactory.getFactory()
                    .createConfigurationController();
            ScriptController scriptController = ControllerFactory.getFactory().createScriptController();
            ObjectXMLSerializer serializer = new ObjectXMLSerializer();
            Map<String, Object> parameterMap = new HashMap<String, Object>();

            if (operation.equals(Operations.CONFIGURATION_CHARSET_ENCODINGS_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(configurationController.getAvaiableCharsetEncodings(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_SERVER_SETTINGS_GET)) {
                response.setContentType(APPLICATION_XML);

                if (isUserAuthorized(request, null)) {
                    serializer.toXML(configurationController.getServerSettings(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_SERVER_SETTINGS_SET)) {
                String settings = request.getParameter("data");
                parameterMap.put("settings", settings);

                if (isUserAuthorized(request, parameterMap)) {
                    configurationController.setServerSettings((ServerSettings) serializer.fromXML(settings));
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_UPDATE_SETTINGS_GET)) {
                response.setContentType(APPLICATION_XML);

                if (isUserAuthorized(request, null)) {
                    serializer.toXML(configurationController.getUpdateSettings(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_UPDATE_SETTINGS_SET)) {
                String settings = request.getParameter("data");
                parameterMap.put("settings", settings);

                if (isUserAuthorized(request, parameterMap)) {
                    configurationController.setUpdateSettings((UpdateSettings) serializer.fromXML(settings));
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_ENCRYPTION_SETTINGS_GET)) {
                response.setContentType(APPLICATION_XML);

                if (isUserAuthorized(request, null)) {
                    serializer.toXML(configurationController.getEncryptionSettings(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_GUID_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(TEXT_PLAIN);
                    out.print(configurationController.generateGuid());
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_DATABASE_DRIVERS_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(configurationController.getDatabaseDrivers(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_VERSION_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(TEXT_PLAIN);
                    out.print(configurationController.getServerVersion());
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_BUILD_DATE_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(TEXT_PLAIN);
                    out.print(configurationController.getBuildDate());
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.SERVER_CONFIGURATION_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(configurationController.getServerConfiguration(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.SERVER_CONFIGURATION_SET)) {
                String serverConfiguration = request.getParameter("data");
                parameterMap.put("data", serverConfiguration);

                if (isUserAuthorized(request, parameterMap)) {
                    configurationController.setServerConfiguration(
                            (ServerConfiguration) serializer.fromXML(serverConfiguration));
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_SERVER_ID_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    out.println(configurationController.getServerId());
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_SERVER_TIMEZONE_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    out.println(configurationController.getServerTimezone(request.getLocale()));
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.GLOBAL_SCRIPT_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(scriptController.getGlobalScripts(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.GLOBAL_SCRIPT_SET)) {
                String scripts = request.getParameter("scripts");
                parameterMap.put("scripts", scripts);

                if (isUserAuthorized(request, parameterMap)) {
                    scriptController.setGlobalScripts((Map<String, String>) serializer.fromXML(scripts));
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            } else if (operation.equals(Operations.CONFIGURATION_PASSWORD_REQUIREMENTS_GET)) {
                if (isUserAuthorized(request, null)) {
                    response.setContentType(APPLICATION_XML);
                    serializer.toXML(configurationController.getPasswordRequirements(), out);
                } else {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                }
            }
        }
    } catch (RuntimeIOException rio) {
        logger.debug(rio);
    } catch (Throwable t) {
        logger.error(ExceptionUtils.getStackTrace(t));
        throw new ServletException(t);
    }
}

From source file:edu.slu.tpen.servlet.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method by logging in using the given credentials.  Credentials
 * should be specified as a JSON object in the request body.  There is also a deprecated way of passing
 * the credentials as query parameters./*w w w.  ja  va2s .  c  o m*/
 *
 * @param req servlet request
 * @param resp servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String mail = null, password = null;
        if (req.getContentLength() > 0) {
            String contentType = getBaseContentType(req);
            if (contentType.equals("application/json")) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> creds = mapper.readValue(req.getInputStream(),
                        new TypeReference<Map<String, String>>() {
                        });
                mail = creds.get("mail");
                password = creds.get("password");
            }
        } else {
            // Deprecated approach where user-name and password are passed on the query string.
            mail = req.getParameter("uname");
            password = req.getParameter("password");
        }
        if (mail != null && password != null) {
            User u = new User(mail, password);
            if (u.getUID() > 0) {
                HttpSession sess = req.getSession(true);
                sess.setAttribute("UID", u.getUID());
            } else {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        } else if (mail == null && password == null) {
            // Passing null data indicates a logout.
            HttpSession sess = req.getSession(true);
            sess.removeAttribute("UID");
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            // Only supplied one of user-id and password.
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (NoSuchAlgorithmException ex) {
        reportInternalError(resp, ex);
    }
}