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:eu.trentorise.smartcampus.mobility.controller.rest.JourneyPlannerController.java

@RequestMapping(method = RequestMethod.PUT, value = "/itinerary/{itineraryId}")
public @ResponseBody Boolean updateItinerary(HttpServletResponse response,
        @RequestBody(required = false) BasicItinerary itinerary, @PathVariable String itineraryId)
        throws Exception {
    try {/*from   ww  w  .jav a2s. com*/
        String userId = getUserId();
        if (userId == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return null;
        }

        String objectClientId = itinerary.getClientId();
        if (!itineraryId.equals(objectClientId)) {
            response.setStatus(HttpServletResponse.SC_CONFLICT);
            return null;
        }

        Map<String, Object> pars = new TreeMap<String, Object>();
        pars.put("clientId", itineraryId);

        ItineraryObject res = domainStorage.searchDomainObject(pars, ItineraryObject.class);

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

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

            domainStorage.saveItinerary(res);

            SavedTrip st = new SavedTrip(new Date(), res, RequestMethod.PUT.toString());
            domainStorage.saveSavedTrips(st);

            return true;
        } else {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
        }
    } catch (Exception e) {
        e.printStackTrace();
        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
    }
    return null;
}

From source file:cz.fi.muni.xkremser.editor.server.AuthenticationServlet.java

private void requrireAuthentication(HttpServletResponse resp) throws IOException {
    resp.setHeader("WWW-Authenticate", "BASIC realm=\"users\"");
    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

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

@RequestMapping(value = "/service/dispatcher/getflights", produces = "application/json")
public List<NodeDisctributor> serviceDispatcherGetFlights(HttpServletRequest request,
        HttpServletResponse response) {//w  ww  .j a  va2  s  .  c o  m
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (serviceUsers.checkUserOnline(user)) {
        List<NodeDisctributor> list = serviceDistributor.getActualInformation(user);

        if (LOG.isInfoEnabled()) {
            LOG.info("user get flight. Session id : " + httpSession.getId() + ". User : " + user
                    + ". URL : /service/dispatcher/getflights");
        }

        return list;
    } else {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

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

    return new ArrayList<>();
}

From source file:com.ucap.uccc.cmis.impl.atompub.CmisAtomPubServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    CallContext context = null;//  w ww.ja v a  2  s . c  o m
    try {
        if (METHOD_HEAD.equals(request.getMethod())) {
            request = new HEADHttpServletRequestWrapper(request);
            response = new NoBodyHttpServletResponseWrapper(response);
        } else {
            request = new QueryStringHttpServletRequestWrapper(request);
        }

        // set default headers
        response.addHeader("Cache-Control", "private, max-age=0");
        response.addHeader("Server", ServerVersion.OPENCMIS_SERVER);

        context = createContext(getServletContext(), request, response);
        dispatch(context, request, response);
    } catch (Exception e) {
        if (e instanceof CmisUnauthorizedException) {
            response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
        } else if (e instanceof CmisPermissionDeniedException) {
            if ((context == null) || (context.getUsername() == null)) {
                response.setHeader("WWW-Authenticate", "Basic realm=\"CMIS\"");
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authorization Required");
            } else {
                response.sendError(getErrorCode((CmisPermissionDeniedException) e), e.getMessage());
            }
        } else {
            printError(e, response);
        }
    } finally {
        // we are done.
        response.flushBuffer();
    }
}

From source file:com.haulmont.cuba.restapi.DataServiceController.java

@RequestMapping(value = "/api/query", method = RequestMethod.POST)
public void queryByPost(@RequestParam(value = "s") String sessionId,
        @RequestHeader(value = "Content-Type") MimeType contentType, @RequestBody String requestContent,
        HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (!authentication.begin(sessionId)) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;/*from w  w w .j  a v a2s .  com*/
    }

    try {
        Converter converter = conversionFactory.getConverter(contentType);

        QueryRequest queryRequest = converter.parseQueryRequest(requestContent);

        MetaClass metaClass = metadata.getClass(queryRequest.getEntity());
        if (metaClass == null) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST,
                    "Persistent entity " + queryRequest.getEntity() + " does not exist");
            return;
        }

        if (!entityOpPermitted(metaClass, EntityOp.READ)) {
            response.sendError(HttpServletResponse.SC_FORBIDDEN);
            return;
        }

        LoadContext loadCtx = new LoadContext(metaClass);
        loadCtx.setLoadDynamicAttributes(Boolean.TRUE.equals(queryRequest.loadDynamicAttributes()));
        LoadContext.Query query = new LoadContext.Query(queryRequest.getQuery());

        for (String key : queryRequest.getParams().keySet()) {
            query.setParameter(key, queryRequest.getParams().get(key));
        }

        loadCtx.setQuery(query);
        if (queryRequest.getFirst() != null)
            query.setFirstResult(queryRequest.getFirst());
        if (queryRequest.getMax() != null)
            query.setMaxResults(queryRequest.getMax());

        if (queryRequest.getViewName() == null) {
            View view = metadata.getViewRepository().getView(metaClass, View.LOCAL);
            loadCtx.setView(new View(view, "local-with-system-props", true));
        } else {
            loadCtx.setView(queryRequest.getViewName());
        }
        List<Entity> entities = dataService.loadList(loadCtx);
        String result = converter.process(entities, metaClass, loadCtx.getView());
        writeResponse(response, result, converter.getMimeType());
    } catch (RowLevelSecurityException e) {
        response.sendError(HttpServletResponse.SC_FORBIDDEN,
                "The operation with entity " + e.getEntity() + " is denied");
    } catch (Throwable e) {
        sendError(request, response, e);
    } finally {
        authentication.end();
    }
}

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

@Test
public void testSecureResourceWithBadAuthToken() throws IOException, Exception {
    mockMvc.perform(get(RequestPath.TEST_SECURE_REQUEST).header(HttpCustomHeaders.AUTH_TOKEN_HEADER.getHeader(),
            BAD_TOKEN)).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_BAD_TOKEN.name())));
}

From source file:com.xwiki.authentication.ntlm.NTLMAuthServiceImpl.java

public NtlmPasswordAuthentication resolveNTLM(XWikiContext context) {
    NtlmPasswordAuthentication ntlm = null;

    UniAddress dc;// w w  w . j  a  va  2s .c  om
    String domainController = getConfig().getParam("domainController", context);
    String defaultDomain = getConfig().getParam("defaultDomain", context);

    String msg = context.getRequest().getHeader("Authorization");
    try {
        if (msg != null && (msg.startsWith("NTLM ") || msg.startsWith("Basic "))) {
            LOG.debug("Auth type: " + msg);
            LOG.debug("domainController: " + domainController);
            dc = UniAddress.getByName(domainController, true);
            if (msg.startsWith("NTLM ")) {
                byte[] challenge = SmbSession.getChallenge(dc);
                byte[] src = Base64.decode(msg.substring(5));
                if (src[8] == 1) {
                    LOG.debug("phase 1");
                    Type1Message type1 = new Type1Message(src);
                    Type2Message type2 = new Type2Message(type1, challenge, null);
                    msg = Base64.encode(type2.toByteArray());
                    LOG.debug("message1 supplied domain: " + type1.getSuppliedDomain());
                    LOG.debug("message1 supplied workstation: " + type1.getSuppliedWorkstation());
                    context.getResponse().setHeader("WWW-Authenticate", "NTLM " + msg);
                    context.getResponse().setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                    context.getResponse().flushBuffer();
                } else if (src[8] == 3) {
                    LOG.debug("phase 2");
                    Type3Message type3 = new Type3Message(src);
                    LOG.debug("message3 domain: " + type3.getDomain());
                    LOG.debug("message3 user: " + type3.getUser());
                    LOG.debug("message3 workstation: " + type3.getWorkstation());
                    byte[] lmResponse = type3.getLMResponse();
                    if (lmResponse == null)
                        lmResponse = new byte[0];
                    byte[] ntResponse = type3.getNTResponse();
                    if (ntResponse == null)
                        ntResponse = new byte[0];
                    ntlm = new NtlmPasswordAuthentication(type3.getDomain(), type3.getUser(), challenge,
                            lmResponse, ntResponse);
                }
            } else {
                LOG.debug("Basic session");
                String auth = new String(Base64.decode(msg.substring(6)), "US-ASCII");
                int index = auth.indexOf(':');
                String user = (index != -1) ? auth.substring(0, index) : auth;
                String pass = (index != -1) ? auth.substring(index + 1) : "";
                index = user.indexOf('\\');
                if (index == -1)
                    index = user.indexOf('/');
                String domain = (index != -1) ? user.substring(0, index) : defaultDomain;
                user = (index != -1) ? user.substring(index + 1) : user;
                ntlm = new NtlmPasswordAuthentication(domain, user, pass);
            }

            if (ntlm != null && "1".equals(getConfig().getParam("validate", "1", context))) {
                try {
                    SmbSession.logon(dc, ntlm);
                } catch (SmbAuthException sae) {
                    LOG.debug("Can't logon");

                    return null;
                }
            }
        } else {
            LOG.debug("No auth type");
            showLogin(context);
        }
    } catch (Exception e) {
        LOG.debug("Got exception: ", e);
    }

    return ntlm;
}

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

/**
 * If the request contains a JWT header, the user will be logged in for this request using the token.
 * <p>//from ww  w.j ava 2 s.  com
 * 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
 */
public HttpServletRequest attemptJwtAuthLogin(HttpServletRequest request, HttpServletResponse response) {
    try {
        // Get the JWT token from the header
        String jwt = getAuthHeaderToken(request, JWT_TOKEN);

        if (jwt != null) {
            // Parse and verify the JWT token
            JWTService.ParsedJWTInfo jwtInfo = jwtService.parseSignedJWT(jwt);

            // Check if the bearer token has expired
            Date now = new Date();
            if (now.after(jwtInfo.getExpirationTime())) {
                request.setAttribute(AUTH_ERROR_ATTR, 419); // 419: session timed out
                log.warn("JWT token expired for user " + jwtInfo.getSubject());
                return request;
            }

            // Before logging in, generate a one-time password token tied to the current thread.
            // This is verified in the JbossLoginModule
            String tempPwd = jwtService.issueTempJwtPwdToken(JbossLoginModule.BEARER_TOKEN_LOGIN);
            request = SecurityUtils.login(userService, request, jwtInfo.getSubject(), tempPwd);
            log.trace("Found JWT user " + request.getUserPrincipal().getName());

            // After a configurable amount of minutes, a new JWT token will automatically be
            // issued and sent back to the client.
            // This will allow the client to implement inactivity timeout instead of relying on
            // the fixed expiration date of the JWT token.
            if (jwtService.reauthJWT(jwtInfo)) {
                log.info("New JWT token issued for re-authorization of user " + jwtInfo.getSubject());
                JWTToken reAuthJwt = jwtService.createSignedJWT(getJwtIssuer(request),
                        (User) request.getUserPrincipal());
                response.setHeader("Reauthorization", reAuthJwt.getToken());
            }
        }
    } catch (Exception ex) {
        request.setAttribute(AUTH_ERROR_ATTR, HttpServletResponse.SC_UNAUTHORIZED);
        log.warn("Failed logging in using bearer token");
    }
    return request;
}