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:com.fbr.services.SecurityService.java

@Transactional
public HttpStatus checkAuthenticationAndAuthorization(HttpServletRequest httpRequest) {

    logger.debug("Request uri is {}" + httpRequest.getRequestURI());
    if (!LOGIN_EXCEPTION_URIS.contains(httpRequest.getRequestURI())) {

        String sessionId = httpRequest.getHeader("sessionId");
        Enumeration<String> headers = httpRequest.getHeaderNames();
        if (headers != null) {
            logger.debug("Headers are");
            while (headers.hasMoreElements()) {
                logger.debug(headers.nextElement());
            }//from   ww w.j  a  v  a 2 s.c o  m
        }
        if (sessionId != null) {
            Date idleExpirationDate = DateUtils.addMinutes(new Date(), -idle_session_timeout);
            SessionDbType sessionDbType = sessionDao.validateSessionId(sessionId, idleExpirationDate);
            if (sessionDbType == null) {
                logger.debug("Session " + sessionId + " was not found in the database");
                return HttpStatus.UNAUTHORIZED;
            }
            logger.debug("Session " + sessionId + " is validated");
            sessionDbType.setLastAccessTime(new Date());
            sessionDao.update(sessionDbType);
            if (!isAuthorizedForApi(httpRequest.getMethod(), httpRequest.getRequestURI(),
                    httpRequest.getQueryString(), sessionDbType)) {
                logger.debug(httpRequest.getMethod() + " on " + httpRequest.getRequestURI()
                        + " for this user is not authorized");
                return HttpStatus.FORBIDDEN;
            }

            logger.debug("Session " + sessionId + "is Authorized");

        } else {
            logger.debug("sessionId was not found in the header");
            return HttpStatus.UNAUTHORIZED;
        }

    }
    return HttpStatus.OK;
}

From source file:com.boot.pf.config.WebMvcConfig.java

@Bean
public EmbeddedServletContainerCustomizer containerCustomizer() {

    return (container -> {
        ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html");
        ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/404.html");
        ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html");

        container.addErrorPages(error401Page, error404Page, error500Page);
    });//w  ww.ja  v a 2 s  . co  m
}

From source file:org.trustedanalytics.serviceexposer.rest.CredentialsController.java

@ApiOperation(value = "Returns list of all service instance credentials of given type for given space.", notes = "Privilege level: Consumer of this endpoint must be a member of specified space based on valid access token")
@ApiResponses(value = { @ApiResponse(code = 200, message = "OK", response = ResponseEntity.class),
        @ApiResponse(code = 401, message = "User is Unauthorized"),
        @ApiResponse(code = 500, message = "Internal server error, see logs for details") })
@RequestMapping(value = GET_SERVICES_LIST_URL, method = GET, produces = APPLICATION_JSON_VALUE)

public ResponseEntity<?> getAllCredentials(@RequestParam(required = true) UUID space,
        @RequestParam(required = true) String service) {
    return ccOperations.getSpace(space)
            .map(s -> new ResponseEntity<>(getCredentialsInJson(service, s.getGuid()), HttpStatus.OK))
            .onErrorReturn(er -> {//ww w  . j  av a  2  s . c  om
                LOG.error("Exception occurred:", er);
                return new ResponseEntity<>(Collections.emptyMap(), HttpStatus.UNAUTHORIZED);
            }).toBlocking().single();
}

From source file:org.trustedanalytics.h2oscoringengine.publisher.http.FilesDownloaderTest.java

@Test
public void download_serverResponse401_excpetionWithProperMessageThrown() throws IOException {
    // given/*from  ww w  . j  a  v  a 2s. co  m*/
    FilesDownloader downloader = new FilesDownloader(testCredentials, restTemplateMock);
    String expectedExceptionMessage = "Login to " + testCredentials.getHost() + " with credentials "
            + new String(Base64.decodeBase64(testCredentials.getBasicAuthToken().getBytes())) + " failed";

    // when
    when(restTemplateMock.exchange(testCredentials.getHost() + testResource, HttpMethod.GET,
            HttpCommunication.basicAuthRequest(testCredentials.getBasicAuthToken()), byte[].class))
                    .thenThrow(new HttpClientErrorException(HttpStatus.UNAUTHORIZED));

    // then
    thrown.expect(IOException.class);
    thrown.expectMessage(expectedExceptionMessage);
    downloader.download(testResource, testPath);
}

From source file:com.wolkabout.hexiwear.activity.LoginActivity.java

@Background
void signIn() {//from   ww w . ja  va2  s .  c  o  m
    try {
        final String emailAddress = "elbert1212@gmail.com";
        final String password = "thisisthegrouppassword";

        ReadingsActivity.username = emailAddress;

        final AuthenticationResponseDto response = authenticationService
                .signIn(new SignInDto(emailAddress, password));
        credentials.username().put(response.getEmail());
        credentials.accessToken().put(response.getAccessToken());
        credentials.refreshToken().put(response.getRefreshToken());
        credentials.accessTokenExpires().put(response.getAccessTokenExpires().getTime());
        credentials.refreshTokenExpires().put(response.getRefreshTokenExpires().getTime());
        MainActivity_.intent(LoginActivity.this).start();
        finish();
    } catch (HttpStatusCodeException e) {
        Log.e(TAG, "signIn: ", e);
        if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            return;
        }

    } catch (Exception e) {
        Log.e(TAG, "signIn: ", e);
    }
}

From source file:com.bcknds.demo.oauth2.security.ClientCredentialAuthenticationTests.java

/**
 * This test is designed to test having a bad client Id.
 *//*from  ww  w . jav a  2 s .c om*/
@Test
public void testBadClientId() {
    OAuth2RestTemplate restTemplate = AuthenticationUtil.getClientCredentialsWithBadClientId();
    try {
        restTemplate.getAccessToken();
        fail("Expected OAuth2AccessDeniedException, but none was thrown");
    } catch (OAuth2AccessDeniedException ex) {
        if (ex.getCause() instanceof HttpClientErrorException) {
            HttpClientErrorException clientException = (HttpClientErrorException) ex.getCause();
            assertEquals(HttpStatus.UNAUTHORIZED, clientException.getStatusCode());
        } else if (ex.getCause() instanceof ResourceAccessException) {
            fail("It appears that the server may not be running. Please start it before running tests");
        } else {
            fail(String.format("Expected HttpClientErrorException. Got %s",
                    ex.getCause().getClass().getName()));
        }
    } catch (Exception ex) {
        fail(ex.getMessage());
    }
}

From source file:org.appverse.web.framework.backend.test.util.frontfacade.mvc.tests.predefined.BasicAuthEndPointsServiceEnabledPredefinedTests.java

@Test
public void basicAuthenticationServiceTestInvalidCredentials() throws Exception {
    HttpHeaders headers = new HttpHeaders();
    headers.set("Authorization", "Basic " + new String(Base64.encode("user:badpassword".getBytes("UTF-8"))));
    HttpEntity<String> entity = new HttpEntity<String>("headers", headers);

    ResponseEntity<AuthorizationData> responseEntity = restTemplate.exchange(
            "http://localhost:" + port + baseApiPath + basicAuthenticationEndpointPath, HttpMethod.POST, entity,
            AuthorizationData.class);
    assertEquals(HttpStatus.UNAUTHORIZED, responseEntity.getStatusCode());
}

From source file:ch.heigvd.gamification.api.BadgesEndpoint.java

@Override
@RequestMapping(value = "/{badgeId}", method = RequestMethod.GET)
public ResponseEntity<BadgeDTO> badgesBadgeIdGet(
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken,
        @ApiParam(value = "Badge's id", required = true) @PathVariable("badgeId") Long badgeId) {

    AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken);
    if (apiKey == null) {
        return new ResponseEntity("apikey not exist", HttpStatus.UNAUTHORIZED);
    }/*from   w  w w  .  java2s. co m*/

    Application app = apiKey.getApp();
    Badge badge = badgeRepository.findByIdAndApp(badgeId, app);
    if (app != null && badge != null) {
        BadgeDTO dto = toDTO(badge);
        dto.setId(badge.getId());
        if (dto == null) {
            return new ResponseEntity<>(dto, HttpStatus.NOT_FOUND);
        } else {
            return new ResponseEntity<>(dto, HttpStatus.OK);
        }
    }
    return new ResponseEntity("no content is available", HttpStatus.NOT_FOUND);
}

From source file:io.github.azige.bbs.web.controller.AccountController.java

public ResponseEntity<?> loginAjax(@RequestBody Account account, Model model) throws IOException {
    try {//from   w  w  w.  j  a  v  a2s.  com
        Authentication authentication = accountService.authenticate(
                new UsernamePasswordAuthenticationToken(account.getAccountName(), account.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);
        Profile loginProfile = (Profile) authentication.getPrincipal();
        return new ResponseEntity<>(loginProfile, HttpStatus.OK);
    } catch (AuthenticationException ex) {
        return new ResponseEntity<>(
                new ErrorResult(
                        messageSource.getMessage("account.login.fail", null, LocaleContextHolder.getLocale())),
                HttpStatus.UNAUTHORIZED);
    }
}

From source file:com.hypersocket.auth.json.AuthenticatedController.java

@ExceptionHandler(UnauthorizedException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
public void unauthorizedAccess(HttpServletRequest request, HttpServletResponse response,
        UnauthorizedException redirect) {

}