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:com.vmware.identity.proxyservice.LogonProcessorImpl.java

@Override
public void authenticationError(Message arg0, Locale locale, String tenant, HttpServletRequest request,
        HttpServletResponse response) {/*w  w  w . j av  a 2s .  c o  m*/

    Validate.notNull(arg0, "arg0");
    Validate.notNull(response, "response");
    try {

        ValidationResult vrExtIdpSsoResponse = retrieveValidationResult(arg0);

        //retrieve current VR
        if (!arg0.isIdpInitiated() && requestState != null) {
            ValidationResult vr = requestState.getValidationResult();
            if (!(null != vr && !vr.isValid())) {
                requestState.setValidationResult(vrExtIdpSsoResponse);
            }
        } else {
            Validate.notEmpty(tenant, "tenant");
            Validate.notNull(locale, "locale");

        }

        //retrieve browser locale
        if (null == locale) {
            locale = requestState == null ? Locale.getDefault() : requestState.getLocale();
        }

        int responseCode = vrExtIdpSsoResponse.getResponseCode();

        //default code is  HttpServletResponse.SC_UNAUTHORIZED
        if (responseCode == HttpServletResponse.SC_OK) {
            responseCode = HttpServletResponse.SC_UNAUTHORIZED;
        }

        String message = vrExtIdpSsoResponse.getMessage(messageSource, locale);

        if (OasisNames.RESPONDER.equals(vrExtIdpSsoResponse.getStatus())) {
            message = messageSource.getMessage(ExternalIDPErrorMessageName, null, locale) + message;
        }
        response.addHeader(Shared.RESPONSE_ERROR_HEADER, Shared.encodeString(message));
        response.sendError(responseCode, message);
        log.info("External IDP responded with ERROR {} message {}", vrExtIdpSsoResponse.getResponseCode(),
                message);

    } catch (Exception e) {
        log.error("Caught unexpect exception in processing authentication error {}", e.toString());

        throw new IllegalStateException(e);
    }
}

From source file:com.logiclander.jaasmine.authentication.http.SPNegoFilter.java

/**
 * This implementation will filter requests for credentials and determine if
 * processing of the FilterChain can proceed.  Filtering occurs as follows:
 * <OL>/*from  w  w  w  .  ja v  a  2s .  co  m*/
 *  <LI>If the request is not an HttpServletRequest and the response is not
 * an HttpServletResponse, continue processing the filter chain (this almost
 * never happens)</LI>
 *  <LI>The HttpServletRequest is checked for a {@code WWW-Authenticate}
 * request header.  If found, it is checked for the scheme used, which must
 * be set to {@code Negotiate}.</LI>
 *  <LI>If found, the SPNego token is decoded and validated.  If it is
 * valid, processing is allowed to continue.  If not, processing will stop
 * and an HTTP 401 is returned with a {@code WWW-Authenticate} request
 * header set to {@code Negotiate}.</LI>
 *  <LI>If the request header is not found, an HTTP 401 is returned with a
 * {@code WWW-Authenticate} request header set to {@code Negotiate}.</LI>
 * </OL>
 *
 * @param request the ServletRequest
 * @param response the ServletResponse
 * @param chain the FilterChain
 * @throws IOException if an I/O error occurs in the FilterChain
 * @throws ServletException if a processing error occurs in the FilterChain
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    if (logger.isDebugEnabled()) {
        logger.debug(String.format("%s: entering doFilter", filterName));
    }

    if (!(request instanceof HttpServletRequest) && !(response instanceof HttpServletResponse)) {

        chain.doFilter(request, response);

    } else {

        HttpServletRequest httpReq = (HttpServletRequest) request;
        HttpServletResponse httpResp = (HttpServletResponse) response;

        if (logger.isDebugEnabled()) {
            logger.debug(String.format("Filtering request: %s%s", httpReq.getContextPath(),
                    httpReq.getServletPath()));
        }

        String sPNegoToken = getSPNegoToken(httpReq);
        boolean canExecute = false;
        SPNegoServer server = null;

        try {

            server = new SPNegoServer(sPNegoToken);
            canExecute = server.isValidToken();

            // Wrap the HttpServletRequest with the requester's GSSName
            // so that additional processing can take place w/out having
            // to re-examine the SPNego token.
            httpReq = new JaasmineHttpServletRequest(httpReq, server.getRequesterName());

        } catch (GSSException ex) {

            if (logger.isDebugEnabled()) {

                logger.debug("Problem with SPNego token", ex);

            } else {

                logger.info(String.format("Problem with SPNego token: %s", ex.getMessage()));

            }

            canExecute = false;

        } catch (Exception ex) {

            if (logger.isFatalEnabled()) {
                logger.fatal(ex.getMessage(), ex);
            }

            canExecute = false;

        }

        if (canExecute) {

            chain.doFilter(httpReq, httpResp);

        } else {

            if (!httpResp.isCommitted()) {
                httpResp.setHeader("WWW-Authenticate", "Negotiate");
                httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }

        }
    }
}

From source file:org.everit.authentication.http.basic.tests.HttpBasicAuthFilterTestComponent.java

@Test
public void testAccessSecureUrl() throws IOException {
    assertGet(secureUrl, new BasicHeader("Authorization", "Basic " + encode(USERNAME + ":" + PASSWORD)),
            HttpServletResponse.SC_OK, authenticatedResourceId);
    assertGet(secureUrl, null, HttpServletResponse.SC_UNAUTHORIZED, null);
    assertGet(secureUrl, new BasicHeader("Authorization", "BasiC " + encode(USERNAME + ":" + PASSWORD)),
            HttpServletResponse.SC_UNAUTHORIZED, null);
    assertGet(secureUrl, new BasicHeader("Authorization", "Basic " + "1234567890ABCDEFGHI"),
            HttpServletResponse.SC_UNAUTHORIZED, authenticatedResourceId);
    assertGet(secureUrl, new BasicHeader("Authorization", "Basic " + encode(USERNAME + PASSWORD)),
            HttpServletResponse.SC_UNAUTHORIZED, authenticatedResourceId);
    assertGet(secureUrl, new BasicHeader("Authorization", "Basic " + encode(USERNAME + ":" + PASSWORD + "1")),
            HttpServletResponse.SC_UNAUTHORIZED, authenticatedResourceId);
}

From source file:com.zimbra.cs.servlet.util.AuthUtil.java

/**
 * If returns null, then resp.sendError has been called.
 *//* ww w.ja v  a  2 s . c o m*/
public static Account basicAuthRequest(HttpServletRequest req, HttpServletResponse resp, boolean sendChallenge,
        boolean isDav) throws IOException, ServiceException {
    try {
        return basicAuthRequest(req, !sendChallenge, isDav);
    } catch (UserServletException e) {
        if (e.getHttpStatusCode() == HttpServletResponse.SC_UNAUTHORIZED) {
            if (sendChallenge) {
                resp.addHeader(WWW_AUTHENTICATE_HEADER, getRealmHeader(req, null));
                resp.sendError(e.getHttpStatusCode(), e.getMessage());
            }
        } else {
            resp.sendError(e.getHttpStatusCode(), e.getMessage());
        }
        return null;
    }
}

From source file:org.slc.sli.dashboard.web.controller.ConfigController.java

/**
 * Controller for client side data pulls without id.
 * The 'params' parameter contains a map of url query parameters. The parameters are matched
 * to the attributes in the JSON config files.
 *
 * e.g. /s/c/cfg?type=LAYOUT&id=school
 *///w  ww.jav  a  2 s. co m
@RequestMapping(value = "/s/c/cfg", method = RequestMethod.GET)
@ResponseBody
public Collection<Config> handleConfigSearch(@RequestParam Map<String, String> params,
        final HttpServletRequest request, HttpServletResponse response) {

    String token = SecurityUtil.getToken();

    // check user is an admin
    Boolean isAdmin = SecurityUtil.isAdmin();

    if (isAdmin != null && isAdmin.booleanValue()) {
        return configManager.getConfigsByAttribute(token, userEdOrgManager.getUserEdOrg(token), params);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return null;
    }

}

From source file:dk.dma.msinm.user.security.SecurityServletFilter.java

/**
 * If the request contains a Basic authentication header, the user will be logged in for this request
 * using the specified credentials./*  w  w  w . ja  v a  2 s . c  om*/
 * <p>
 * If the authentication fails, this methods does nothing. It is left to the handler of the request,
 * say a Rest endpoint, to throw an error if security requirements are not met.
 *
 * @param request the servlet request
 * @return the request
 */
private HttpServletRequest attemptBasicAuthLogin(HttpServletRequest request) {
    try {
        String token = getAuthHeaderToken(request, BASIC_AUTH);
        if (token != null) {
            String[] cred = new String(Base64.getDecoder().decode(token), "UTF-8").split(":");
            request = SecurityUtils.login(userService, request, cred[0], cred[1]);
            log.trace("Found Basic Auth user " + request.getUserPrincipal().getName());
        }
    } catch (Exception ex) {
        request.setAttribute(AUTH_ERROR_ATTR, HttpServletResponse.SC_UNAUTHORIZED);
        log.warn("Failed logging in using Basic Authentication");
    }
    return request;
}

From source file:org.sakaiproject.tool.section.filter.RoleFilter.java

public void doFilter(ServletRequest servletRequest, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    String servletPath = request.getServletPath();
    if (logger.isDebugEnabled())
        logger.debug("Filtering request for servletPath=" + servletPath);
    servletPath = servletPath.replaceFirst("^/", "");
    if (servletPath.indexOf("/") >= 0) {
        // Only protect the top-level folder, to allow for login through
        // a subdirectory, shared resource files, and so on.
        chain.doFilter(request, response);
        return;/*from w  w w .ja va2  s . c  om*/
    }

    Authn authn = (Authn) ac.getBean(authnBeanName);
    Authz authz = (Authz) ac.getBean(authzBeanName);
    Context context = (Context) ac.getBean(contextBeanName);
    AuthorizationFilterConfigurationBean authzFilterConfigBean = (AuthorizationFilterConfigurationBean) ac
            .getBean(authorizationFilterConfigurationBeanName);
    String userUid = authn.getUserUid(request);

    if (logger.isDebugEnabled())
        logger.debug("Filtering request for user " + userUid + ", pathInfo=" + request.getPathInfo());

    // Try to get the currently selected site context, if any
    String siteContext = context.getContext(request);

    if (logger.isDebugEnabled())
        logger.debug("context=" + siteContext);

    if (siteContext != null) {
        // Get the name of the page from the servlet path.
        String[] splitPath = servletPath.split("[./]");
        String pageName = splitPath[0];

        boolean isAuthorized = false;
        if (authz.isSectionManagementAllowed(userUid, siteContext)
                && authzFilterConfigBean.getManageAllSections().contains(pageName)) {
            isAuthorized = true;
        } else if (authz.isViewAllSectionsAllowed(userUid, siteContext)
                && authzFilterConfigBean.getViewAllSections().contains(pageName)) {
            isAuthorized = true;
        } else if (authz.isSectionTaManagementAllowed(userUid, siteContext)
                && authzFilterConfigBean.getManageTeachingAssistants().contains(pageName)) {
            isAuthorized = true;
        } else if (authz.isSectionEnrollmentMangementAllowed(userUid, siteContext)
                && authzFilterConfigBean.getManageEnrollments().contains(pageName)) {
            isAuthorized = true;
        } else if (authz.isViewOwnSectionsAllowed(userUid, siteContext)
                && authzFilterConfigBean.getViewOwnSections().contains(pageName)) {
            isAuthorized = true;
        } else if (pageName.contains("closed")) {
            isAuthorized = true;
        }

        // SAK-13408 - This fix addresses the problem of the filter receiving a blank field on WebSphere.
        // Without this, users would be denied access to the tool
        if ("websphere".equals(ServerConfigurationService.getString("servlet.container"))
                && (isAuthorized || pageName.equals(""))) {
            chain.doFilter(request, response);
        } else if (!"websphere".equals(ServerConfigurationService.getString("servlet.container"))
                && isAuthorized) {
            chain.doFilter(request, response);
        } else {
            logger.error("AUTHORIZATION FAILURE: User " + userUid + " in site " + siteContext
                    + " attempted to reach URL " + request.getRequestURL());
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        if (selectSiteRedirect != null) {
            ((HttpServletResponse) response).sendRedirect(selectSiteRedirect);
        } else {
            ((HttpServletResponse) response).sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    }
}

From source file:com.cloudera.alfredo.server.TestKerberosAuthenticationHandler.java

public void testRequestWithAuthorization() throws Exception {
    String token = KerberosTestUtils.doAsClient(new Callable<String>() {
        @Override//from w w  w.  j a v a 2s.  c o m
        public String call() throws Exception {
            GSSManager gssManager = GSSManager.getInstance();
            GSSContext gssContext = null;
            try {
                String servicePrincipal = KerberosTestUtils.getServerPrincipal();
                GSSName serviceName = gssManager.createName(servicePrincipal, GSSUtil.NT_GSS_KRB5_PRINCIPAL);
                gssContext = gssManager.createContext(serviceName, GSSUtil.GSS_KRB5_MECH_OID, null,
                        GSSContext.DEFAULT_LIFETIME);
                gssContext.requestCredDeleg(true);
                gssContext.requestMutualAuth(true);

                byte[] inToken = new byte[0];
                byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
                Base64 base64 = new Base64(0);
                return base64.encodeToString(outToken);

            } finally {
                if (gssContext != null) {
                    gssContext.dispose();
                }
            }
        }
    });

    HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
    HttpServletResponse response = Mockito.mock(HttpServletResponse.class);

    Mockito.when(request.getHeader(KerberosAuthenticator.AUTHORIZATION))
            .thenReturn(KerberosAuthenticator.NEGOTIATE + " " + token);

    AuthenticationToken authToken = handler.authenticate(request, response);

    if (authToken != null) {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_OK);

        assertEquals(KerberosTestUtils.getClientPrincipal(), authToken.getName());
        assertTrue(KerberosTestUtils.getClientPrincipal().startsWith(authToken.getUserName()));
        assertEquals(KerberosAuthenticationHandler.TYPE, authToken.getType());
    } else {
        Mockito.verify(response).setHeader(Mockito.eq(KerberosAuthenticator.WWW_AUTHENTICATE),
                Mockito.matches(KerberosAuthenticator.NEGOTIATE + " .*"));
        Mockito.verify(response).setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:com.krawler.svnwebclient.authorization.impl.CredentialsManager.java

protected void forceCredentialsRequest(HttpServletRequest request, HttpServletResponse response) {
    request.getSession().setAttribute(CredentialsManager.CREDENTIALS, null);
    request.getSession().setAttribute(SystemInitializing.ID, null);
    try {/* ww  w.j a  va 2  s. c  o  m*/
        if (ConfigurationProvider.getInstance().isBasicAuth()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.setHeader("WWW-Authenticate",
                    "BASIC realm=\"" + ConfigurationProvider.getInstance().getBasicRealm() + "\"");
            response.sendError(401);
        } else {
            RequestDispatcher dispatcher = request.getRequestDispatcher(Links.LOGIN);
            dispatcher.forward(request, response);
        }
    } catch (Exception e) {
        Logger.getLogger(this.getClass()).error(e, e);
    }
}

From source file:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.POST, value = "/itinerary")
public @ResponseBody BasicItinerary saveItinerary(HttpServletResponse response,
        @RequestBody(required = false) BasicItinerary itinerary) throws Exception {
    try {/*w w w  .j  ava2 s.  c  om*/
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

        statLogger.log(itinerary, userId);

        String clientId = itinerary.getClientId();

        if (clientId == null) {
            clientId = new ObjectId().toString();
        } else {
            Map<String, Object> pars = new TreeMap<String, Object>();
            pars.put("clientId", clientId);
            ItineraryObject res = domainStorage.searchDomainObject(pars, ItineraryObject.class);

            if (res != null && !userId.equals(res.getUserId())) {
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return null;
            }
        }

        ItineraryObject io = new ItineraryObject();

        io.setClientId(clientId);
        io.setUserId(userId);
        io.setOriginalFrom(itinerary.getOriginalFrom());
        io.setOriginalTo(itinerary.getOriginalTo());
        io.setName(itinerary.getName());
        io.setData(itinerary.getData());
        if (itinerary.getAppId() == null || itinerary.getAppId().isEmpty()) {
            io.setAppId(NotificationHelper.MS_APP);
        } else {
            io.setAppId(itinerary.getAppId());
        }
        io.setRecurrency(itinerary.getRecurrency());

        domainStorage.saveItinerary(io);

        SavedTrip st = new SavedTrip(new Date(), io, RequestMethod.POST.toString());
        domainStorage.saveSavedTrips(st);

        itinerary.setClientId(clientId);
        return itinerary;
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}