Example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED

List of usage examples for java.net HttpURLConnection HTTP_UNAUTHORIZED

Introduction

In this page you can find the example usage for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Prototype

int HTTP_UNAUTHORIZED

To view the source code for java.net HttpURLConnection HTTP_UNAUTHORIZED.

Click Source Link

Document

HTTP Status-Code 401: Unauthorized.

Usage

From source file:no.uis.fsws.proxy.ProxySoapHeaderInterceptor.java

@Override
public void handleMessage(Message message) {

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);

    // If the policy is not set, the user did not specify credentials
    // A 401 is sent to the client to indicate that authentication is required
    if (policy == null) {
        log.warn("User attempted to log in with no credentials");
        sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
        return;//from  ww w .ja  va 2 s  .  co m
    }

    if (log.isInfoEnabled()) {
        log.info("Logged in user: " + policy.getUserName());
    }

    boolean authorized = false;
    ProxyPrincipal principal = authorizer.authenticate(policy.getUserName(), policy.getPassword());
    if (principal != null) {
        if (authorizer.hasAuthorization(principal, policy.getAuthorizationType(), policy.getAuthorization())) {
            message.setContextualProperty(AbstractFswsProxy.PRINCIPAL, principal);
            authorized = true;
        }
    }

    if (!authorized) {
        if (log.isEnabledFor(Level.WARN)) {
            log.warn("User not authorized: " + policy.getUserName());
        }
        sendErrorResponse(message, HttpURLConnection.HTTP_FORBIDDEN);
    }
}

From source file:eu.dime.userresolver.service.basicauth.BasicAuthenticationInterceptor.java

/**
 * org.apache.cxf.message.Message.PROTOCOL_HEADERS -- 
 * {Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp, *;q=0.8], 
 * accept-encoding=[gzip,deflate,sdch], 
 * accept-language=[de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4], 
 * Authorization=[Basic Og==], /*from  w  ww  . j  a  va 2  s .co m*/
 * cache-control=[max-age=0], 
 * connection=[keep-alive], 
 * Content-Type=[null], 
 * dnt=[1], 
 * host=[141.99.159.223], 
 * user-agent=[...]}
*/

@Override
public void handleMessage(Message message) throws Fault {
    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    Set<Entry<String, Object>> set = message.entrySet();

    if (policy == null) {
        sendErrorResponse(message, HttpURLConnection.HTTP_UNAUTHORIZED);
        return;
    }
    String address;
    if (message != null && message.get(Message.ENDPOINT_ADDRESS) != null) {
        address = message.get(Message.ENDPOINT_ADDRESS).toString();
    } else {
        address = "";
    }
    if (!address.endsWith("register")) {
        User user = userProvider.getBySaid(policy.getUserName());
        String key = DigestUtils.sha256Hex(policy.getPassword());

        if (!user.getKey().equals(key)) {
            log.warn("Invalid username or password for user: " + policy.getUserName());
            sendErrorResponse(message, HttpURLConnection.HTTP_FORBIDDEN);
            return;
        }
    }
}

From source file:net.sf.taverna.t2.uiexts.bioswr.ui.worker.CheckCredentialsWorker.java

@Override
protected Boolean doInBackground() throws Exception {
    HttpClient client = new HttpClient();
    client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

    GetMethod get = new GetMethod(uri.toString());
    get.setDoAuthentication(true);// w w  w  .j a  va2  s. c  o  m

    try {
        final int status = client.executeMethod(get);
        return status != HttpURLConnection.HTTP_UNAUTHORIZED;
    } finally {
        get.releaseConnection();
    }

    //        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
    //        connection.setAllowUserInteraction(false);
    //        connection.setRequestProperty ("Authorization", authorization);
    //        connection.connect();
    //        return connection.getResponseCode() != HttpURLConnection.HTTP_UNAUTHORIZED;
}

From source file:gov.nih.nci.nbia.servlet.DownloadServletV2.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // This servlet processes Manifest download related requests only. JNLP
    // download related requests are processed at DownloadServlet
    String serverManifestLoc = request.getParameter("serverManifestLoc");

    // check file type and authenticate user
    if (StringUtils.isNotBlank(serverManifestLoc)) {

        String userId = request.getParameter("userId");
        String password = request.getHeader("password");

        if ((userId == null) || (password == null)) {
            userId = NCIAConfig.getGuestUsername();
        } else if (!loggedIn(userId, password)) {
            response.sendError(HttpURLConnection.HTTP_UNAUTHORIZED,
                    "Incorrect username and/or password. Please try it again.");
            return;
        }/*from  w  w  w .  j  a va 2 s .c o m*/
        downloadManifestFile(serverManifestLoc, response, userId, password);
    } else {
        String seriesUid = request.getParameter("seriesUid");
        String userId = request.getParameter("userId");
        String password = request.getHeader("password");
        Boolean includeAnnotation = Boolean.valueOf(request.getParameter("includeAnnotation"));
        Boolean hasAnnotation = Boolean.valueOf(request.getParameter("hasAnnotation"));
        String sopUids = request.getParameter("sopUids");

        if ((userId == null) || (userId.length() < 1)) {
            userId = NCIAConfig.getGuestUsername();
        }

        logger.info("sopUids:" + sopUids);
        logger.info("seriesUid: " + seriesUid + " userId: " + userId + " includeAnnotation: "
                + includeAnnotation + " hasAnnotation: " + hasAnnotation);

        processRequest(response, seriesUid, userId, password, includeAnnotation, hasAnnotation, sopUids);
    }
}

From source file:i5.las2peer.services.userManagement.UserManagement.java

/**
 * /* w w  w  . j  a v  a  2 s. com*/
 * createUser
 * 
 * 
 * @return HttpResponse
 * 
 */
@POST
@Path("/create")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.TEXT_PLAIN)
@ApiResponses(value = { @ApiResponse(code = HttpURLConnection.HTTP_CONFLICT, message = "userExists"),
        @ApiResponse(code = HttpURLConnection.HTTP_UNAUTHORIZED, message = "authorizationNeeded"),
        @ApiResponse(code = HttpURLConnection.HTTP_CREATED, message = "userCreated"),
        @ApiResponse(code = HttpURLConnection.HTTP_INTERNAL_ERROR, message = "internal"),
        @ApiResponse(code = HttpURLConnection.HTTP_BAD_REQUEST, message = "malformedRequest") })
@ApiOperation(value = "createUser", notes = "")
public HttpResponse createUser() {
    // userExists
    boolean userExists_condition = true;
    if (userExists_condition) {
        String error = "Some String";
        HttpResponse userExists = new HttpResponse(error, HttpURLConnection.HTTP_CONFLICT);
        return userExists;
    }
    // authorizationNeeded
    boolean authorizationNeeded_condition = true;
    if (authorizationNeeded_condition) {
        String error = "Some String";
        HttpResponse authorizationNeeded = new HttpResponse(error, HttpURLConnection.HTTP_UNAUTHORIZED);
        return authorizationNeeded;
    }
    // userCreated
    boolean userCreated_condition = true;
    if (userCreated_condition) {
        JSONObject User = new JSONObject();
        HttpResponse userCreated = new HttpResponse(User.toJSONString(), HttpURLConnection.HTTP_CREATED);
        return userCreated;
    }
    // internal
    boolean internal_condition = true;
    if (internal_condition) {
        String error = "Some String";
        HttpResponse internal = new HttpResponse(error, HttpURLConnection.HTTP_INTERNAL_ERROR);
        return internal;
    }
    // malformedRequest
    boolean malformedRequest_condition = true;
    if (malformedRequest_condition) {
        String malformation = "Some String";
        HttpResponse malformedRequest = new HttpResponse(malformation, HttpURLConnection.HTTP_BAD_REQUEST);
        return malformedRequest;
    }
    return null;
}

From source file:rapture.kernel.UserApiImpl.java

@Override
public RaptureUser changeMyPassword(CallingContext context, String oldHashPassword, String newHashPassword) {
    RaptureUser usr = Kernel.getAdmin().getTrusted().getUser(context, context.getUser());
    if (usr != null) {
        if (usr.getHashPassword().equals(oldHashPassword)) {
            usr.setHashPassword(newHashPassword);
            RaptureUserStorage.add(usr, context.getUser(), "Updated my password");
            return usr;
        } else {/* www . j a  va  2  s  . c o  m*/
            throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_UNAUTHORIZED, "Bad Password");
        }
    } else {
        throw RaptureExceptionFactory.create(HttpURLConnection.HTTP_BAD_REQUEST, "Could not find user record");
    }
}

From source file:com.mobile.godot.core.controller.CoreController.java

public synchronized void approach(String username, String carName) {

    String servlet = "Approach";
    List<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
    params.add(new BasicNameValuePair("username", username));
    params.add(new BasicNameValuePair("carName", carName));
    SparseIntArray mMessageMap = new SparseIntArray();
    mMessageMap.append(HttpURLConnection.HTTP_ACCEPTED, GodotMessage.Core.DRIVER_UPDATED);
    mMessageMap.append(HttpURLConnection.HTTP_CREATED, GodotMessage.Core.MESSAGE_SENT);
    mMessageMap.append(HttpURLConnection.HTTP_NOT_FOUND, GodotMessage.Core.CAR_NOT_FOUND);
    mMessageMap.append(HttpURLConnection.HTTP_UNAUTHORIZED, GodotMessage.Error.UNAUTHORIZED);

    GodotAction action = new GodotAction(servlet, params, mMessageMap, mHandler);
    Thread tAction = new Thread(action);
    tAction.start();/* w  w  w . jav  a2s  .c  o  m*/

}

From source file:org.apache.cxf.security.spring.BasicAuthInterceptor.java

public void handleMessage(Message inMessage) {
    AuthorizationPolicy policy = inMessage.get(AuthorizationPolicy.class);
    boolean sendUnauthorized = true;
    if (policy != null) {
        Authentication authentication = new UsernamePasswordAuthenticationToken(policy.getUserName(),
                policy.getPassword());/*from  w w  w.java  2 s. c  om*/
        try {
            authentication = authenticationManager.authenticate(authentication);
            inMessage.getExchange().put(Authentication.class, authentication);
            sendUnauthorized = false;
        } catch (AuthenticationException ex) {
            // TODO: log exception?
        }
    }
    if (sendUnauthorized) {
        Message outMessage = getOutMessage(inMessage);
        outMessage.put(Message.RESPONSE_CODE, HttpURLConnection.HTTP_UNAUTHORIZED);
        setHeader(outMessage, "WWW-Authenticate", "Basic realm=foo"); // TODO: configure realm
        inMessage.getInterceptorChain().abort();
        try {
            getConduit(inMessage).prepare(outMessage);
            close(outMessage);
        } catch (IOException ioe) {
            // REVISIT log etc...
            ioe.printStackTrace();
        }
    }
}

From source file:org.deegree.framework.util.HttpUtils.java

/**
 * validates passed URL. If it is not a valid URL or a client can not connect to it an exception will be thrown
 * /*from   w  w  w .ja v  a 2  s .  co m*/
 * @param url
 * @param user
 * @param password
 * @throws IOException
 */
public static int validateURL(String url, String user, String password) throws IOException {
    if (url.startsWith("http:")) {
        URL tmp = new URL(url);
        HeadMethod hm = new HeadMethod(url);
        setHTTPCredentials(hm, user, password);
        InetAddress.getByName(tmp.getHost());
        HttpClient client = new HttpClient();
        client.executeMethod(hm);
        if (hm.getStatusCode() != HttpURLConnection.HTTP_OK) {
            if (hm.getStatusCode() != HttpURLConnection.HTTP_UNAUTHORIZED && hm.getStatusCode() != 401) {
                // this method just evaluates if a URL/host is valid; it does not takes care
                // if authorization is available/valid
                throw new IOException("Host " + tmp.getHost() + " of URL + " + url + " does not exists");
            }
        }
        return hm.getStatusCode();
    } else if (url.startsWith("file:")) {
        URL tmp = new URL(url);
        InputStream is = tmp.openStream();
        is.close();
        return 200;
    }
    return HttpURLConnection.HTTP_UNAVAILABLE;
}

From source file:co.cask.cdap.client.rest.RestStreamClientTest.java

@Test
public void testNotAuthorizedGetTTL() throws IOException {
    try {//from   w  w  w  .j a va  2s .co m
        streamClient.getTTL(TestUtils.AUTH_STREAM_NAME);
        Assert.fail("Expected HttpFailureException");
    } catch (HttpFailureException e) {
        Assert.assertEquals(HttpURLConnection.HTTP_UNAUTHORIZED, e.getStatusCode());
    }
}