Example usage for org.springframework.http HttpStatus UNAUTHORIZED

List of usage examples for org.springframework.http HttpStatus UNAUTHORIZED

Introduction

In this page you can find the example usage for org.springframework.http HttpStatus UNAUTHORIZED.

Prototype

HttpStatus UNAUTHORIZED

To view the source code for org.springframework.http HttpStatus UNAUTHORIZED.

Click Source Link

Document

401 Unauthorized .

Usage

From source file:org.cloudfoundry.identity.uaa.authentication.RemoteAuthenticationEndpoint.java

@RequestMapping(value = { "/authenticate" }, method = RequestMethod.POST, params = { "source", "origin",
        UaaAuthenticationDetails.ADD_NEW })
@ResponseBody// w  ww  .  j  a  v a  2  s  . c om
public HttpEntity<AuthenticationResponse> authenticate(HttpServletRequest request,
        @RequestParam(value = "username", required = true) String username,
        @RequestParam(value = OriginKeys.ORIGIN, required = true) String origin,
        @RequestParam(value = "email", required = false) String email) {
    AuthenticationResponse response = new AuthenticationResponse();
    HttpStatus status = HttpStatus.UNAUTHORIZED;

    if (!hasClientOauth2Authentication()) {
        response.setError("authentication failed");
        return new ResponseEntity<>(response, status);
    }

    Map<String, String> userInfo = new HashMap<>();
    userInfo.put("username", username);
    userInfo.put(OriginKeys.ORIGIN, origin);
    if (StringUtils.hasText(email)) {
        userInfo.put("email", email);
    }

    AuthzAuthenticationRequest token = new AuthzAuthenticationRequest(userInfo,
            new UaaAuthenticationDetails(request));
    try {
        Authentication a = loginAuthenticationManager.authenticate(token);
        response.setUsername(a.getName());
        processAdditionalInformation(response, a);
        status = HttpStatus.OK;
    } catch (AuthenticationException e) {
        response.setError("authentication failed");
    } catch (Exception e) {
        logger.debug("Failed to authenticate user ", e);
        response.setError("error");
        status = HttpStatus.INTERNAL_SERVER_ERROR;
    }

    return new ResponseEntity<>(response, status);
}

From source file:org.cloudfoundry.identity.uaa.integration.CheckTokenEndpointIntegrationTests.java

@Test
public void testUnauthorized() {
    MultiValueMap<String, String> formData = new LinkedMultiValueMap<String, String>();
    formData.add("token", "FOO");
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap("/check_token", formData, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());

    @SuppressWarnings("unchecked")
    Map<String, String> map = response.getBody();
    assertTrue(map.containsKey("error"));
}

From source file:org.cloudfoundry.identity.uaa.integration.feature.SamlLoginWithLocalIdpIT.java

@Test
public void testInvalidSaml2Bearer() throws Exception {
    SamlIdentityProviderDefinition idpDef = createLocalSamlIdpDefinition(IDP_ENTITY_ID, "uaa");
    @SuppressWarnings("unchecked")
    IdentityProvider<SamlIdentityProviderDefinition> provider = IntegrationTestUtils.createIdentityProvider(
            "Local SAML IdP", IDP_ENTITY_ID, true, this.baseUrl, this.serverRunning, idpDef);
    HttpHeaders headers = new HttpHeaders();
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
    headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

    LinkedMultiValueMap<String, String> postBody = new LinkedMultiValueMap<>();
    postBody.add("grant_type", "urn:ietf:params:oauth:grant-type:saml2-bearer");
    postBody.add("client_id", "oauth_showcase_saml2_bearer");
    postBody.add("client_secret", "secret");
    postBody.add("assertion",
            "PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz48c2FtbDI6QXNzZXJ0aW9uIHhtbG5zOnNhbWwyPS"
                    + "J1cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YXNzZXJ0aW9uIiBJRD0iXzBkNzhhYTdhLTY4MzctNDUyNi1iNTk4"
                    + "LTliZGE0MTI5NTE0YiIgSXNzdWVJbnN0YW50PSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIFZlcnNpb249IjIuMC"
                    + "IgeG1sbnM6eHM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDEvWE1MU2NoZW1hIj48c2FtbDI6SXNzdWVyPmNsb3VkZm91"
                    + "bmRyeS1zYW1sLWxvZ2luPC9zYW1sMjpJc3N1ZXI-PHNhbWwyOlN1YmplY3Q-PHNhbWwyOk5hbWVJRCBGb3JtYXQ9In"
                    + "VybjpvYXNpczpuYW1lczp0YzpTQU1MOjEuMTpuYW1laWQtZm9ybWF0OnVuc3BlY2lmaWVkIj5Vbml0VGVzdFRlc3RV"
                    + "c2VyPC9zYW1sMjpOYW1lSUQ-PHNhbWwyOlN1YmplY3RDb25maXJtYXRpb24gTWV0aG9kPSJ1cm46b2FzaXM6bmFtZX"
                    + "M6dGM6U0FNTDoyLjA6Y206YmVhcmVyIj48c2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbkRhdGEgTm90T25PckFmdGVy"
                    + "PSIyMDE3LTExLTIyVDIyOjAyOjMwLjI5NloiIFJlY2lwaWVudD0iaHR0cDovL2xvY2FsaG9zdDo4MDgwL3VhYS9vYX"
                    + "V0aC90b2tlbiIvPjwvc2FtbDI6U3ViamVjdENvbmZpcm1hdGlvbj48L3NhbWwyOlN1YmplY3Q-PHNhbWwyOkNvbmRp"
                    + "dGlvbnMgTm90QmVmb3JlPSIyMDE2LTExLTIyVDIxOjU3OjMwLjI2NVoiIE5vdE9uT3JBZnRlcj0iMjAxNy0xMS0yMl"
                    + "QyMjowMjozMC4yOTZaIj48c2FtbDI6QXVkaWVuY2VSZXN0cmljdGlvbj48c2FtbDI6QXVkaWVuY2U-aHR0cDovL2xv"
                    + "Y2FsaG9zdDo4MDgwL3VhYS9vYXV0aC90b2tlbjwvc2FtbDI6QXVkaWVuY2U-PC9zYW1sMjpBdWRpZW5jZVJlc3RyaW"
                    + "N0aW9uPjwvc2FtbDI6Q29uZGl0aW9ucz48c2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdHRyaWJ1dGUg"
                    + "TmFtZT0iR3JvdXBzIj48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMD"
                    + "AxL1hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LndyaXRlPC9zYW1sMjpBdHRy"
                    + "aWJ1dGVWYWx1ZT48c2FtbDI6QXR0cmlidXRlVmFsdWUgeG1sbnM6eHNpPSJodHRwOi8vd3d3LnczLm9yZy8yMDAxL1"
                    + "hNTFNjaGVtYS1pbnN0YW5jZSIgeHNpOnR5cGU9InhzOnN0cmluZyI-Y2xpZW50LnJlYWQ8L3NhbWwyOkF0dHJpYnV0"
                    + "ZVZhbHVlPjwvc2FtbDI6QXR0cmlidXRlPjwvc2FtbDI6QXR0cmlidXRlU3RhdGVtZW50PjxzYW1sMjpBdXRoblN0YX"
                    + "RlbWVudCBBdXRobkluc3RhbnQ9IjIwMTYtMTEtMjJUMjI6MDI6MzAuMjk5WiIgU2Vzc2lvbk5vdE9uT3JBZnRlcj0i"
                    + "MjAxNi0xMi0yMlQyMjowMjozMC4yOTlaIj48c2FtbDI6QXV0aG5Db250ZXh0PjxzYW1sMjpBdXRobkNvbnRleHRDbG"
                    + "Fzc1JlZj51cm46b2FzaXM6bmFtZXM6dGM6U0FNTDoyLjA6YWM6Y2xhc3NlczpQYXNzd29yZDwvc2FtbDI6QXV0aG5D"
                    + "b250ZXh0Q2xhc3NSZWY-PC9zYW1sMjpBdXRobkNvbnRleHQ-PC9zYW1sMjpBdXRoblN0YXRlbWVudD48L3NhbWwyOk"
                    + "Fzc2VydGlvbj4");

    try {// w  w  w  . j  a  va2 s . c  o m
        restOperations.exchange(baseUrl + "/oauth/token", HttpMethod.POST, new HttpEntity<>(postBody, headers),
                Void.class);
    } catch (HttpClientErrorException he) {
        Assert.assertEquals(HttpStatus.UNAUTHORIZED, he.getStatusCode());
    }

    provider.setActive(false);
    IntegrationTestUtils.updateIdentityProvider(this.baseUrl, this.serverRunning, provider);
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testAuthenticateMarissaFails() throws Exception {
    params.set("username", testAccounts.getUserName());
    params.set("password", "");
    ResponseEntity<Map> response = serverRunning.postForMap("/authenticate", params, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testMissingUserInfoIsError() throws Exception {
    params.set("client_id", testAccounts.getDefaultImplicitResource().getClientId());
    params.remove("username");
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAuthorizationUri(), params,
            headers);/*from  ww  w.  j a  va  2 s  .  c  o m*/
    // TODO: should be 302
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> results = response.getBody();
    assertNotNull("There should be an error: " + results, results.containsKey("error"));
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testMissingUsernameIsError() throws Exception {
    ((RestTemplate) serverRunning.getRestTemplate())
            .setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    params.set("client_id", testAccounts.getDefaultImplicitResource().getClientId());
    params.remove("username");
    // Some of the user info is there but not enough to determine a username
    params.set("given_name", "Mabel");
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAuthorizationUri(), params,
            headers);//from   ww w  . j av a2  s  .  c o m
    // TODO: should be 302
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> results = response.getBody();
    assertNotNull("There should be an error: " + results, results.containsKey("error"));
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testWrongUsernameIsErrorAddNewDisabled() throws Exception {

    ((RestTemplate) serverRunning.getRestTemplate())
            .setRequestFactory(new HttpComponentsClientHttpRequestFactory());
    ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource();

    params.set("client_id", resource.getClientId());
    params.set("username", "bogus2");
    params.set(UaaAuthenticationDetails.ADD_NEW, "false");
    String redirect = resource.getPreEstablishedRedirectUri();
    if (redirect != null) {
        params.set("redirect_uri", redirect);
    }//from   ww w. jav  a  2 s .c  o m
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAuthorizationUri(), params,
            headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    @SuppressWarnings("unchecked")
    Map<String, String> results = response.getBody();
    assertNotNull("There should be an error: " + results, results.containsKey("error"));
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testLoginServerWithoutBearerToken() throws Exception {
    ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    headers.add("Authorization", getAuthorizationEncodedValue(resource.getClientId(), ""));
    params.set("client_id", resource.getClientId());
    params.set("client_secret", "");
    params.set("source", "login");
    params.set(UaaAuthenticationDetails.ADD_NEW, "false");
    params.set("grant_type", "password");
    String redirect = resource.getPreEstablishedRedirectUri();
    if (redirect != null) {
        params.set("redirect_uri", redirect);
    }//from   www .j a v a2 s  .co  m
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAccessTokenUri(), params, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(LoginClient.class)
public void testLoginServerCfInvalidClientPasswordToken() throws Exception {
    ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    params.set("client_id", resource.getClientId());
    params.set("client_secret", "bogus");
    params.set("source", "login");
    params.set(UaaAuthenticationDetails.ADD_NEW, "false");
    params.set("grant_type", "password");

    String redirect = resource.getPreEstablishedRedirectUri();
    if (redirect != null) {
        params.set("redirect_uri", redirect);
    }//  www  .  java2 s.c  om
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAccessTokenUri(), params, headers);
    HttpStatus statusCode = response.getStatusCode();
    assertTrue("Status code should be 401 or 403.",
            statusCode == HttpStatus.FORBIDDEN || statusCode == HttpStatus.UNAUTHORIZED);
}

From source file:org.cloudfoundry.identity.uaa.integration.LoginServerSecurityIntegrationTests.java

@Test
@OAuth2ContextConfiguration(AppClient.class)
public void testLoginServerCfInvalidClientToken() throws Exception {
    ImplicitResourceDetails resource = testAccounts.getDefaultImplicitResource();
    HttpHeaders headers = new HttpHeaders();
    headers.add("Accept", MediaType.APPLICATION_JSON_VALUE);
    params.set("client_id", resource.getClientId());
    params.set("client_secret", "bogus");
    params.set("source", "login");
    params.set(UaaAuthenticationDetails.ADD_NEW, "false");
    params.set("grant_type", "password");

    String redirect = resource.getPreEstablishedRedirectUri();
    if (redirect != null) {
        params.set("redirect_uri", redirect);
    }/*from   w ww. j  a  v a 2 s .c o  m*/
    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.postForMap(serverRunning.getAccessTokenUri(), params, headers);
    HttpStatus statusCode = response.getStatusCode();

    assertTrue("Status code should be 401 or 403.",
            statusCode == HttpStatus.FORBIDDEN || statusCode == HttpStatus.UNAUTHORIZED);
}