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.hemou.android.account.AccountUtils.java

/**
 * Is the given {@link Exception} due to a 401 Unauthorized API response?
 * //from  w w w.ja  v  a2s .co m
 * @param e
 * @return true if 401, false otherwise
 */
public static boolean isUnauthorized(final Exception e) {
    Log.e(TAG, "Exception occured[" + Thread.currentThread().getId() + "]:{type:" + e.getClass().getName() + ","
            + e.getLocalizedMessage() + "}");
    String errorMess = e.getMessage();

    if (!StringUtils.isEmpty(errorMess) && (errorMess.contains("The authorization has expired")
            || errorMess.contains("401 Unauthorized") || errorMess.contains("403 Forbidden")))
        return true;

    if (e instanceof NotAuthorizedException) {
        Log.e(TAG, "?...");
        return true;
    }
    //      if (e instanceof ResourceAccessException)
    //         return true;
    if (e instanceof HttpClientErrorException) {
        HttpClientErrorException expt = (HttpClientErrorException) e;
        HttpStatus status = expt.getStatusCode();
        if (Arrays.asList(HttpStatus.UNAUTHORIZED, HttpStatus.NETWORK_AUTHENTICATION_REQUIRED,
                HttpStatus.NON_AUTHORITATIVE_INFORMATION, HttpStatus.PROXY_AUTHENTICATION_REQUIRED,
                //403??????
                HttpStatus.FORBIDDEN).contains(status))
            return true;
    }

    return false;
}

From source file:org.eclipse.cft.server.core.internal.CloudErrorUtil.java

/**
 * check 401 error due to invalid credentials
 * @param t//from  w  w w . j a  va 2 s .c o  m
 * @return true if 401. False otherwise
 */
public static boolean isUnauthorisedException(Throwable t) {
    return isHttpException(t, HttpStatus.UNAUTHORIZED);
}

From source file:com.appglu.impl.UserTemplateTest.java

@Test
public void readDataUnauthorized() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/users/me/data")).andExpect(method(HttpMethod.GET))
            .andExpect(header(UserSessionPersistence.X_APPGLU_SESSION_HEADER, "sessionId"))
            .andRespond(withStatus(HttpStatus.UNAUTHORIZED).body(compactedJson("data/user_unauthorized"))
                    .headers(responseHeaders));

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    appGluTemplate.setUserSessionPersistence(new LoggedInUserSessionPersistence("sessionId", new User("test")));

    Assert.assertTrue(appGluTemplate.isUserAuthenticated());
    Assert.assertNotNull(appGluTemplate.getAuthenticatedUser());

    try {/*  ww w .  j  a v  a 2s  .c om*/
        userOperations.readData();
        Assert.fail("An unauthorized response should throw an AppGluHttpUserUnauthorizedException exception");
    } catch (AppGluHttpUserUnauthorizedException e) {

    }

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    mockServer.verify();
}

From source file:de.hska.ld.etherpad.controller.DocumentEtherpadController.java

@RequestMapping(method = RequestMethod.POST, value = "/etherpad/conversationsForComments")
public Callable getConversationsForComments(
        @RequestBody ConversationsForCommentsReqDto conversationsForCommentsReqDto) {
    return () -> {
        if (env.getProperty("module.etherpad.apikey").equals(conversationsForCommentsReqDto.getApiKey())) {
            String sessionId = conversationsForCommentsReqDto.getAuthorId();
            UserEtherpadInfo userEtherpadInfo = userEtherpadInfoService.findBySessionId(sessionId);
            if (userEtherpadInfo == null) {
                return new ResponseEntity<>("sessionID is invalid", HttpStatus.UNAUTHORIZED);
            }/*from  ww w  . j  a  va  2 s. co  m*/
            ConversationsForCommentsReqDto temp = conversationsForCommentsReqDto;
            System.out.println(temp);
            DocumentEtherpadInfo documentEtherpadInfo = documentEtherpadInfoService
                    .findByGroupPadId(conversationsForCommentsReqDto.getPadId());
            return userService.callAs(userEtherpadInfo.getUser(), () -> {
                if (temp.getCommentIdList().size() > 0) {
                    CommentConversationDto commentConversationDto = new CommentConversationDto();
                    commentConversationDto.setCommentId(temp.getCommentIdList().get(0));
                    commentConversationDto.setConversationId("Test");
                    return new ResponseEntity<>(commentConversationDto, HttpStatus.OK);
                } else {
                    return new ResponseEntity<>("[]", HttpStatus.OK);
                }
            });
        } else {
            return new ResponseEntity<>(HttpStatus.UNAUTHORIZED);
        }
    };
}

From source file:org.mitreid.multiparty.web.ResourceController.java

@RequestMapping(value = "/api/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody//from ww  w .  ja  v  a  2s.com
public Resource getResource(@PathVariable("id") String rsId,
        @RequestHeader(value = "Authorization", required = false) String authorization,
        HttpServletResponse response) throws JsonIOException, IOException {
    // load the resource from the ID
    Resource res = resourceService.getById(rsId);

    if (res == null) {
        // no resource with that ID, return a 404
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return null;
    }

    // get the resource set associated with the resource
    SharedResourceSet resourceSet = resourceService.getSharedResourceSetForResource(res);

    if (resourceSet == null) {
        // not shared yet, return a 404
        response.setStatus(HttpStatus.NOT_FOUND.value());
        return null;
    }

    // load the server configuration based on the issuer from the resource set
    MultipartyServerConfiguration server = serverConfig.getServerConfiguration(resourceSet.getIssuer());
    // load client configuration (register if needed)
    RegisteredClient client = clientConfig.getClientConfiguration(server);
    // get an access token
    String protectionAccessTokenValue = acccessTokenService.getAccessToken(server, client);

    // get a permission ticket for this resource set
    String ticket = getTicket(resourceSet, server, client, protectionAccessTokenValue);

    if (Strings.isNullOrEmpty(ticket)) {
        // couldn't get a ticket for some reason
        response.addHeader(HttpHeaders.WARNING, "199 - UMA Authorization Server Unreachable");
        response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
        return null;
    }

    // add the issuer and ticket to the response header
    response.addHeader(HttpHeaders.WWW_AUTHENTICATE, "UMA realm=\"multiparty-resource\", as_uri=\""
            + resourceSet.getIssuer() + "\", ticket=\"" + ticket + "\"");

    // check the request to get the incoming token
    if (Strings.isNullOrEmpty(authorization) || !authorization.toLowerCase().startsWith("bearer ")) {
        // no token, return a 401
        response.setStatus(HttpStatus.UNAUTHORIZED.value());
        return null;
    }
    String incomingAccessToken = authorization.substring("bearer ".length());
    // introspect/load the token
    JsonObject introspected = introspectToken(incomingAccessToken, server, client, protectionAccessTokenValue);

    if (!introspected.get("active").getAsBoolean()) {
        // token wasn't active, forbidden
        response.setStatus(HttpStatus.FORBIDDEN.value());
        return null;
    }

    JsonArray permissions = introspected.get("permissions").getAsJsonArray();
    for (JsonElement permission : permissions) {
        // check to see that the token is for the right resource set
        String permissionRsid = permission.getAsJsonObject().get("resource_set_id").getAsString();
        if (permissionRsid.equals(resourceSet.getRsid())) {
            // check to see if the token has the right scopes
            Set<String> scopes = JsonUtils.getAsStringSet(permission.getAsJsonObject(), "permission_scopes");

            if (scopes.contains("read")) {
                // if the token is good enough, return the resource
                return res;
            }
        }
    }

    // if we fall down here then we didn't find a workable permission
    response.setStatus(HttpStatus.FORBIDDEN.value());
    return null;

}

From source file:com.appglu.impl.UserTemplateTest.java

@Test
public void writeDataUnauthorized() {
    mockServer.expect(requestTo("http://localhost/appglu/v1/users/me/data")).andExpect(method(HttpMethod.PUT))
            .andExpect(content().string(compactedJson("data/user_data_single_entry")))
            .andExpect(header(UserSessionPersistence.X_APPGLU_SESSION_HEADER, "sessionId"))
            .andRespond(withStatus(HttpStatus.UNAUTHORIZED).body(compactedJson("data/user_unauthorized"))
                    .headers(responseHeaders));

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    appGluTemplate.setUserSessionPersistence(new LoggedInUserSessionPersistence("sessionId", new User("test")));

    Assert.assertTrue(appGluTemplate.isUserAuthenticated());
    Assert.assertNotNull(appGluTemplate.getAuthenticatedUser());

    try {/*from w w  w. j  a va2s  .c  om*/
        HashMap<String, Object> data = new HashMap<String, Object>();
        data.put("key", "value");

        userOperations.writeData(data);
        Assert.fail("An unauthorized response should throw an AppGluHttpUserUnauthorizedException exception");
    } catch (AppGluHttpUserUnauthorizedException e) {

    }

    Assert.assertFalse(appGluTemplate.isUserAuthenticated());
    Assert.assertNull(appGluTemplate.getAuthenticatedUser());

    mockServer.verify();
}

From source file:com.erudika.scoold.ScooldServer.java

/**
 * @return Error page registry bean// w w w.j  av  a2s .c  o  m
 */
@Bean
public ErrorPageRegistrar errorPageRegistrar() {
    return new ErrorPageRegistrar() {
        @Override
        public void registerErrorPages(ErrorPageRegistry epr) {
            epr.addErrorPages(new ErrorPage(HttpStatus.NOT_FOUND, "/not-found"));
            epr.addErrorPages(new ErrorPage(HttpStatus.FORBIDDEN, "/error/403"));
            epr.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401"));
            epr.addErrorPages(new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500"));
            epr.addErrorPages(new ErrorPage(HttpStatus.SERVICE_UNAVAILABLE, "/error/503"));
            epr.addErrorPages(new ErrorPage(HttpStatus.BAD_REQUEST, "/error/400"));
            epr.addErrorPages(new ErrorPage(HttpStatus.METHOD_NOT_ALLOWED, "/error/405"));
            epr.addErrorPages(new ErrorPage(Exception.class, "/error/500"));
        }
    };
}

From source file:com.ge.predix.integration.test.AccessControlServiceIT.java

@Test(dataProvider = "endpointProvider")
public void testPolicyUpdateWithNoOauthToken(final String endpoint)
        throws JsonParseException, JsonMappingException, IOException {
    RestTemplate acs = new RestTemplate();
    // Use vanilla rest template with no oauth token.
    try {// w w  w. j  ava 2  s.co  m
        String policyFile = "src/test/resources/policy-set-with-multiple-policies-na-with-condition.json";
        this.policyHelper.setTestPolicy(acs, this.zone1Headers, endpoint, policyFile);
        Assert.fail("No exception thrown when making request without token.");
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.UNAUTHORIZED);
    }

}

From source file:com.ge.predix.integration.test.AccessControlServiceIT.java

@Test(dataProvider = "endpointProvider")
public void testPolicyEvalWithNoOauthToken(final String endpoint) {
    RestTemplate acs = new RestTemplate();
    // Use vanilla rest template with no oauth token.
    try {//from   www .ja  v a2 s  . c o  m
        acs.postForEntity(endpoint + PolicyHelper.ACS_POLICY_EVAL_API_PATH,
                new HttpEntity<>(
                        this.policyHelper.createEvalRequest(MARISSA_V1.getSubjectIdentifier(), "sanramon"),
                        this.zone1Headers),
                PolicyEvaluationResult.class);
        Assert.fail("No exception thrown when making policy evaluation request without token.");
    } catch (HttpClientErrorException e) {
        Assert.assertEquals(e.getStatusCode(), HttpStatus.UNAUTHORIZED);
    }
}

From source file:de.zib.gndms.dspace.service.SubspaceServiceImpl.java

@ExceptionHandler(UnauthorizedException.class)
public ResponseEntity<Void> handleUnAuthorizedException(UnauthorizedException ex, HttpServletResponse response)
        throws IOException {
    logger.debug("handling exception for: " + ex.getMessage());
    response.setStatus(HttpStatus.UNAUTHORIZED.value());
    response.sendError(HttpStatus.UNAUTHORIZED.value());
    return new ResponseEntity<Void>(null, getSliceKindHeaders(ex.getMessage(), null, null),
            HttpStatus.UNAUTHORIZED);/*from   w  w w.  j a va2  s.co  m*/
}