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:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/chat/get", produces = "application/json")
public List<Message> serviceChatGet(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        int numberMessage = Integer.parseInt(request.getParameter("numberMessage"));

        if (LOG.isInfoEnabled()) {
            LOG.info("user get messages. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/chat/get");
        }/*from w w  w .  j a  v  a 2  s. c o  m*/

        return serviceChat.getMessageMiss(numberMessage);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/chat/get");
        }
    }

    return new ArrayList<>();
}

From source file:eu.freme.broker.security.SecurityConfig.java

@Bean
public AuthenticationEntryPoint unauthorizedEntryPoint() {
    return new AuthenticationEntryPoint() {

        @Override//  w ww. j a va  2s  . c om
        public void commence(HttpServletRequest request, HttpServletResponse response,
                AuthenticationException authException) throws IOException, ServletException {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    };
}

From source file:org.apache.archiva.redback.integration.filter.authentication.digest.HttpDigestAuthentication.java

/**
 * Issue HTTP Digest Authentication Challenge
 *
 * @param request   the request to use./*  www  .  j  a v  a  2  s.  c  o  m*/
 * @param response  the response to use.
 * @param realmName the realm name to state.
 * @param exception the exception to base the message off of.
 * @throws IOException if there was a problem with the {@link HttpServletResponse#sendError(int, String)} call.
 */
public void challenge(HttpServletRequest request, HttpServletResponse response, String realmName,
        AuthenticationException exception) throws IOException {
    // The Challenge Header
    StringBuilder authHeader = new StringBuilder();
    authHeader.append("Digest ");
    // [REQUIRED] The name to appear in the dialog box to the user.
    authHeader.append("realm=\"").append(realmName).append("\"");
    // [OPTIONAL] We do not use the optional 'domain' header.
    // authHeader.append( "domain=\"" ).append( domain ).append( "\"" );
    // [REQUIRED] Nonce specification.
    authHeader.append(", nonce=\"");
    long timestamp = System.currentTimeMillis() + (nonceLifetimeSeconds * 1000);
    // Not using ETag from RFC 2617 intentionally.
    String hraw = String.valueOf(timestamp) + ":" + digestKey;
    String rawnonce = String.valueOf(timestamp) + ":" + Digest.md5Hex(hraw);
    authHeader.append(Base64.encodeBase64(rawnonce.getBytes()));
    authHeader.append("\"");
    // [REQUIRED] The RFC 2617 Quality of Protection.
    // MSIE Appears to only support 'auth'
    // Do not use 'opaque' here. (Your MSIE users will have issues)
    authHeader.append(", qop=\"auth\"");
    // [BROKEN] since we force the 'auth' qop we cannot use the opaque option.
    // authHeader.append( ", opaque=\"").append(opaqueString).append("\"");

    // [OPTIONAL] Use of the stale option is reserved for expired nonce strings.
    if (exception instanceof NonceExpirationException) {
        authHeader.append(", stale=\"true\"");
    }

    // [OPTIONAL] We do not use the optional Algorithm header.
    // authHeader.append( ", algorithm=\"MD5\"");

    response.addHeader("WWW-Authenticate", authHeader.toString());
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
}

From source file:com.google.gsa.valve.modules.krb.KerberosAuthorizationProcess.java

/**
 * // ww  w .ja  va  2s  .co m
 * This is the main method that does the authorization and should be 
 * invoked by the classes that would like to check if the user is 
 * priviledged to access to the document (url) against the Kerberized 
 * protected source that serves it.
 * <p>
 * The Kerberos user ticket is read from the credentials sent in the 
 * setCredentials() method. The default Kerberos credential, where the 
 * ticket is recovered, is "krb5".
 * <p>
 * If it is a HEAD request, it means it's not necessary to get the content, 
 * and that's why this process only cares about the HTTP result code. That 
 * result code is returned back to the caller, and if the request is not a 
 * HEAD (i.e. usually GET), the content is sent as well if the overall 
 * result is OK.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param responseCookies vector that contains the authentication cookies
 * @param url the document url
 * @param id the default credential id
 * 
 * @return the HTTP error code
 * 
 * @throws HttpException
 * @throws IOException
 */
public int authorize(HttpServletRequest request, HttpServletResponse response, Cookie[] responseCookies,
        String url, String id) throws HttpException, IOException {

    logger.debug("Krb Authorization");

    String loginUrl = null;

    loginUrl = valveConf.getLoginUrl();

    maxConnectionsPerHost = (new Integer(valveConf.getMaxConnectionsPerHost())).intValue();
    maxTotalConnections = (new Integer(valveConf.getMaxTotalConnections())).intValue();

    logger.debug("KrbAuthZ maxConnectionsPerHost: " + maxConnectionsPerHost);
    logger.debug("KrbAuthZ maxTotalConnections: " + maxTotalConnections);

    // Protection
    if (webProcessor == null) {
        // Instantiate Web processor
        if ((maxConnectionsPerHost != -1) && (maxTotalConnections != -1)) {
            webProcessor = new WebProcessor(maxConnectionsPerHost, maxTotalConnections);
        } else {
            webProcessor = new WebProcessor();
        }
    }

    //
    // Launch the authorization process
    //

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

    //set credentials
    if (creds != null) {
        logger.debug("creds is not null");
        if (creds.getCredential(KRB5_ID) != null) {
            credentials = new Krb5Credentials(valveConf.getKrbConfig().getKrbconfig(),
                    valveConf.getKrbConfig().getKrbini(), creds.getCredential(KRB5_ID).getSubject());
        }
    }

    if (credentials == null) {

        // no authZ header, can't auth this URL
        logger.debug("No Kerberos credentials");
        return statusCode;

    } else {

        boolean isHead = AuthorizationUtils.isHead(request, valveConf);
        logger.debug("isHead?: " + isHead);
        setHeaders();

        // Protection
        if (webProcessor != null) {

            // Protection
            try {
                // Process authz request
                String requestType = RequestType.GET_REQUEST;

                if (isHead) {
                    requestType = RequestType.HEAD_REQUEST;
                }

                method = webProcessor.sendRequest(credentials, requestType, headers, null, url);

                // Protection
                if (method != null) {
                    // Cache status code
                    statusCode = method.getStatusCode();
                    logger.debug("statusCode is.... " + statusCode);

                    if (statusCode == HttpServletResponse.SC_OK) {
                        //check if it's a Head request
                        if (!isHead) {
                            //call HTTPAuthZProcessor
                            HTTPAuthZProcessor.processResponse(response, method, url, loginUrl);
                        }
                    } else {

                        logger.debug("not AuthZ : should return response Code");
                    }
                }

                // Garbagge collect
                if (method != null) {
                    method.releaseConnection();
                    method = null;
                }

            } catch (Exception e) {
                // Log error
                logger.error("authorization failure: " + e.getMessage(), e);
                statusCode = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;

                // Garbagge collect
                logger.debug("Let's release the connection");
                method.releaseConnection();
                method = null;
            }

        }

        //
        // End of the authorization process
        //

        // Return status code
        return statusCode;
    }

}

From source file:org.dataconservancy.ui.api.ProjectController.java

/**
 * Handles get request with an id, this returns the serialized project
 * identified by the id. Partially implemented.
 * //  ww  w.ja  va 2s  .  co m
 * @param idpart
 * @param mimeType
 * @param modifiedSince
 * @param request
 * @throws BizPolicyException
 */
@RequestMapping(value = "/{idpart}", method = { RequestMethod.GET })
public void handleProjectGetRequest(@PathVariable String idpart,
        @RequestHeader(value = "Accept", required = false) String mimeType,
        @RequestHeader(value = "If-Modified-Since", required = false) @DateTimeFormat(iso = DATE_TIME) Date modifiedSince,
        HttpServletRequest request, HttpServletResponse resp) throws IOException, BizPolicyException {

    Person user = getAuthenticatedUser();
    if (user == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;
    } else {
        String id = util.buildRequestUrl(request);

        Project project = projectBizService.getProject(id, user);

        if (project == null) {
            resp.setStatus(HttpStatus.SC_NOT_FOUND);
        } else {
            if (authorizationService.canReadProject(user, project)) {
                Bop bop = new Bop();
                bop.addProject(project);
                resp.setContentType("text/xml");
                objectBuilder.buildBusinessObjectPackage(bop, resp.getOutputStream());
            } else {
                resp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            }
        }
    }
}

From source file:fr.paris.lutece.plugins.rest.service.LuteceJerseySpringServlet.java

/**
 * Checks if the request is authenticated. Sets {@link HttpServletResponse#SC_UNAUTHORIZED} if not,
 * calls {@link ServletContainer#doFilter(HttpServletRequest, HttpServletResponse, FilterChain)} otherwise.
 * @param request the HTTP request/*  ww w .  ja  va2s  .  c  o  m*/
 * @param response the response
 * @param chain the filter chain
 * @throws IOException exception if I/O error
 * @throws ServletException exception if servlet error
 */
@Override
public void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    if (checkRequestAuthentification(request)) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("LuteceJerseySpringServlet processing request : " + request.getMethod() + " "
                    + request.getContextPath() + request.getServletPath());
        }
        super.doFilter(request, response, chain);
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.appverse.web.framework.backend.frontfacade.rest.authentication.filter.JWSAuthenticationProcessFilterTest.java

@Test
public void testJWSAuthenticationFilterFailNoHeader() throws Exception {

    ArgumentCaptor<Integer> errorCode = ArgumentCaptor.forClass(Integer.class);
    when(request.getHeader(JWSAuthenticationProcessingFilter.JWS_AUTH_HEADER)).thenReturn(null);
    //test//w  ww  . jav a  2s .c o m
    myJWSFilter.doFilter(request, response, chain);
    //verification
    verify(response, times(1)).sendError(errorCode.capture());
    int errorCodeValue = errorCode.getValue().intValue();
    logger.info("Response error:{}", errorCodeValue);
    Assert.assertEquals("sendError should be:", HttpServletResponse.SC_UNAUTHORIZED, errorCodeValue);
    verify(chain, times(0)).doFilter(any(ServletRequest.class), any(ServletResponse.class));

}

From source file:com.example.ManualSpnegoNegotiateServlet.java

/**
 * Use of Kerberos is wrapped in an HTTP auth-scheme of "Negotiate" [RFC 4559].
 *
 * The auth-params exchanged use data formats defined for use with the GSS-API [RFC 2743]. In particular, they follow the formats set for the SPNEGO [RFC 4178] and
 * Kerberos [RFC 4121] mechanisms for GSSAPI. The "Negotiate" auth-scheme calls for the use of SPNEGO GSSAPI tokens that the specific mechanism type specifies.
 *
 * The current implementation of this protocol is limited to the use of SPNEGO with the Kerberos protocol.
 *
 * @param request/*from   w ww.  j a  v  a 2  s  . c om*/
 * @param response
 * @throws ServletException
 *
 * @return true upon successful authentication, false otherwise
 */
protected boolean attemptNegotiation(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, UnsupportedEncodingException, IOException {
    log.debug("Attempting negotiation.");

    String header = request.getHeader("Authorization");

    /**
     * Guard clause to check for Negotiate header.
     *
     * If the server receives a request for an access-protected object, and if an acceptable Authorization header has not been sent, the server responds with a "401
     * Unauthorized" status code, and a "WWW-Authenticate:" header as per the framework described in [RFC 2616]. The initial WWW-Authenticate header will not carry
     * any gssapi-data.
     */
    if (header == null || header.length() < 10 || !header.startsWith("Negotiate ")) {
        response.setHeader("WWW-Authenticate", "Negotiate");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        log.debug("Proper authorization header not found, returning challenge.");
        return false;
    }

    /**
     * A client may initiate a connection to the server with an "Authorization" header containing the initial token for the server. This form will bypass the initial
     * 401 error from the server when the client knows that the server will accept the Negotiate HTTP authentication type.
     */
    log.debug("Authorization header found, continuing negotiation.");

    /**
     * The data following the word Negotiate is the GSS-API data to process.
     */
    byte gssapiData[] = Base64.decode(header.substring(10));

    log.debug("GSS API data: " + Arrays.toString(gssapiData));

    /**
     * Guard clause to check for the unsupported NTLM authentication mechanism.
     */
    if (isNtlmMechanism(gssapiData)) {
        log.warn("Got request for unsupported NTLM mechanism, aborting negotiation.");
        return false;
    }

    /**
     * The server attempts to establish a security context. Establishment may result in tokens that the server must return to the client. Tokens are BASE-64 encoded
     * GSS-API data.
     */
    GSSContext gssContext = null;
    LoginContext loginContext = null;
    String outToken = null;

    try {
        final String domainUsername = "Zeus";
        final String domainUserPassword = "Z3usP@55";
        final CallbackHandler handler = SpnegoProvider.getUsernamePasswordHandler(domainUsername,
                domainUserPassword);

        loginContext = new LoginContext("spnego-server", handler);
        loginContext.login();
        Subject subject = loginContext.getSubject();

        Oid spnegoOid = new Oid("1.3.6.1.5.5.2"); // for spnego answers
        Oid kerbv5Oid = new Oid("1.2.840.113554.1.2.2"); // for chromium (they send a kerbv5 token instead of spnego)
        final Oid[] oids = new Oid[] { spnegoOid, kerbv5Oid };

        final GSSManager manager = GSSManager.getInstance();
        final PrivilegedExceptionAction<GSSCredential> action = new PrivilegedExceptionAction<GSSCredential>() {
            public GSSCredential run() throws GSSException {
                return manager.createCredential(null, GSSCredential.INDEFINITE_LIFETIME, oids,
                        GSSCredential.ACCEPT_ONLY);
            }
        };

        GSSCredential serverCreds = Subject.doAs(subject, action);

        log.debug("Mechs: " + Arrays.toString(serverCreds.getMechs()));

        gssContext = manager.createContext(serverCreds);

        log.debug("Context created. " + gssContext);

        byte tokenBytes[] = gssContext.acceptSecContext(gssapiData, 0, gssapiData.length);
        outToken = Base64.encode(tokenBytes);
    } catch (PrivilegedActionException ex) {
        log.error("", ex);
    } catch (LoginException ex) {
        log.error("", ex);
    } catch (GSSException gsse) {
        gsse.printStackTrace();
        log.error("GSSException:       " + gsse.getMessage());
        log.error("GSSException major: " + gsse.getMajorString());
        log.error("GSSException minor: " + gsse.getMinorString());
        throw new ServletException(gsse);
    }

    /**
     * If the context is established, we can attempt to retrieve the name of the "context initiator." In the case of the Kerberos mechanism, the context initiator is
     * the Kerberos principal of the client. Additionally, the client may be delegating credentials.
     */
    if (gssContext != null && gssContext.isEstablished()) {
        log.debug("Context established, attempting Kerberos principal retrieval.");

        try {
            Subject subject = new Subject();
            GSSName clientGSSName = gssContext.getSrcName();
            KerberosPrincipal clientPrincipal = new KerberosPrincipal(clientGSSName.toString());
            subject.getPrincipals().add(clientPrincipal);
            log.info("Got client Kerberos principal: " + clientGSSName);
            response.getWriter().println("Hello, " + clientPrincipal);

            /**
             * Retrieve LogonInfo (for example, GroupSIDs) from the PAC Authorization Data
             * from a Kerberos Ticket that was issued by Active Directory.
             */
            byte[] kerberosTokenData = gssapiData;
            try {
                SpnegoToken token = SpnegoToken.parse(gssapiData);
                kerberosTokenData = token.getMechanismToken();
            } catch (DecodingException dex) {
                // Chromium bug: sends a Kerberos response instead of an spnego response with a Kerberos mechanism
            } catch (Exception ex) {
                log.error("", ex);
            }

            try {
                Object[] keyObjs = IteratorUtils
                        .toArray(loginContext.getSubject().getPrivateCredentials(KerberosKey.class).iterator());
                KerberosKey[] keys = new KerberosKey[keyObjs.length];
                System.arraycopy(keyObjs, 0, keys, 0, keyObjs.length);

                KerberosToken token = new KerberosToken(kerberosTokenData, keys);
                log.info("Authorizations: ");
                for (KerberosAuthData authData : token.getTicket().getEncData().getUserAuthorizations()) {
                    if (authData instanceof KerberosPacAuthData) {
                        PacSid[] groupSIDs = ((KerberosPacAuthData) authData).getPac().getLogonInfo()
                                .getGroupSids();
                        log.info("GroupSids: " + Arrays.toString(groupSIDs));
                        response.getWriter().println("Found group SIDs: " + Arrays.toString(groupSIDs));
                    } else {
                        log.info("AuthData without PAC: " + authData.toString());
                    }
                }
            } catch (Exception ex) {
                log.error("", ex);
            }

            if (gssContext.getCredDelegState()) {
                GSSCredential delegateCredential = gssContext.getDelegCred();
                GSSName delegateGSSName = delegateCredential.getName();
                Principal delegatePrincipal = new KerberosPrincipal(delegateGSSName.toString());
                subject.getPrincipals().add(delegatePrincipal);
                subject.getPrivateCredentials().add(delegateCredential);
                log.info("Got delegated Kerberos principal: " + delegateGSSName);
            }

            /**
             * A status code 200 status response can also carry a "WWW-Authenticate" response header containing the final leg of an authentication. In this case, the
             * gssapi-data will be present.
             */
            if (outToken != null && outToken.length() > 0) {
                response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
                response.setStatus(HttpServletResponse.SC_OK);
                log.debug("Returning final authentication data to client to complete context.");
                log.debug("Negotiation completed.");
                return true;
            }
        } catch (GSSException gsse) {
            log.error("GSSException:       " + gsse.getMessage());
            log.error("GSSException major: " + gsse.getMajorString());
            log.error("GSSException minor: " + gsse.getMinorString());

            response.addHeader("Client-Warning", gsse.getMessage());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } else {
        /**
         * Any returned code other than a success 2xx code represents an authentication error. If a 401 containing a "WWW-Authenticate" header with "Negotiate" and
         * gssapi-data is returned from the server, it is a continuation of the authentication request.
         */
        if (outToken != null && outToken.length() > 0) {
            response.setHeader("WWW-Authenticate", "Negotiate " + outToken.getBytes());
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.debug("Additional authentication processing required, returning token.");
            return false;
        } else {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            log.warn("Kerberos negotiation failed.");
        }
    }

    log.debug("Negotiation completed.");

    return true;
}

From source file:io.fabric8.apiman.BearerTokenFilter.java

/**
 * Sends a response that tells the client that authentication is required.
 * //  w w  w .  java 2  s . co m
 * @param response
 *            the response
 * @throws IOException
 *             when an error cannot be sent
 */
private void sendInvalidTokenResponse(HttpServletResponse response, String errMsg) throws IOException {

    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, errMsg);
}

From source file:com.tasktop.c2c.server.webdav.server.SpringAwareWebdavServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    ITransaction transaction = null;/* w w w .  j  av a2 s. c  om*/
    boolean needRollback = false;

    try {
        Principal userPrincipal = req.getUserPrincipal();
        transaction = webdavStore.begin(userPrincipal);
        needRollback = true;
        webdavStore.checkAuthentication(transaction);

        IMethodExecutor methodExecutor = methodMap.get(req.getMethod());
        if (methodExecutor == null) {
            methodExecutor = methodMap.get("*NO*IMPL*");
        }

        methodExecutor.execute(transaction, req, resp);

        webdavStore.commit(transaction);
        needRollback = false;

    } catch (UnauthenticatedException e) {
        resp.sendError(WebdavStatus.SC_UNAUTHORIZED);
    } catch (AccessDeniedException ade) {

        // If we got a security exception, determine the correct type of error code to return.
        AuthenticationToken token = AuthenticationServiceUser.getCurrent().getToken();
        List<String> roles = token.getAuthorities();

        // Our request was rejected - time to send back an appropriate error.
        if (roles.contains(Role.Anonymous)) {
            // This was an anonymous request, so prompt the user for credentials - perhaps they can still do this.
            resp.addHeader("WWW-Authenticate",
                    String.format("Basic realm=\"%s\"", TenancyUtil.getCurrentTenantProjectIdentifer()));
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Please login to continue");
        } else {
            // This user was authenticated, but this request is not allowed for permissions reasons - reject it.
            resp.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "Insufficient permissions to perform this WebDav request");
        }
    } catch (Exception e) {
        LOG.error(e);
        resp.sendError(WebdavStatus.SC_INTERNAL_SERVER_ERROR);
        throw new ServletException(e);
    } finally {
        if (needRollback) {
            webdavStore.rollback(transaction);
        }
    }
}