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.craftercms.security.authentication.impl.AuthenticationManagerImplTest.java

@Before
public void setUp() throws Exception {
    MockitoAnnotations.initMocks(this);

    when(authenticationService.authenticate(TENANT1, USERNAME1, PASSWORD1)).thenReturn(getTicket1());
    when(authenticationService.authenticate(TENANT2, USERNAME2, PASSWORD2)).thenReturn(getTicket2());
    doThrow(new ProfileRestServiceException(HttpStatus.UNAUTHORIZED, ErrorCode.BAD_CREDENTIALS, ""))
            .when(authenticationService).authenticate(TENANT1, USERNAME2, PASSWORD2);
    doThrow(new ProfileRestServiceException(HttpStatus.FORBIDDEN, ErrorCode.DISABLED_PROFILE, ""))
            .when(authenticationService).authenticate(TENANT1, DISABLED_USERNAME, PASSWORD1);

    when(profileService.getProfile(PROFILE_ID1.toString(), new String[0])).thenReturn(getProfile1());
    when(profileService.getProfile(PROFILE_ID2.toString(), new String[0])).thenReturn(getProfile2());
    when(profileService.getProfileByTicket(TICKET_ID1, new String[0])).thenReturn(getProfile1());
    doThrow(new ProfileRestServiceException(HttpStatus.BAD_REQUEST, ErrorCode.NO_SUCH_TICKET, ""))
            .when(profileService).getProfileByTicket(INVALID_TICKET_ID, new String[0]);

    when(authenticationCache.getAuthentication(TICKET_ID1)).thenReturn(getAuthentication1());

    authenticationManager = new AuthenticationManagerImpl();
    authenticationManager.setAuthenticationService(authenticationService);
    authenticationManager.setProfileService(profileService);
    authenticationManager.setAuthenticationCache(authenticationCache);
}

From source file:io.github.howiefh.jeews.modules.oauth2.controller.AuthorizeController.java

@RequestMapping("/authentication")
public Object authorize(HttpServletRequest request) throws URISyntaxException, OAuthSystemException {
    try {//from  w w  w . ja  va  2s.com

        // OAuth ?
        OAuthAuthzRequest oauthRequest = new OAuthAuthzRequest(request);

        // id?
        if (!oAuthService.checkClientId(oauthRequest.getClientId())) {
            OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_BAD_REQUEST)
                    .setError(OAuthError.TokenResponse.INVALID_CLIENT)
                    .setErrorDescription(Constants.INVALID_CLIENT_DESCRIPTION).buildJSONMessage();
            return new ResponseEntity<String>(response.getBody(),
                    HttpStatus.valueOf(response.getResponseStatus()));
        }

        Subject subject = SecurityUtils.getSubject();
        // ?
        if (!subject.isAuthenticated()) {
            if (!login(subject, request)) {// ?
                // TODO
                HttpHeaders headers = new HttpHeaders();
                headers.setLocation(new URI(loginUrl));
                return new ResponseEntity<Object>(headers, HttpStatus.UNAUTHORIZED);
            }
        }

        String username = (String) subject.getPrincipal();
        // ???
        String authorizationCode = null;
        // responseType??CODE?TOKEN
        String responseType = oauthRequest.getParam(OAuth.OAUTH_RESPONSE_TYPE);
        OAuthIssuerImpl oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());
        // OAuth?
        OAuthASResponse.OAuthAuthorizationResponseBuilder builder = OAuthASResponse
                .authorizationResponse(request, HttpServletResponse.SC_FOUND);
        if (responseType.equals(ResponseType.CODE.toString())) {
            authorizationCode = oauthIssuerImpl.authorizationCode();
            oAuthService.addAuthCode(authorizationCode, username);
            // ??
            builder.setCode(authorizationCode);
        } else if (responseType.equals(ResponseType.TOKEN.toString())) {
            final String accessToken = oauthIssuerImpl.accessToken();
            oAuthService.addAccessToken(accessToken, username);
            builder.setAccessToken(accessToken);
            builder.setParam("token_type", TokenType.BEARER.toString());
            builder.setExpiresIn(oAuthService.getExpireIn());
        }

        // ???
        String redirectURI = oauthRequest.getParam(OAuth.OAUTH_REDIRECT_URI);

        // ?
        final OAuthResponse response = builder.location(redirectURI).buildQueryMessage();

        // ?OAuthResponseResponseEntity?
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    } catch (OAuthProblemException e) {
        // ?
        String redirectUri = e.getRedirectUri();
        if (OAuthUtils.isEmpty(redirectUri)) {
            // redirectUri
            return new ResponseEntity<String>("OAuth callback url needs to be provided by client!!!",
                    HttpStatus.NOT_FOUND);
        }

        // ??error=
        final OAuthResponse response = OAuthASResponse.errorResponse(HttpServletResponse.SC_FOUND).error(e)
                .location(redirectUri).buildQueryMessage();
        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(new URI(response.getLocationUri()));
        return new ResponseEntity<Object>(headers, HttpStatus.valueOf(response.getResponseStatus()));
    }
}

From source file:com.todo.backend.web.rest.exception.ExceptionResolver.java

@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
@ExceptionHandler(AuthenticationError.class)
public @ResponseBody ErrorResponse authenticationError(HttpServletRequest request,
        AuthenticationError exception) {
    if (log.isErrorEnabled()) {
        log.error(exception.getMessage(), exception);
    }//from   ww  w .  j av a 2s.  c  o  m
    return new ErrorResponse(exception.getErrorCode(), exception.getErrorMessage());
}

From source file:de.zib.gndms.gndmc.dspace.Test.SubspaceClientTest.java

@Test(groups = { "subspaceServiceTest" })
public void testCreateSubspace() {
    final String mode = "CREATE";

    ResponseEntity<Facets> subspace = null;
    try {/*w  w  w .ja v  a  2  s . c o  m*/
        subspace = subspaceClient.createSubspace(subspaceId, subspaceConfig, admindn);

        Assert.assertNotNull(subspace);
        Assert.assertEquals(subspace.getStatusCode(), HttpStatus.CREATED);
    } catch (HttpClientErrorException e) {
        if (!e.getStatusCode().equals(HttpStatus.UNAUTHORIZED))
            throw e;
    }

    final ResponseEntity<Facets> res = subspaceClient.listAvailableFacets(subspaceId, admindn);
    Assert.assertNotNull(res);
    Assert.assertEquals(res.getStatusCode(), HttpStatus.OK);
}

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

@Test
public void testUnauthenticated() throws Exception {

    HttpHeaders headers = new HttpHeaders();
    ResourceOwnerPasswordResourceDetails app = testAccounts.getDefaultResourceOwnerPasswordResource();
    headers.set("Authorization", testAccounts.getAuthorizationHeader(app.getClientId(), "bogus"));
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

    @SuppressWarnings("rawtypes")
    ResponseEntity<Map> response = serverRunning.getForObject("/clientinfo", Map.class, headers);
    assertEquals(HttpStatus.UNAUTHORIZED, response.getStatusCode());
    assertEquals("unauthorized", response.getBody().get("error"));

}

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

@Test
@OAuth2ContextConfiguration(resource = TokenResourceOwnerPassword.class)
public void testRevokeTokenByUser() throws Exception {

    OAuth2AccessToken token = context.getAccessToken();
    String hash = new StandardPasswordEncoder().encode(token.getValue());

    HttpEntity<?> request = new HttpEntity<String>(token.getValue());
    assertEquals(HttpStatus.OK,/* w ww.  j a  va  2s .c  o m*/
            serverRunning
                    .getRestTemplate().exchange(serverRunning.getUrl("/oauth/users/{user}/tokens/{token}"),
                            HttpMethod.DELETE, request, Void.class, testAccounts.getUserName(), hash)
                    .getStatusCode());

    // The token was revoked so if we trya nd use it again it should come back unauthorized
    ResponseEntity<String> result = serverRunning
            .getForString("/oauth/users/" + testAccounts.getUserName() + "/tokens");
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    String body = result.getBody();
    assertTrue("Wrong body: " + body, body.contains("invalid_token"));

}

From source file:org.openlmis.fulfillment.service.BaseCommunicationServiceTest.java

@Test
public void shouldRetryObtainingAccessToken() throws Exception {
    // given/*  w w  w  .  ja v  a2s .c  om*/
    BaseCommunicationService<T> service = prepareService();
    HttpStatusCodeException exception = mock(HttpStatusCodeException.class);
    when(exception.getStatusCode()).thenReturn(HttpStatus.UNAUTHORIZED);
    when(exception.getResponseBodyAsString())
            .thenReturn("{\"error\":\"invalid_token\",\"error_description\":\"" + UUID.randomUUID() + "}");

    // when
    when(restTemplate.exchange(any(URI.class), eq(HttpMethod.GET), any(HttpEntity.class),
            eq(service.getArrayResultClass()))).thenThrow(exception);

    expectedException.expect(DataRetrievalException.class);
    service.findAll("", RequestParameters.init());

    verify(authService, times(1)).clearTokenCache();
    verify(authService, times(2)).obtainAccessToken();
}

From source file:org.craftercms.profile.controllers.rest.ExceptionHandlers.java

@ExceptionHandler(MissingAccessTokenIdParamException.class)
public ResponseEntity<Object> handleMissingAccessTokenIdParamException(MissingAccessTokenIdParamException e,
        WebRequest request) {//from   w  ww.java 2s .c o m
    return handleExceptionInternal(e, HttpStatus.UNAUTHORIZED, ErrorCode.MISSING_ACCESS_TOKEN_ID_PARAM,
            request);
}

From source file:org.createnet.raptor.auth.service.controller.TokenController.java

@PreAuthorize("isAuthenticated()")
@RequestMapping(value = "/token/{tokenId}", method = RequestMethod.GET)
@ApiOperation(value = "Get a token", notes = "", response = Token.class, nickname = "getToken")
public ResponseEntity<?> get(@AuthenticationPrincipal User user, @PathVariable Long tokenId) {

    Token token = tokenService.read(tokenId);

    // TODO add ACL checks
    if (user.getId().longValue() != token.getUser().getId().longValue()) {
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(new JsonErrorResponse(HttpStatus.UNAUTHORIZED.value(), "Not authorized"));
    }//from w  ww  .j a v  a  2 s. c om

    return ResponseEntity.ok(token);
}