Example usage for org.apache.http.auth BasicUserPrincipal BasicUserPrincipal

List of usage examples for org.apache.http.auth BasicUserPrincipal BasicUserPrincipal

Introduction

In this page you can find the example usage for org.apache.http.auth BasicUserPrincipal BasicUserPrincipal.

Prototype

public BasicUserPrincipal(final String username) 

Source Link

Usage

From source file:org.hawk.service.api.dt.http.LazyCredentials.java

protected void getCredentials() {
    try {/*from w ww.jav a 2s. co  m*/
        // Search within the registered servers by prefix
        final List<Server> servers = Activator.getDefault().getServerStore().readAllServers();
        String storeKey = url;
        for (Server server : servers) {
            if (url.startsWith(server.getBaseURL())) {
                storeKey = server.getBaseURL();
                break;
            }
        }

        CredentialsStore.Credentials creds = Activator.getDefault().getCredentialsStore().get(storeKey);
        if (creds == null && PlatformUI.isWorkbenchRunning()) {
            final Display display = PlatformUI.getWorkbench().getDisplay();
            final CredentialsPrompter prompter = new CredentialsPrompter(display);
            display.syncExec(prompter);
            creds = prompter.getCredentials();
        }
        if (creds != null) {
            principal = new BasicUserPrincipal(creds.getUsername());
            password = creds.getPassword();
        }
    } catch (Exception e) {
        Activator.getDefault().logError(e);
    }
}

From source file:com.googlecode.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final DefaultHttpClient client = new DefaultHttpClient();
    final CountDownLatch count = new CountDownLatch(1);
    client.setCredentialsProvider(new BasicCredentialsProvider() {
        @Override/*from  w ww.  ja  va  2s. c  om*/
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:com.github.sardine.AuthenticationTest.java

@Test
public void testBasicPreemptiveAuth() throws Exception {
    final HttpClientBuilder client = HttpClientBuilder.create();
    final CountDownLatch count = new CountDownLatch(1);
    client.setDefaultCredentialsProvider(new BasicCredentialsProvider() {
        @Override// w ww  .  j a v a2s .  c om
        public Credentials getCredentials(AuthScope authscope) {
            // Set flag that credentials have been used indicating preemptive authentication
            count.countDown();
            return new Credentials() {
                public Principal getUserPrincipal() {
                    return new BasicUserPrincipal("anonymous");
                }

                public String getPassword() {
                    return "invalid";
                }
            };
        }
    });
    SardineImpl sardine = new SardineImpl(client);
    URI url = URI.create("http://sudo.ch/dav/basic/");
    //Send basic authentication header in initial request
    sardine.enablePreemptiveAuthentication(url.getHost());
    try {
        sardine.list(url.toString());
        fail("Expected authorization failure");
    } catch (SardineException e) {
        // Expect Authorization Failed
        assertEquals(401, e.getStatusCode());
        // Make sure credentials have been queried
        assertEquals("No preemptive authentication attempt", 0, count.getCount());
    }
}

From source file:org.restheart.test.integration.SecurityAuthTokenIT.java

@Test
public void testAuthTokenResourceLocation() throws Exception {
    Response resp = adminExecutor.execute(Request.Get(rootUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);/*  w w w  .j  a va 2s .co m*/

    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode());

    Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString());
    Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());
    Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString());

    assertNotNull("check not null auth token header", _authToken);
    assertNotNull("check not null auth token valid header", _authTokenValid);
    assertNotNull("check not null auth token location header", _authTokenLocation);

    assertTrue("check not empty array auth token header array ", _authToken.length == 1);
    assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1);
    assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1);

    String locationURI = _authTokenLocation[0].getValue();

    URI authTokenResourceUri = rootUri.resolve(locationURI);

    final String host = CLIENT_HOST;
    final int port = conf.getHttpPort();

    Response resp2 = unauthExecutor.authPreemptive(new HttpHost(host, port, HTTP)).auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Get(authTokenResourceUri));

    HttpResponse httpResp2 = resp2.returnResponse();
    assertNotNull(httpResp2);

    StatusLine statusLine2 = httpResp2.getStatusLine();
    assertNotNull(statusLine2);

    HttpEntity entity = httpResp2.getEntity();
    assertNotNull(entity);

    Header[] _authTokenValid2 = httpResp2.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());

    assertEquals("check auth token resource URI", HttpStatus.SC_OK, statusLine2.getStatusCode());

    assertNotNull("content type not null", entity.getContentType());
    assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue());

    String content = EntityUtils.toString(entity);

    assertNotNull("check content of auth token resource", content);

    JsonObject json = null;

    try {
        json = JsonObject.readFrom(content);
    } catch (Throwable t) {
        fail("parsing received json");
    }

    assertNotNull("check content - auth_token not null", json.get("auth_token"));
    assertNotNull("check content - auth_token_valid_until not null", json.get("auth_token_valid_until"));

    assertTrue("check content - auth_token not empty", !json.get("auth_token").asString().isEmpty());
    assertTrue("check content - auth_token_valid_until not empty",
            !json.get("auth_token_valid_until").asString().isEmpty());

    assertEquals(json.get("auth_token").asString(), _authToken[0].getValue());
    assertEquals(json.get("auth_token_valid_until").asString(), _authTokenValid2[0].getValue());
}

From source file:org.restheart.test.integration.SecurityAuthTokenIT.java

@Test
public void testAuthTokenInvalidation() throws Exception {
    Response resp = adminExecutor.execute(Request.Get(rootUri));

    HttpResponse httpResp = resp.returnResponse();
    assertNotNull(httpResp);/*from   w  w w . j ava2  s .c  om*/

    StatusLine statusLine = httpResp.getStatusLine();
    assertNotNull(statusLine);

    assertEquals("check authorized", HttpStatus.SC_OK, statusLine.getStatusCode());

    Header[] _authToken = httpResp.getHeaders(AUTH_TOKEN_HEADER.toString());
    Header[] _authTokenValid = httpResp.getHeaders(AUTH_TOKEN_VALID_HEADER.toString());
    Header[] _authTokenLocation = httpResp.getHeaders(AUTH_TOKEN_LOCATION_HEADER.toString());

    assertNotNull("check not null auth token header", _authToken);
    assertNotNull("check not null auth token valid header", _authTokenValid);
    assertNotNull("check not null auth token location header", _authTokenLocation);

    assertTrue("check not empty array auth token header array ", _authToken.length == 1);
    assertTrue("check not empty array auth token valid header", _authTokenValid.length == 1);
    assertTrue("check not empty array auth token location header", _authTokenLocation.length == 1);

    String locationURI = _authTokenLocation[0].getValue();

    URI authTokenResourceUri = rootUri.resolve(locationURI);

    Response resp2 = unauthExecutor.auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Delete(authTokenResourceUri));

    HttpResponse httpResp2 = resp2.returnResponse();
    assertNotNull(httpResp2);

    StatusLine statusLine2 = httpResp2.getStatusLine();
    assertNotNull(statusLine2);

    assertEquals("check auth token resource URI", HttpStatus.SC_NO_CONTENT, statusLine2.getStatusCode());

    Response resp3 = unauthExecutor.auth(new Credentials() {
        @Override
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("admin");
        }

        @Override
        public String getPassword() {
            return _authToken[0].getValue();
        }
    }).execute(Request.Get(rootUri));

    HttpResponse httpResp3 = resp3.returnResponse();
    assertNotNull(httpResp3);

    StatusLine statusLine3 = httpResp3.getStatusLine();
    assertNotNull(statusLine3);

    assertEquals("check auth token resource URI", HttpStatus.SC_UNAUTHORIZED, statusLine3.getStatusCode());
}

From source file:org.apache.hadoop.gateway.SecureClusterTest.java

private CloseableHttpClient getHttpClient() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new Credentials() {
        @Override//from  w  w w.j a  v  a  2  s. c om
        public Principal getUserPrincipal() {
            return new BasicUserPrincipal("guest");
        }

        @Override
        public String getPassword() {
            return "guest-password";
        }
    });

    return HttpClients.custom().setDefaultCredentialsProvider(credentialsProvider).build();
}

From source file:com.notemyweb.controller.RestController.java

@RequestMapping(value = "/public/reminder/send.json", method = RequestMethod.GET)
public @ResponseBody void sendReminder(@RequestParam String userId, @RequestParam String webUrl,
        @RequestParam String reminderId) {
    String domain = NotesUtil.getDomain(webUrl);
    Validate.notEmpty(domain, String.format("Invalid domain for url:%s", webUrl));
    try {//from  w  ww .  j  a v  a 2  s .co  m
        BasicUserPrincipal user = new BasicUserPrincipal(userId);
        ReminderList reminderList = getAllReminder(user, webUrl);
        Reminder reminder = reminderList.getReminder(reminderId);
        if (reminder != null && !reminder.isSent()) {
            facebookController.postReminder(userId, String.format("%s - %s", domain, reminder.getMsg()));
            notesEmailClient.sendReminder(notesDao.getUser(userId, Keys.email).getEmail(),
                    ImmutableMap.of("reminder", reminder.getMsg(), "website", domain));
            reminder.setSent(true);
            reminderList.add(reminder);
            setReminderList(user, webUrl, reminderList);
            logger.info("Reminder is sent:" + reminder);
        } else {
            logger.info("Reminder is not sent:" + reminder);
        }
    } catch (Exception e) {
        logger.error("Error in sending reminder:", e);
    }
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

private void configureHttpClient(final DefaultHttpClient httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);//from   ww w .j  a  v  a  2s  .  c  om

    configureAuthentication(httpclient, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        httpclient.getAuthSchemes().register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.getAuthSchemes().register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        configureAuthentication(httpclient, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(httpclient, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.getParams().setBooleanParameter(HANDLE_AUTHENTICATION, true);
}

From source file:com.xebialabs.overthere.winrm.WinRmClient.java

private void configureHttpClient(final HttpClientBuilder httpclient) throws GeneralSecurityException {
    configureTrust(httpclient);/*from w  w w  .ja  v a 2  s .  co  m*/
    BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    httpclient.setDefaultCredentialsProvider(credentialsProvider);

    configureAuthentication(credentialsProvider, BASIC, new BasicUserPrincipal(username));

    if (enableKerberos) {
        String spnServiceClass = kerberosUseHttpSpn ? "HTTP" : "WSMAN";
        RegistryBuilder<AuthSchemeProvider> authSchemeRegistryBuilder = RegistryBuilder.create();
        authSchemeRegistryBuilder.register(KERBEROS, new WsmanKerberosSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        authSchemeRegistryBuilder.register(SPNEGO, new WsmanSPNegoSchemeFactory(!kerberosAddPortToSpn,
                spnServiceClass, unmappedAddress, unmappedPort));
        httpclient.setDefaultAuthSchemeRegistry(authSchemeRegistryBuilder.build());
        configureAuthentication(credentialsProvider, KERBEROS, new KerberosPrincipal(username));
        configureAuthentication(credentialsProvider, SPNEGO, new KerberosPrincipal(username));
    }

    httpclient.setDefaultSocketConfig(SocketConfig.custom().setSoTimeout(soTimeout).build());
    httpclient.setDefaultRequestConfig(
            RequestConfig.custom().setAuthenticationEnabled(true).setConnectTimeout(connectionTimeout).build());
}

From source file:org.apache.solr.security.BasicAuthPlugin.java

@Override
public boolean doAuthenticate(ServletRequest servletRequest, ServletResponse servletResponse,
        FilterChain filterChain) throws Exception {

    HttpServletRequest request = (HttpServletRequest) servletRequest;
    HttpServletResponse response = (HttpServletResponse) servletResponse;

    String authHeader = request.getHeader("Authorization");
    if (authHeader != null) {
        BasicAuthPlugin.authHeader.set(new BasicHeader("Authorization", authHeader));
        StringTokenizer st = new StringTokenizer(authHeader);
        if (st.hasMoreTokens()) {
            String basic = st.nextToken();
            if (basic.equalsIgnoreCase("Basic")) {
                try {
                    String credentials = new String(Base64.decodeBase64(st.nextToken()), "UTF-8");
                    int p = credentials.indexOf(":");
                    if (p != -1) {
                        final String username = credentials.substring(0, p).trim();
                        String pwd = credentials.substring(p + 1).trim();
                        if (!authenticate(username, pwd)) {
                            log.debug("Bad auth credentials supplied in Authorization header");
                            authenticationFailure(response, "Bad credentials");
                        } else {
                            HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request) {
                                @Override
                                public Principal getUserPrincipal() {
                                    return new BasicUserPrincipal(username);
                                }//from w w  w . j  a  v a2s  .  com
                            };
                            filterChain.doFilter(wrapper, response);
                            return true;
                        }

                    } else {
                        authenticationFailure(response, "Invalid authentication token");
                    }
                } catch (UnsupportedEncodingException e) {
                    throw new Error("Couldn't retrieve authentication", e);
                }
            }
        }
    } else {
        if (blockUnknown) {
            authenticationFailure(response, "require authentication");
        } else {
            request.setAttribute(AuthenticationPlugin.class.getName(),
                    authenticationProvider.getPromptHeaders());
            filterChain.doFilter(request, response);
            return true;
        }
    }
    return false;
}