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:au.edu.uq.cmm.benny.Benny.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String user = req.getParameter("user");
    String password = req.getParameter("password");
    if (user == null && password == null) {
        String[] credentials = getBasicAuthCredentials(req);
        if (credentials == null) {
            resp.setHeader("WWW-Authenticate", "Basic realm=\"" + realm + "\"");
            respond(resp, HttpServletResponse.SC_UNAUTHORIZED, "No credentials provided");
            return;
        }/*from   w  w  w . j  av  a  2s.  c  om*/
        user = credentials[0];
        password = credentials[1];
    }
    try {
        LOG.debug("checking user='" + user + "', password='XXXXXX'");
        boolean ok = authenticator.authenticate(user, password, null) != null;
        if (ok) {
            respond(resp, HttpServletResponse.SC_OK, "Credentials accepted");
        } else {
            respond(resp, HttpServletResponse.SC_FORBIDDEN, "Credentials rejected");
        }
    } catch (IOException ex) {
        throw ex;
    } catch (Exception ex) {
        LOG.error("Unexpected exception", ex);
        respond(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Service error");
    }
}

From source file:com.rockagen.gnext.service.spring.security.extension.ExAuthenticationHandler.java

/**
 * Authentication failure handler/* w  w w. j  a v a  2  s  .co m*/
 *
 * @param request  request
 * @param response response
 */
public void failureHandler(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String uid = request.getParameter(username);
    try {
        failureRegister(uid, request);
    } catch (AuthenticationException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, e.getMessage());
    }
}

From source file:com.mnt.base.web.DigestAuthenticator.java

/**
 * WWW-Authenticate: Digest realm="testrealm@host.com",
  *                   qop="auth,auth-int",
  *                   nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093",
  *                   opaque="5ccc069c403ebaf9f0171e9517f40e41"
 * @param req // w  w  w .ja  va2s  .c  o m
 *
 * @param resp
 * @param authInfoMap
 */
private static void postAuthRequired(HttpServletRequest req, HttpServletResponse resp,
        Map<String, Object> authInfoMap) {

    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    StringBuilder sb = new StringBuilder();
    String siteHost;
    siteHost = req.getHeader("Host");
    if (siteHost == null) {
        siteHost = "www.mntplay.com";
    }

    sb.append("Digest realm=\"" + siteHost + "\",algorithm=\"md5\",");
    sb.append("qop=\"auth,auth-int\",");

    String nonce = (String) authInfoMap.get("nonce");

    if (nonce == null) {
        nonce = UUID.randomUUID().toString();
    }

    String opaque = UUID.randomUUID().toString();

    sb.append("nonce=\"" + nonce + "\",");
    sb.append("opaque=\"" + opaque + "\"");

    authInfoMap.put("nonce", nonce);
    resp.setHeader("WWW-Authenticate", sb.toString());

    try {
        resp.flushBuffer();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.obiba.shiro.web.filter.AuthenticationFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    if (ThreadContext.getSubject() != null) {
        log.warn("Previous executing subject was not properly unbound from executing thread. Unbinding now.");
        ThreadContext.unbindSubject();//from w ww . ja v a  2s.  co m
    }

    try {
        authenticateAndBind(request);
        filterChain.doFilter(request, response);
    } catch (AuthenticationException e) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } catch (Exception e) {
        log.error("Exception", e);
        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        response.getWriter().println(e.getMessage());
    } finally {
        unbind();
    }
}

From source file:com.vmware.identity.samlservice.impl.AuthnRequestStateKerbAuthenticationFilter.java

@Override
public void authenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateKerbAuthenticationFilter.authenticate is called");

    Validate.notNull(t);//from ww w . j  a  v a 2 s. co m
    IdmAccessor accessor = t.getIdmAccessor();
    Validate.notNull(accessor);
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    AuthnRequest authnRequest = t.getAuthnRequest();
    Validate.notNull(authnRequest);

    GSSResult result = null;

    // call IDM to perform GSS auth
    String castleAuthParam = request.getParameter(Shared.REQUEST_AUTH_PARAM);
    Validate.notNull(castleAuthParam);
    castleAuthParam = castleAuthParam.replace(Shared.KERB_AUTH_PREFIX, "").trim();
    String[] parts = castleAuthParam.split(" ");
    Validate.isTrue(parts.length == 1 || parts.length == 2);

    String browserAuthHeader = request.getHeader(Shared.IWA_AUTH_REQUEST_HEADER);
    String contextId = parts[0];
    String encodedToken = null;

    if (parts.length == 1) {
        t.setKerbAuthnType(KerbAuthnType.IWA);
        if (browserAuthHeader == null) {
            t.setWwwAuthenticate(Shared.KERB_AUTH_PREFIX);
            t.setValidationResult(
                    new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized", null));
            throw new SamlServiceException();
        } else {
            encodedToken = browserAuthHeader.replace(Shared.KERB_AUTH_PREFIX, "").trim();
        }
    } else {
        t.setKerbAuthnType(KerbAuthnType.CIP);
        encodedToken = parts[1];
    }

    Validate.notEmpty(contextId);
    Validate.notEmpty(encodedToken);
    byte[] decodedAuthData = Base64.decode(encodedToken);

    try {
        result = accessor.authenticate(contextId, decodedAuthData);
    } catch (Exception ex) {
        // Could not authenticate with GSS, send browser login credential
        // error message. this allow user fall back to using password
        // authentication.
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized", null);
        t.setValidationResult(vr);
        throw new SamlServiceException();
    }

    if (result != null) {
        if (!result.complete()) {
            // need additional auth exchange
            log.debug("Requesting more auth data");
            String encodedAuthData = Shared.encodeBytes(result.getServerLeg());
            if (t.getKerbAuthnType() == KerbAuthnType.CIP) {
                t.setWwwAuthenticate(Shared.KERB_AUTH_PREFIX + " " + contextId + " " + encodedAuthData);
            } else {
                t.setWwwAuthenticate(Shared.KERB_AUTH_PREFIX + " " + encodedAuthData);
            }
            t.setValidationResult(
                    new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized", null));
            throw new SamlServiceException();
        }

        PrincipalId principalId = result.getPrincipalId();
        Validate.notNull(principalId);
        t.setPrincipalId(principalId);
        t.setAuthnMethod(AuthnMethod.KERBEROS);
    }
}

From source file:in.flipbrain.controllers.App.java

@Action
public void loginJson() throws IOException, ServletException {
    if (isJsonRequest()) {
        boolean failed = true;
        HashMap<String, Object> result = new HashMap<String, Object>();
        String jsonPayload = getJsonData();
        UserDto user = gson.fromJson(jsonPayload, UserDto.class);
        // Login using external service
        if (user.auth2Code != null && user.login == null && user.password == null) {
            // Check with Google API
            if (Utils.auth2Check(user.auth2Code, getConfigValue(Constants.CFG_GA_CLIENT_ID))) {
                user.external = true;// ww w .  ja  v a 2 s. c o  m
                user.password = RandomStringUtils.randomAlphanumeric(10);
                user.login = user.email;
                UserDto u2 = MyBatisDao.getInstance(getClientInfo()).getUserByLogin(user.login);
                if (u2 == null) {
                    result = saveUser(user); // Save only first time
                }
                user = u2;
                failed = false;
            }
        } else {
            failed = !loginProvider.login(user.login, user.password);
        }
        recordLoginAttempt(user, failed);
        if (failed) {
            result.put("Status", "error");
            result.put("Message",
                    user != null && user.failedLogins >= 3
                            ? "Too many failed logins! Your account has been locked."
                            : "Login or password is wrong. Please retry.");
            sendJsonErrorResponse(HttpServletResponse.SC_UNAUTHORIZED, gson.toJson(result));
            return;
        } else {
            user = MyBatisDao.getInstance(getClientInfo()).getUserByLogin(user.login);
            user.password = null;
            setSessionAttribute(Constants.SK_USER, user);
            setSessionAttribute(Constants.SK_ROLES, user.getRoleNames());
            result.put("Status", "success");
        }
        Json(gson.toJson(result));
    } else {
        sendJsonErrorResponse(406, "Expected JSON request.");
    }
}

From source file:org.openxdata.server.servlet.DataImportServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    ServletOutputStream out = response.getOutputStream();
    try {//from   w  w w  .  j a va  2  s  .c o  m
        // authenticate user
        User user = getUser(request.getHeader("Authorization"));
        if (user != null) {
            log.info("authenticated user:");
            // check msisdn
            String msisdn = request.getParameter("msisdn");
            if (msisdn != null && !msisdn.equals("")) {
                // if an msisdn is sent, then we retrieve the user with that phone number
                authenticateUserBasedOnMsisd(msisdn);
            }

            // can be empty or null, then the default is used. this parameter is a key in the settings table indicating the classname of the serializer to use
            String serializer = request.getParameter("serializer");

            // input stream
            // first byte contains number of forms (x)
            // followed by x number of UTF strings (use writeUTF method in DataOutput)
            formDownloadService.submitForms(request.getInputStream(), out, serializer);

        } else {
            response.setHeader("WWW-Authenticate", "BASIC realm=\"openxdata\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (UserNotFoundException userNotFound) {
        out.println("Invalid msisdn");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    } catch (Exception e) {
        log.error("Could not import data", e);
        out.println(e.getMessage());
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    } finally {
        out.close();
    }
}

From source file:com.sg.rest.SpringSecurityTest.java

@Test
public void testNonExistentResourceWhichStartsFromSecurePath() throws Exception {
    mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST + PATH_DO_NOT_EXIST))
            .andExpect(status().is(HttpServletResponse.SC_UNAUTHORIZED))
            .andExpect(content().contentType(CustomMediaTypes.APPLICATION_JSON_UTF8.getMediatype()))
            .andExpect(jsonPath("$.eventRef.id", not(isEmptyOrNullString()))).andExpect(jsonPath("$.status",
                    is(AuthentificationFailureStatus.TOKEN_AUTHENTICATION_NO_TOKEN.name())));
}

From source file:eu.trentorise.smartcampus.permissionprovider.auth.google.GoogleController.java

/**
 * This rest web service is the one that google called after login (callback
 * url). First it retrieve code and token that google sends back. It checks
 * if code and token are not null, then if token is the same that was saved
 * in session. If it is not response status is UNAUTHORIZED, otherwise it
 * retrieves user data. If user is not already saved in db, then user is
 * added in db, iff email is not already used, otherwise it sends an
 * UNAUTHORIZED status and redirect user to home page without authenticating
 * him/her. If it is all ok, then it authenticates user in spring security
 * and create cookie user. Then redirects authenticated user to home page
 * where user can access protected resources.
 * /*from  ww  w.  ja v a2s.  co m*/
 * @param request
 *            : instance of {@link HttpServletRequest}
 * @param response
 *            : instance of {@link HttpServletResponse}
 * @return redirect to home page
 */
@RequestMapping(value = "/callback", method = RequestMethod.GET)
public String confirmStateToken(HttpServletRequest request, HttpServletResponse response) {

    String code = request.getParameter("code");
    String token = request.getParameter("state");
    String sessionStateToken = "";
    if (request.getSession().getAttribute(SESSION_ATTR_STATE) != null) {
        sessionStateToken = request.getSession().getAttribute(SESSION_ATTR_STATE).toString();
    }

    // compare state token in session and state token in response of google
    // if equals return to home
    // if not error page
    if ((code == null || token == null) && (!token.equals(sessionStateToken))) {
        logger.error("Error in google authentication flow");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return "";
    } else {
        try {
            GoogleUser userInfo = auth.getUserInfoJson(code);
            response.setStatus(HttpServletResponse.SC_OK);
            request.getSession().setAttribute(GoogleAuthHelper.SESSION_GOOGLE_CHECK, "true");
            return String.format(
                    "redirect:/eauth/google?target=%s&OIDC_CLAIM_email=%s&OIDC_CLAIM_given_name=%s&OIDC_CLAIM_family_name=%s",
                    URLEncoder.encode((String) request.getSession().getAttribute("redirect"), "UTF8"),
                    userInfo.getEmail(), userInfo.getGivenName(), userInfo.getFamilyName());

        } catch (IOException e) {
            logger.error("IOException .. Problem in reading user data.", e);
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    return "redirect:/";
}

From source file:org.openmrs.module.clinicalsummary.web.controller.service.LocationCohortController.java

@RequestMapping(method = RequestMethod.GET)
public void searchCohort(@RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "password") String password,
        @RequestParam(required = true, value = "locationId") Integer locationId,
        @RequestParam(required = true, value = "summaryId") Integer summaryId, HttpServletResponse response)
        throws IOException {

    try {//from ww  w .  j  a  v a2  s .c  o  m
        if (!Context.isAuthenticated())
            Context.authenticate(username, password);

        String cohortTimeFrame = Context.getAdministrationService()
                .getGlobalProperty(CLINICALSUMMARY_SERVICE_TIMEFRAME);
        Integer timeFrame = NumberUtils.toInt(cohortTimeFrame, 5);

        Location location = Context.getLocationService().getLocation(locationId);
        Summary summary = Context.getService(SummaryService.class).getSummary(summaryId);

        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, -timeFrame);
        Date startDate = calendar.getTime();

        calendar = Calendar.getInstance();
        calendar.add(Calendar.DATE, timeFrame);
        Date endDate = calendar.getTime();

        List<Index> indexes = Context.getService(IndexService.class).getIndexes(location, summary, startDate,
                endDate);

        Set<Patient> patients = new HashSet<Patient>();
        for (Index index : indexes) {
            Patient patient = index.getPatient();
            if (CollectionUtils.isNotEmpty(patient.getIdentifiers()))
                patients.add(index.getPatient());
        }

        // serialize the the search result
        XStream xStream = new XStream();
        xStream.alias("results", Set.class);
        xStream.alias("patient", Patient.class);
        xStream.registerConverter(new PatientConverter());
        xStream.registerConverter(new PatientIdentifierConverter());
        xStream.registerConverter(new PersonNameConverter());
        xStream.toXML(patients, response.getOutputStream());
    } catch (ContextAuthenticationException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}