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.kurento.kmf.jsonrpcconnector.internal.server.config.OAuthFiWareFilter.java

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

    String fullUrl = request.getRequestURL().append('?').append(request.getQueryString()).toString();

    log.info("Client trying to stablish new websocket session with {}", fullUrl);

    if (!Strings.isNullOrEmpty(props.getKeystoneHost())) {
        String accessToken = parseAccessToken(request);
        if (Strings.isNullOrEmpty(accessToken)) {
            log.warn("Request from {} without OAuth token", request.getRemoteAddr());
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Access token not found in request");
        } else if (isTokenValid(accessToken)) {
            log.info("The request from {} was authorized", request.getRemoteAddr());
            filterChain.doFilter(request, response);
        } else {// w  ww . j  a  v  a  2  s .c  o m
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unathorized request");
        }
    } else {
        log.info("Request from {} authorized: no keystone host configured", request.getRemoteAddr());
        filterChain.doFilter(request, response);
    }
}

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

@RequestMapping(method = RequestMethod.GET)
public void searchLocation(@RequestParam(required = false, value = "username") String username,
        @RequestParam(required = false, value = "password") String password,
        @RequestParam(required = false, value = "term") String term, HttpServletResponse response)
        throws IOException {
    try {/*from   w  w  w  . j  ava2  s .  co m*/
        if (!Context.isAuthenticated())
            Context.authenticate(username, password);
        // search the locations with matching the search term
        List<Location> locations = Context.getLocationService().getLocations(term);
        // serialize the locations
        XStream xStream = new XStream();
        xStream.alias("results", List.class);
        xStream.alias("location", Location.class);
        xStream.registerConverter(new LocationConverter());
        xStream.toXML(locations, response.getOutputStream());
    } catch (ContextAuthenticationException e) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

From source file:org.apache.cxf.fediz.service.idp.kerberos.KerberosEntryPoint.java

public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex)
        throws IOException, ServletException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("Sending back Negotiate Header for request: " + request.getRequestURL());
    }/*from w w w.j a  va 2 s.  com*/
    response.addHeader("WWW-Authenticate", "Negotiate");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    response.flushBuffer();
}

From source file:com.vmware.identity.samlservice.TestAuthnRequestStateAuthenticationFilter.java

public void preAuthenticate(AuthnRequestState t) throws SamlServiceException {
    log.debug("AuthnRequestStateAuthenticationFilter.preAuthenticate is called");

    Validate.notNull(t);//from  ww w .  j a  v a 2 s .c om
    HttpServletRequest request = t.getRequest();
    Validate.notNull(request);
    if (request.getParameter(REQUEST_AUTH_HEADER) == null) {
        // authentication not possible
        log.debug(REQUEST_AUTH_HEADER + " is missing, requesting " + AUTH_PREFIX);
        t.setWwwAuthenticate(AUTH_PREFIX);
        t.setValidationResult(new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized", null));
        throw new SamlServiceException(REQUEST_AUTH_HEADER + " is missing, requesting " + AUTH_PREFIX);
    }
}

From source file:pdl.web.filter.RestAuthenticationFilter.java

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

    List<String> headerKeys = Arrays.asList(USER_NAME_PARAM, USER_PASS_PARAM);
    Map<String, String> headerAndParms = new HashMap<String, String>();

    // load header values we care about
    Enumeration e = request.getHeaderNames();
    while (e.hasMoreElements()) {
        String key = (String) e.nextElement();

        if (headerKeys.contains(key)) {
            headerAndParms.put(key, request.getHeader(key));
        }//from ww w  .j  av a 2s .  co  m
    }

    // load parameters
    for (Object key : request.getParameterMap().keySet()) {
        String[] o = (String[]) request.getParameterMap().get(key);
        headerAndParms.put((String) key, o[0]);
    }

    String userName = headerAndParms.get(USER_NAME_PARAM);
    String userPasswd = headerAndParms.get(USER_PASS_PARAM);

    if (userName == null || userPasswd == null) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "REST signature failed validation.");
        return;
    }
    /*catch (Exception e) {
      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "The REST Security Server experienced an internal error.");
      return;
      }*/

    filterChain.doFilter(request, response);
}

From source file:grails.plugin.springsecurity.web.authentication.AjaxAwareAuthenticationEntryPoint.java

@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {
    if (StringUtils.equalsIgnoreCase(request.getHeader("nopage"), "true")) {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized: The requested URL is protected");
        return;/*from w w w  . j  a  va 2 s .  c o  m*/
    }
    super.commence(request, response, authException);
}

From source file:co.carlosandresjimenez.gotit.backend.controller.SecurityInterceptor.java

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    String testEnviroment = request.getHeader("Environment");
    if (testEnviroment != null && !testEnviroment.isEmpty() && testEnviroment.equals(TEST_ENVIRONMENT)) {

        request.setAttribute("email", request.getHeader("Email"));

        System.out.println(/*from ww w  .  jav  a 2s  . com*/
                "SecurityInterceptor: Test environment access granted to user " + request.getHeader("Email"));

        return true;
    }

    String accessToken = request.getHeader("Authorization");
    String email;

    if (accessToken != null && accessToken.length() > 7) {
        // Removing 'Bearer ' prefix
        accessToken = accessToken.substring(7);
        email = Utility.validateGoogleToken(accessToken);

        if (email.equals("INVALID")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

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

    request.setAttribute("email", email);
    return true;
}

From source file:com.create.application.configuration.OAuth2Configuration.java

@Bean
public AuthenticationEntryPoint accessForbiddenEntryPoint() {
    return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
}

From source file:jp.or.openid.eiwg.scim.operation.Operation.java

/**
 * ??//from ww  w.j av  a  2 s .c  om
 *
 * @param context 
 * @param request 
 */
public boolean Authentication(ServletContext context, HttpServletRequest request) throws IOException {
    boolean result = false;

    // Authorization?
    String authorization = request.getHeader("Authorization");

    if (authorization == null || StringUtils.isEmpty(authorization)) {
        // 
        setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_UNAUTHORIZED);
        //return false;
        return true;
    }

    String[] values = authorization.split(" ");

    // ?
    setError(0, null, null);

    if (values.length < 2) {
        // 
        setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_UNAUTHORIZED);
    } else {
        // ????????
        if ("Basic".equalsIgnoreCase(values[0])) {
            // HTTP Basic ?
            String userID;
            String password;
            String[] loginInfo = SCIMUtil.decodeBase64(values[1]).split(":");

            if (loginInfo.length < 2) {
                // 
                setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS);
            } else {
                // ??
                userID = loginInfo[0];
                // 
                password = loginInfo[1];

                if (StringUtils.isEmpty(userID) || StringUtils.isEmpty(password)) {
                    // 
                    setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                            MessageConstants.ERROR_INVALID_CREDENTIALS);
                } else {
                    // ????

                    // ???
                    ObjectMapper mapper = new ObjectMapper();
                    ArrayList<LinkedHashMap<String, Object>> adminInfoList = null;
                    try {
                        adminInfoList = mapper.readValue(new File(context.getRealPath("/WEB-INF/Admin.json")),
                                new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() {
                                });
                    } catch (IOException e) {
                        // 
                        setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null,
                                MessageConstants.ERROR_UNKNOWN);
                        e.printStackTrace();
                        return result;
                    }

                    if (adminInfoList != null && !adminInfoList.isEmpty()) {
                        Iterator<LinkedHashMap<String, Object>> adminInfoIt = adminInfoList.iterator();
                        while (adminInfoIt.hasNext()) {
                            LinkedHashMap<String, Object> adminInfo = adminInfoIt.next();
                            Object adminID = SCIMUtil.getAttribute(adminInfo, "id");
                            Object adminPassword = SCIMUtil.getAttribute(adminInfo, "password");
                            // id????
                            if (adminID != null && adminID instanceof String) {
                                if (userID.equals(adminID.toString())) {
                                    // password????
                                    if (adminID != null && adminID instanceof String) {
                                        if (password.equals(adminPassword.toString())) {
                                            // ??
                                            result = true;
                                        }
                                    }

                                    break;
                                }
                            }
                        }

                        if (result != true) {
                            // 
                            setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                                    MessageConstants.ERROR_INVALID_CREDENTIALS);
                        }
                    } else {
                        // 
                        setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                                MessageConstants.ERROR_INVALID_CREDENTIALS);
                    }
                }
            }
        } else if ("Bearer".equalsIgnoreCase(values[0])) {
            // OAuth2 Bearer 
            String token = values[1];

            if (StringUtils.isEmpty(token)) {
                // 
                setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS);
            } else {
                // ??

                // ???
                ObjectMapper mapper = new ObjectMapper();
                ArrayList<LinkedHashMap<String, Object>> adminInfoList = null;
                try {
                    adminInfoList = mapper.readValue(new File(context.getRealPath("/WEB-INF/Admin.json")),
                            new TypeReference<ArrayList<LinkedHashMap<String, Object>>>() {
                            });
                } catch (IOException e) {
                    // 
                    setError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, null,
                            MessageConstants.ERROR_UNKNOWN);
                    e.printStackTrace();
                    return result;
                }

                if (adminInfoList != null && !adminInfoList.isEmpty()) {
                    Iterator<LinkedHashMap<String, Object>> adminInfoIt = adminInfoList.iterator();
                    while (adminInfoIt.hasNext()) {
                        LinkedHashMap<String, Object> adminInfo = adminInfoIt.next();
                        Object adminToken = SCIMUtil.getAttribute(adminInfo, "bearer");
                        // token????
                        if (adminToken != null && adminToken instanceof String) {
                            if (token.equals(adminToken.toString())) {
                                // ??
                                result = true;

                                break;
                            }
                        }
                    }

                    if (result != true) {
                        // 
                        setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                                MessageConstants.ERROR_INVALID_CREDENTIALS);
                    }
                } else {
                    // 
                    setError(HttpServletResponse.SC_UNAUTHORIZED, null,
                            MessageConstants.ERROR_INVALID_CREDENTIALS);
                }
            }
        } else {
            // 
            setError(HttpServletResponse.SC_UNAUTHORIZED, null, MessageConstants.ERROR_INVALID_CREDENTIALS);
        }
    }

    return result;
}

From source file:fr.univlille2.ecm.drive.BasicDriveAuthenticator.java

public Boolean handleLoginPrompt(HttpServletRequest httpRequest, HttpServletResponse httpResponse,
        String baseURL) {/*from   ww  w . ja  v  a2  s  .  c  om*/
    logger.debug(BasicDriveAuthenticator.class.getSimpleName() + " : handleLoginPrompt");
    try {
        String baHeader = "Basic realm=\"" + realmName + '\"';
        httpResponse.addHeader(BA_HEADER_NAME, baHeader);
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return true;
    } catch (IOException e) {
        return false;
    }
}