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.bosch.cr.examples.inventorybrowser.server.CustomProxyServlet.java

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // enforce BASIC auth on all requests
    String auth = req.getHeader("Authorization");
    if (auth == null) {
        resp.setHeader("WWW-Authenticate", "BASIC realm=\"Proxy for Bosch IoT Things\"");
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        return;//from ww w.j a v  a2  s . c  o m
    }

    super.service(req, resp);
}

From source file:core.NiprSyncController.java

private boolean isAuthorized(HttpServletRequest request, HttpServletResponse response) {
    String lAuthHeader = request.getHeader("Authorization");
    if (!Configuration.IsAuthenticated(lAuthHeader)) {
        System.out.println("Authentication Failed");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        return false;
    }/*from ww w. j av  a2s .  co  m*/

    return true;
}

From source file:com.pearson.developer.xapi.proxy.AuthFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws java.io.IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;

    // AJAX will preflight xAPI request with OPTIONS request without Authorization header
    if ("OPTIONS".equals(req.getMethod())) {
        chain.doFilter(request, response);
        return;//ww w  . j a  v a 2 s. com
    }

    boolean authorized = false;
    try { // decode and verify the basic auth credentials
        String authHeader = req.getHeader("Authorization");
        authHeader = authHeader.substring("Basic ".length());
        String decodedAuthHeader = new String(Base64.decodeBase64(authHeader), "UTF-8");
        String[] credentials = decodedAuthHeader.split(":");
        if (credentials.length == 2) {
            String username = credentials[0];
            String password = credentials[1];
            authorized = SessionDatabase.verify(username, password);
        }
    } catch (Exception e) {
        // do nothing
    }

    // proceed to xAPI if session was authorized
    if (authorized) {
        final String targetBasicAuth = config.getInitParameter("targetBasicAuth");

        // need to give the LRS it's expected Authorization value
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(req) {
            @Override
            public String getHeader(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    return targetBasicAuth;
                }
                return super.getHeader(name);
            }

            @Override
            public Enumeration<String> getHeaders(String name) {
                if ("Authorization".equalsIgnoreCase(name)) {
                    List<String> values = new ArrayList<String>();
                    values.add(targetBasicAuth);
                    return Collections.enumeration(values);
                }
                return super.getHeaders(name);
            }
        };
        chain.doFilter(requestWrapper, response);
        return;
    }

    // respond with a 401 if missing auth
    HttpServletResponse resp = (HttpServletResponse) response;
    resp.reset();
    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    resp.getWriter().println("401 - Unauthorized");
}

From source file:io.getlime.security.powerauth.app.server.WebSecurityConfig.java

@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    return new AuthenticationEntryPoint() {
        @Override//ww  w.  j  a v a 2  s. c  o m
        public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
                AuthenticationException e) throws IOException, ServletException {
            RESTResponseWrapper<String> errorResponse = new RESTResponseWrapper<>("ERROR",
                    "Authentication failed");
            httpServletResponse.setContentType("application/json");
            httpServletResponse.setCharacterEncoding("UTF-8");
            httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            httpServletResponse.getOutputStream().println(new ObjectMapper().writeValueAsString(errorResponse));
            httpServletResponse.getOutputStream().flush();
        }
    };
}

From source file:com.ecyrd.jspwiki.dav.WikiDavServlet.java

@Override
public void doMkCol(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (request.getContentLength() > 0) {
        response.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Message may contain no body");
    } else {//from w w  w. jav a 2 s .  c  o  m
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "JSPWiki is read-only.");
    }
}

From source file:workspace.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//from   w ww  .ja  v  a2s  .  c  o m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    String class1 = request.getParameter("class");
    String hour = request.getParameter("hour");
    HttpSession session = request.getSession(false);
    if (session == null) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
    } else {
        if (hour == null) {
            try {
                current(out, class1);
            } catch (Exception e) {
            }
        } else {
            try {
                importlast(out, class1, hour);
            } catch (Exception e) {
            }
        }
    }
}

From source file:com.google.gsa.valve.modules.ldap.LDAPUniqueCreds.java

/**
 * This is the main method that does the LDAP authentication using user's 
 * credential in the format of username and password. It creates a 
 * connection with the user credentials and reads his/her own information. 
 * It does not read any other LDAP attribute out of the user entry.
 * <p>/*from   ww  w. ja  va2 s.  c o m*/
 * If the LDAP authentication result is OK, it creates an 
 * authentication cookie. Anyway, the HTTP response code is returned in this 
 * method to inform the caller on the status.
 * 
 * @param request HTTP request
 * @param response HTTP response
 * @param authCookies vector that contains the authentication cookies
 * @param url the document url
 * @param creds an array of credentials for all external sources
 * @param id the default credential id to be retrieved from creds
        
 * @return the HTTP error code
        
 * @throws HttpException
 * @throws IOException
 */
public int authenticate(HttpServletRequest request, HttpServletResponse response, Vector<Cookie> authCookies,
        String url, Credentials creds, String id) throws HttpException, IOException {

    logger.debug("LDAP Unique Credentials Start");

    Cookie[] cookies = null;

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

    // Read cookies
    cookies = request.getCookies();

    //First read the u/p the credentails store, in this case using the same as the root login
    logger.debug("LDAPUniqueCreds: trying to get creds from repository ID: " + id);
    Credential cred = null;
    try {
        cred = creds.getCredential(id);
    } catch (NullPointerException npe) {
        logger.error("NPE while reading credentials of ID: " + id);
    }
    if (cred == null) {
        cred = creds.getCredential("root");
        if (cred != null) {
            logger.info("LDAPUniqueCreds: credential ID used is \"root\"");
        } else {
            logger.error("LDAPUniqueCreds: No credentials available for " + id);
        }
    }

    try {
        authMaxAge = Integer.parseInt(valveConf.getAuthMaxAge());
    } catch (NumberFormatException nfe) {
        logger.error(
                "Configuration error: chack the configuration file as the number set for authMaxAge is not OK:");
    }

    //If the required cookie was not found need to authenticate.
    logger.debug("Authenticating");
    try {

        //read values from config file (if any)
        readLDAPParameters(id);

        //Check if the LDAP credentials are OK                      
        logger.debug("Base user is: " + ldapBaseuser);
        Ldap ldapconn = new Ldap(ldapHost, cred.getUsername(), cred.getPassword(), ldapBaseuser, ldapDomain,
                rdnAttr);

        try {
            logger.debug("Connection to LDAP");
            DirContext ctx = ldapconn.openConnection();
            if (ctx == null) {
                //Just send a comment  
                logger.debug("The user(" + cred.getUsername() + ")/password doesn't match");
                ldapconn.closeConnection(ctx);
                return (HttpServletResponse.SC_UNAUTHORIZED);
            }

            logger.debug("User properly authenticated against the LDAP");

            //Close the connection
            ldapconn.closeConnection(ctx);

        } catch (Exception ex) {
            logger.error("LDAP connection problem during user access: " + ex.getMessage(), ex);
            return (HttpServletResponse.SC_UNAUTHORIZED);
        } finally {
        }

        Cookie extAuthCookie = null;

        extAuthCookie = settingCookie();

        //add sendCookies support
        boolean isSessionEnabled = new Boolean(valveConf.getSessionConfig().isSessionEnabled()).booleanValue();
        boolean sendCookies = false;
        if (isSessionEnabled) {
            sendCookies = new Boolean(valveConf.getSessionConfig().getSendCookies()).booleanValue();
        }
        if ((!isSessionEnabled) || ((isSessionEnabled) && (sendCookies))) {
            response.addCookie(extAuthCookie);
        }

        //add cookie to the array
        authCookies.add(extAuthCookie);

        //This would be set to OK or 401 in a real AuthN module
        statusCode = HttpServletResponse.SC_OK;

    } catch (Exception e) {

        // Log error
        logger.error("Sample authentication failure: " + e.getMessage(), e);

        // Update status code
        statusCode = HttpServletResponse.SC_UNAUTHORIZED;

    }

    // Debug
    logger.debug("Sample Authentication completed (" + statusCode + ")");

    // Return status code
    return statusCode;

}

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

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

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

    // extract auth data
    String authData = getAuthData(request);
    Validate.notNull(authData);
    byte[] decodedAuthData = Base64.decode(authData);

    PrincipalId result = null;
    try {
        // extract username and password from the auth data
        String unp = new String(decodedAuthData, "UTF-8");
        int idx = unp.indexOf(':');
        String username = idx > 0 ? unp.substring(0, idx) : null;
        String password = idx > 0 && unp.length() > idx + 1 ? unp.substring(idx + 1) : null;

        // call authenticate
        result = accessor.authenticate(username, password);
        Validate.notNull(result);
    } catch (Exception e) {
        // failed to authenticate with username/password.
        ValidationResult vr = new ValidationResult(HttpServletResponse.SC_UNAUTHORIZED,
                WebSSOError.UNAUTHORIZED, null);
        t.setValidationResult(vr);
        throw new SamlServiceException();
    }

    if (result != null) {
        t.setPrincipalId(result);
        t.setAuthnMethod(AuthnMethod.PASSWORD);
    }
}

From source file:com.sun.socialsite.web.filters.AnonymousAccessFilter.java

/**
 * If anonymous access not allowed then reject any request that does not
 * have either a SocialSite security token or an OAuth token.
 *//* w ww  .  j  a v  a 2s  .  co  m*/
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {

    log.debug("--- entering");
    if (allowAnonymous) {
        chain.doFilter(req, res);
    } else {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        log.debug(request.getMethod() + " " + request.getRequestURL().toString());
        log.debug("st=" + request.getParameter("st"));

        SecurityToken st = new AuthInfo(request).getSecurityToken();
        if (st != null && (st instanceof SocialSiteToken || st instanceof OAuthSecurityToken
                || st instanceof AssertedToken)) {
            chain.doFilter(req, res);
        } else {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED,
                    "No suitable security token found in request");
        }
    }
    log.debug("--- exiting");
}