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.alehuo.wepas2016projekti.controller.ImageController.java

/**
 * Kuvasta tykkys/*  ww  w  .j  a v a  2  s . co  m*/
 *
 * @param a Autentikointi
 * @param imageUuid Kuvan UUID
 * @param redirect Uudelleenohjaus
 * @param req HTTP Request
 * @return Onnistuiko pyynt vai ei (sek sen tyyppi; unlike vai like).
 */
@RequestMapping(value = "/like", method = RequestMethod.POST)
public ResponseEntity<String> likeImage(Authentication a, @RequestParam String imageUuid,
        @RequestParam int redirect, HttpServletRequest req) {
    //Kyttjn autentikoiminen
    UserAccount u = userService.getUserByUsername(a.getName());
    final HttpHeaders h = new HttpHeaders();
    //Jos kyttjtili ei ole tyhj
    if (u != null) {
        //Haetaan kuva
        Image i = imageService.findOneImageByUuid(imageUuid);

        //Jos kuva ei ole tyhj
        if (i != null && i.isVisible()) {
            //Lis / poista tykkys tilanteen mukaan
            if (i.getLikedBy().contains(u)) {
                LOG.log(Level.INFO, "Kayttaja ''{0}'' poisti tykkayksen kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                i.removeLike(u);
                imageService.saveImage(i);
                h.add("LikeType", "unlike");
            } else {
                i.addLike(u);
                LOG.log(Level.INFO, "Kayttaja ''{0}'' tykkasi kuvasta ''{1}''",
                        new Object[] { a.getName(), imageUuid });
                imageService.saveImage(i);
                h.add("LikeType", "like");
            }
            //Uudelleenohjaus
            if (redirect == 1) {
                h.add("Location", req.getHeader("Referer"));
                return new ResponseEntity<>(h, HttpStatus.FOUND);
            }
            return new ResponseEntity<>(h, HttpStatus.OK);
        } else {
            //Jos kuvaa ei ole olemassa mutta yritetn silti tykt
            LOG.log(Level.WARNING, "Kayttaja ''{0}'' yritti tykata kuvaa, mita ei ole olemassa. ({1})",
                    new Object[] { a.getName(), imageUuid });
            return new ResponseEntity<>(h, HttpStatus.BAD_REQUEST);
        }
    }
    //Jos ei olla kirjauduttu sisn ja yritetn tykt kuvasta
    LOG.log(Level.WARNING, "Yritettiin tykata kuvaa kirjautumatta sisaan ({0})", a.getName());
    return new ResponseEntity<>(h, HttpStatus.UNAUTHORIZED);
}

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

@Test
@OAuth2ContextConfiguration(resource = OAuth2ContextConfiguration.ClientCredentials.class)
public void testRevokeTokenByClient() throws Exception {

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

    HttpEntity<?> request = new HttpEntity<String>(token.getValue());
    assertEquals(HttpStatus.OK,//from ww  w.  j  a v a  2 s.  c  o m
            serverRunning.getRestTemplate().exchange(serverRunning.getUrl("/oauth/clients/scim/tokens/" + hash),
                    HttpMethod.DELETE, request, Void.class).getStatusCode());

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

}

From source file:com.springsource.greenhouse.WebOAuthActivity.java

@UiThread
void greenhousePreConnectFailed(Exception exception) {
    dismissProgressDialog();//from ww  w .j a  v  a  2s  .  co  m
    if (exception instanceof HttpClientErrorException) {
        if (((HttpClientErrorException) exception).getStatusCode() == HttpStatus.UNAUTHORIZED) {
            displayAppAuthorizationError("This application is not authorized to connect to Greenhouse");
        }
    }
}

From source file:com.capstone.giveout.controllers.GiftsController.java

@PreAuthorize("hasRole(mobile)")
@RequestMapping(value = Routes.GIFTS_UPDATE_PATH, method = RequestMethod.POST)
public @ResponseBody Gift update(@PathVariable("id") long id, @RequestParam("gift") String giftString,
        Principal p, HttpServletResponse response) throws IOException {

    Gift oldGift = gifts.findOne(id);/*w  w  w  .java 2  s  . c o m*/
    if (oldGift == null) {
        response.sendError(HttpStatus.NOT_FOUND.value());
        return null;
    }

    oldGift.allowAccessToGiftChain = true;
    GiftChain oldGiftChain = oldGift.getGiftChain();

    User currentUser = users.findByUsername(p.getName());
    if (oldGift.getUser().getId() != currentUser.getId()) {
        response.sendError(HttpStatus.UNAUTHORIZED.value(), "You are not the owner of this gift");
        return null;
    }

    Gift gift = new ObjectMapper().readValue(UriEncoder.decode(giftString), Gift.class);

    gift.setUser(currentUser);
    gift.setId(id);
    gift.allowAccessToGiftChain = true;

    GiftChain giftChain = gift.getGiftChain();
    if (giftChain != null) {
        // The gift chain provided needs to be created?
        if (giftChain.getId() <= 0) {
            giftChains.save(giftChain);
        } else {
            GiftChain exisingGiftChain = giftChains.findOne(giftChain.getId());
            if (exisingGiftChain == null) {
                response.sendError(HttpStatus.NOT_FOUND.value(), "The Gift chain provided does not exists");
                return null;
            }

            gift.setGiftChain(exisingGiftChain);
        }

    }

    gift.setImageUrlSmall(oldGift.getImageUrlSmall());
    gift.setImageUrlMedium(oldGift.getImageUrlMedium());
    gift.setImageUrlFull(oldGift.getImageUrlFull());
    gifts.save(gift);

    long giftsRemaining = gifts.countByGiftChain(oldGiftChain);

    if (giftsRemaining == 0) {
        giftChains.delete(oldGiftChain);
    }

    return gift;
}

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

@Override
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<BadgeDTO>> badgesGet(
        @ApiParam(value = "token that identifies the app sending the request", required = true) @RequestHeader(value = "X-Gamification-Token", required = true) String xGamificationToken) {

    AuthenKey apiKey = authenKeyRepository.findByAppKey(xGamificationToken);

    //Application app = apprepository.findByAppKey(apiKey);
    if (apiKey == null) {
        return new ResponseEntity(HttpStatus.UNAUTHORIZED);
    }// ww w  .  j  a va2s.co  m

    Application app = apiKey.getApp();

    if (app != null) {
        return new ResponseEntity<>(StreamSupport.stream(badgeRepository.findAllByApp(app).spliterator(), true)
                .map(p -> toDTO(p)).collect(toList()), HttpStatus.OK);
    }
    return new ResponseEntity("no content available", HttpStatus.BAD_REQUEST);

}

From source file:org.craftercms.profile.services.AuthenticationServiceIT.java

@Test
public void testAuthenticateWithInvalidUsername() throws Exception {
    try {/*from w w  w .  ja v a2  s.c o  m*/
        authenticationService.authenticate(DEFAULT_TENANT_NAME, INVALID_USERNAME, ADMIN_PASSWORD);
        fail("Exception " + ProfileRestServiceException.class.getName() + " expected");
    } catch (ProfileRestServiceException e) {
        assertEquals(HttpStatus.UNAUTHORIZED, e.getStatus());
        assertEquals(ErrorCode.BAD_CREDENTIALS, e.getErrorCode());
    }
}

From source file:net.navasoft.madcoin.backend.services.controller.SessionController.java

@ExceptionHandler(InactiveUserException.class)
@ResponseStatus(value = HttpStatus.UNAUTHORIZED)
private @ResponseBody FailedResponseVO handleInactiveUser(SessionControllerException e) {
    FailedResponseVO value = new AuthenticationFailedResponseVO();
    value.setErrorMessage(e.getMessage());
    value.setCauses(e.getCauses());//from  ww w. jav  a 2 s.com
    value.setTip(e.formulateTips());
    return value;
}

From source file:com.alexa.oms.service.AlexaOmsSpeechlet.java

@Override
public SpeechletResponse onIntent(final IntentRequest request, final Session session)
        throws SpeechletException, HttpServerErrorException {
    //LOG.debug("onIntent requestId={}, sessionId={}, access_token={}, userid={}", request.getRequestId(), session.getSessionId(), session.getUser().getAccessToken(), session.getUser().getUserId());

    int customerId;
    try {//from w ww.  ja  v a  2s  . c  o m
        customerId = (Integer) session.getAttribute(CUSTOMER_ID);
        if (!session.getApplication().getApplicationId().equalsIgnoreCase(applicationId)) {
            //return getResponse(RESPONSE_NOT_AUTHORIZED);

            throw new HttpServerErrorException(HttpStatus.UNAUTHORIZED, RESPONSE_NOT_AUTHORIZED);

        }

        Intent intent = request.getIntent();
        String intentName = (intent != null) ? intent.getName() : null;

        IntentType reqIntent = getIntentType(intentName);

        if (reqIntent != null) {
            LOG.debug("Intent ==> " + reqIntent + " Slot Keys :  " + intent.getSlots().keySet() + "Slot Keys :"
                    + intent.getSlots().values());

            switch (reqIntent) {
            case HelloWorldIntent:
                return getResponse(RESPONSE_HELLO_INTENT);

            case OrderStatusIntent:
                return getOrderStatusIntentResponse(intent, customerId, session);

            case OrdersIntent:
                return getOrdersIntentResponse(intent, customerId, session);

            case OrderDetailIntent:
                return getOrderDetailIntentResponse(intent, customerId, session);

            case AmazonHelpIntent:
                return newAskResponse(RESPONSE_HELP_INTENT, true, RESPONSE_REPROMPT_HELP_INTENT, false);

            case AmazonCancelIntent:
                return getResponse(RESPONSE_GOODBYE, true);

            case AmazonStopIntent:
                return getResponse(RESPONSE_GOODBYE, true);

            default:
                throw new SpeechletException(RESPONSE_INVALID_INTENT);

            }
        } else {
            throw new SpeechletException(RESPONSE_INVALID_INTENT);
        }

    } catch (NumberFormatException e) {
        LOG.error("", e);
        throw new SpeechletException(RESPONSE_UNKNOWN_CUSTOMER);

    } catch (Exception e) {
        LOG.error("", e);
        throw new SpeechletException(e.getMessage());
    }

}

From source file:org.appverse.web.framework.backend.test.util.oauth2.tests.predefined.authorizationcode.Oauth2AuthorizationCodeFlowPredefinedTests.java

@Test
public void oauth2FlowTest() throws Exception {
    // Obtains the token
    obtainTokenFromOuth2LoginEndpoint();

    // Call remotelog        
    ResponseEntity<String> result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.OK, result.getStatusCode());

    // Call remotelog once the access token has expired (we wait enough to make sure it has expired)
    Thread.sleep(getTokenExpirationDelayInSeconds() * 1000);

    // Call remotelog        
    result = callRemoteLogWithAccessToken();
    assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    assertTrue(result.getBody().contains("Access token expired"));

    // Refresh the token
    refreshToken();/*  w w w .j  a  v a 2  s.  com*/

    if (!isJwtTokenStore) {
        // The following code is executed only if the token store is not a JwtTokenStore. The reason is that using this kind of store
        // the tokens can't be revoked (they just expire) and so this part of the test would fail.
        // A JwtTokenStore is not a proper store as the tokens are not stored anywhere (as they contain all the required info about the user
        // themselves. That's why the token revocation is not possible.

        // We call logout endpoint (we need to use the access token for this)
        UriComponentsBuilder builder = UriComponentsBuilder
                .fromHttpUrl(resourceServerBaseUrl + baseApiPath + oauth2LogoutEndpointPath);
        builder.queryParam("access_token", accessToken);

        ResponseEntity<String> result2 = restTemplate.exchange(builder.build().encode().toUri(),
                HttpMethod.POST, null, String.class);
        assertEquals(HttpStatus.OK, result2.getStatusCode());

        // We try to call the protected API again (after having logged out which removes the token) - We expect not to be able to call the service.
        // This will throw a exception. In this case here in the test we receive an exception but really what happened was 'access denied'
        // A production client will receive the proper http error
        result = callRemoteLogWithAccessToken();
        assertEquals(HttpStatus.UNAUTHORIZED, result.getStatusCode());
    }
}

From source file:com.github.ibole.infrastructure.web.security.spring.shiro.filter.StatelessAuthFilter.java

@Override
protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request,
        ServletResponse response) {//from   w ww. ja  v a 2s . c o  m

    try {
        WsWebUtil.supportCustomError(response, HttpStatus.UNAUTHORIZED, HttpErrorStatus.ACCOUNT_INVALID);
    } catch (IOException e1) {
        return false;
    }
    logger.warn("Authenticated failed for '{}'. ", token.getPrincipal());
    return false;
}