Java 类javax.ws.rs.NotAuthorizedException 实例源码

项目:plugin-id-ldap    文件:LdapPluginResource.java   
/**
 * Check the authentication, then create or get the application user
 * matching to the given account.
 * 
 * @param repository
 *            Repository used to authenticate the user, and also to use to
 *            fetch the user attributes.
 * @param authentication
 *            The current authentication.
 * @return A not <code>null</code> application user.
 */
protected String toApplicationUser(final UserLdapRepository repository, final Authentication authentication) {
    // Check the authentication
    final UserOrg account = repository.findOneBy(repository.getAuthenticateProperty(authentication.getName()),
            authentication.getName());

    // Check at least one mail is present
    if (account.getMails().isEmpty()) {
        // Mails are required to proceed the authentication
        log.info("Account '{} [{} {}]' has no mail", account.getId(), account.getFirstName(),
                account.getLastName());
        throw new NotAuthorizedException("ambiguous-account-no-mail");
    }

    // Find the right application user
    return toApplicationUser(account);
}
项目:plugin-id-ldap    文件:LdapPluginResource.java   
/**
 * Create or get the application user matching to the given account.
 * 
 * @param account
 *            The account from the authentication.
 * @return A not <code>null</code> application user.
 */
protected String toApplicationUser(final UserOrg account) {
    // Find the user by the mail in the primary repository
    final List<UserOrg> usersByMail = userResource.findAllBy("mail", account.getMails().get(0));
    if (usersByMail.isEmpty()) {
        // No more try, account can be created in the application repository
        // with a free login
        return newApplicationUser(account);
    }
    if (usersByMail.size() == 1) {
        // Everything is checked, account can be merged into the existing
        // application user
        userResource.mergeUser(usersByMail.get(0), account);
        return usersByMail.get(0).getId();
    }

    // Too many matching mail
    log.info("Account '{} [{} {}]' has too many mails ({}), expected one", account.getId(), account.getFirstName(),
            account.getLastName(), usersByMail.size());
    throw new NotAuthorizedException("ambiguous-account-too-many-mails");

}
项目:InComb    文件:LoggedInUserServiceTest.java   
@Test
public void testLoginFailed() {
    final User user = createUser();

    final UserModel userModel = new UserModel();
    userModel.setUsername(user.getUsername());
    userModel.setPassword("wrongPassword");

    final HttpServletRequest request = new TestHttpServletRequest();

    try {
        service.setRequest(request);
        service.login(userModel, con);
        fail();
    }
    catch(final NotAuthorizedException e) {
        // should happen
    }

    final User userToCheck = (User) request.getSession().getAttribute(LoggedInUserService.SESSIONATTR_LOGGEDIN);
    assertNull(userToCheck);
}
项目:InComb    文件:LoggedInUserServiceTest.java   
@Test
public void testLoginUnknownUser() {
    createUser();

    final UserModel userModel = new UserModel();
    userModel.setUsername("usssserrrr");
    userModel.setPassword(PASSWORD);

    final HttpServletRequest request = new TestHttpServletRequest();

    try {
        service.setRequest(request);
        service.login(userModel, con);
        fail();
    }
    catch(final NotAuthorizedException e) {
        // should happen
    }

    final User userToCheck = (User) request.getSession().getAttribute(LoggedInUserService.SESSIONATTR_LOGGEDIN);
    assertNull(userToCheck);
}
项目:trellis    文件:WebACFilterTest.java   
@Test
public void testFilterAppend() throws Exception {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("POST");
    when(mockAccessControlService.getAccessModes(any(IRI.class), any(Session.class))).thenReturn(modes);

    final WebAcFilter filter = new WebAcFilter(emptyList(), mockAccessControlService);
    modes.add(ACL.Append);
    filter.filter(mockContext);

    modes.add(ACL.Write);
    filter.filter(mockContext);

    modes.remove(ACL.Append);
    filter.filter(mockContext);

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext));
}
项目:aws-photosharing-example    文件:AuthenticationFilter.java   
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    // Get the HTTP Authorization header from the request
    String authorizationHeader =
            requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    // Check if the HTTP Authorization header is present and formatted correctly
    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
        throw new NotAuthorizedException("Authorization header must be provided");
    }

    // Extract the token from the HTTP Authorization header
    String token = authorizationHeader.substring("Bearer".length()).trim();


        // Validate the token
        boolean isValid = validateToken(token);

        if (!isValid) requestContext.abortWith(
                Response.status(Response.Status.UNAUTHORIZED).build());

}
项目:rest-api    文件:JWTTokenNeededFilter.java   
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
    log.info("authorizationHeader : " + authorizationHeader);

    // Check if the HTTP Authorization header is present and formatted correctly
    if (authorizationHeader == null || !authorizationHeader.startsWith("token ")) {
        log.error("invalid authorizationHeader : " + authorizationHeader);
        throw new NotAuthorizedException("Authorization header must be provided");
    }

    // Extract the token from the HTTP Authorization header
    String token = authorizationHeader.substring("Bearer".length()).trim();

    try {
        // Validate the token
        Key key = keyGenerator.generateKey();
        Jwts.parser().setSigningKey(key).parseClaimsJws(token);
        log.info("valid token : " + token);
    } catch (Exception ex) {
        log.error("invalid token : " + token);
        log.error("Exception occurred while validate the token : " + ex);
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
}
项目:servicebuilder    文件:UserTokenFilter.java   
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    String usertokenId = requestContext.getHeaderString(Constants.USERTOKENID_HEADER);

    if (Strings.isNullOrEmpty(usertokenId)) {
        return;
    }

    UserToken userToken;
    try {
        userToken = tokenServiceClient.getUserTokenById(usertokenId);
    } catch (TokenServiceClientException e) {
        throw new NotAuthorizedException("UsertokenId: '" + usertokenId + "' not valid", e);
    }

    UibBrukerPrincipal brukerPrincipal = UibBrukerPrincipal.ofUserToken(userToken);
    ImmutableSet<String> tilganger = extractRolesAllowed(userToken, brukerPrincipal.uibBruker);

    requestContext.setSecurityContext(new AutentiseringsContext(brukerPrincipal, tilganger));

    if (authenticatedHandler != null) {
        authenticatedHandler.handle(requestContext);
    }
}
项目:Reinickendorf_SER316    文件:ApiClient.java   
public <T> T sendRequest (Function <WebClient, T> request) {
    int retries = 0;
    do {
        try {
            WebClient webClientCopy = WebClient.fromClient(webClient);
            T response = request.apply(webClientCopy);
            webClientCopy.close();
            return response;
        }
        catch (NotAuthorizedException e) {
            if (retries < 5) {
                retries ++;
                authClient.refreshAuthenticationContext();
            }
            else throw e;
        }
    } 
    while (retries < 5);

    return null;
}
项目:coddy    文件:AuthorizationRequestFilter.java   
/**
 * This method will catch any request and will analyse the header value of "Authorization" key.
 * If the key is valid, then it will extract the permission user from the token (see {@link JWTService#validateToken(String)}  validateToken()})
 * and put in a Jwt Security Context. see : {@link JWTSecurityContext}
 *
 * @param requestContext : the request context
 * @throws IOException            if an I/O exception occurs.
 * @throws NotAuthorizedException : if the request doesn't contain the token in the header,
 *                                then the user is not authenticated and not allowed to access to the application
 */
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    String token = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (token == null) {
        throw new NotAuthorizedException("user is not authenticated");
    }

    if (token.startsWith(AuthorizationRequestFilter.HEADER_PREFIX)) {
        // Remove header prefix
        token = token.substring(AuthorizationRequestFilter.HEADER_PREFIX.length());
    }

    // if the token is valid, jwt returns an object Principal which contains the list of the user permissions
    JWTPrincipal principal = this.jwtService.validateToken(token);

    String scheme = requestContext.getUriInfo().getRequestUri().getScheme();
    requestContext.setSecurityContext(new JWTSecurityContext(principal, scheme, requestContext.getUriInfo().getPathParameters(), snippetService));
}
项目:fabric8-forge    文件:GitCommandCompletePostProcessor.java   
@Override
public UserDetails preprocessRequest(String name, ExecutionRequest executionRequest, HttpServletRequest request) {
    StopWatch watch = new StopWatch();

    UserDetails userDetails = gitUserHelper.createUserDetails(request);
    // TODO this isn't really required if there's a secret associated with the BuildConfig source
    if (Strings.isNullOrEmpty(userDetails.getUser()) || Strings.isNullOrEmpty(userDetails.getUser())) {
        throw new NotAuthorizedException("You must authenticate to be able to perform this command");
    }

    if (Objects.equals(name, Constants.PROJECT_NEW_COMMAND)) {
        List<Map<String, Object>> inputList = executionRequest.getInputList();
        if (inputList != null) {
            Map<String, Object> page1 = inputList.get(0);
            if (page1 != null) {
                if (page1.containsKey(Constants.TARGET_LOCATION_PROPERTY)) {
                    page1.put(Constants.TARGET_LOCATION_PROPERTY, projectFileSystem.getUserProjectFolderLocation(userDetails));
                }
            }
        }
    }

    LOG.info("preprocessRequest took " + watch.taken());

    return userDetails;
}
项目:trellis    文件:WebACFilterTest.java   
@Test
public void testFilterAppend() throws Exception {
    final Set<IRI> modes = new HashSet<>();
    when(mockContext.getMethod()).thenReturn("POST");
    when(mockAccessControlService.getAccessModes(any(IRI.class), any(Session.class))).thenReturn(modes);

    final WebAcFilter filter = new WebAcFilter(emptyList(), mockAccessControlService);
    modes.add(ACL.Append);
    filter.filter(mockContext);

    modes.add(ACL.Write);
    filter.filter(mockContext);

    modes.remove(ACL.Append);
    filter.filter(mockContext);

    modes.clear();
    assertThrows(NotAuthorizedException.class, () -> filter.filter(mockContext));
}
项目:robozonky    文件:AuthenticatedTest.java   
@Test
public void tokenReattempt() {
    // prepare SUT
    final SecretProvider sp = SecretProvider.fallback(UUID.randomUUID().toString(), new char[0]);
    final String username = sp.getUsername();
    final char[] password = sp.getPassword();
    final ZonkyApiToken token = new ZonkyApiToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(), 1);
    final OAuth oauth = Mockito.mock(OAuth.class);
    Mockito.when(oauth.login(ArgumentMatchers.eq(username), ArgumentMatchers.eq(password))).thenReturn(token);
    final ZonkyApiToken newToken = new ZonkyApiToken(UUID.randomUUID().toString(), UUID.randomUUID().toString(),
                                                     299);
    Mockito.when(oauth.refresh(ArgumentMatchers.eq(token))).thenReturn(newToken);
    final Zonky z = Mockito.mock(Zonky.class);
    final ApiProvider api = mockApiProvider(oauth, z);
    final Duration never = Duration.ofDays(1000); // let's not auto-refresh during the test
    final TokenBasedAccess a = (TokenBasedAccess) Authenticated.tokenBased(api, sp, never);
    // call SUT
    final Consumer<Zonky> f = Mockito.mock(Consumer.class);
    Mockito.doThrow(NotAuthorizedException.class).when(f).accept(z);
    Assertions.assertThatThrownBy(() -> a.run(f)).isInstanceOf(IllegalStateException.class);
    Mockito.verify(oauth).refresh(ArgumentMatchers.any());
    Mockito.verify(f, Mockito.times(3)).accept(z); // three attempts to execute
}
项目:wso2-community-api    文件:TopicsApiServiceImpl.java   
/**
 * Retrieves votes that have been casted on all the posts belonging to the topic
 * @param authorization
 * @param topicId The topic id
 * @param memberId If specified, returns only votes casted by the member with this id
 * @return
 * @throws NotAuthorizedException
 * @throws ServerErrorException
 */
public Response getVotes(
        String authorization,
        Long topicId,
        Integer memberId) 
    throws NotAuthorizedException, ServerErrorException 
   {
       try {
        // Authorize. May throw NotAuthorizedException
        authorize(authorization);
        // Get the DAO implementation
        VoteDAO voteDAO = DAOProvider.getDAO(VoteDAO.class);
        // Get the votes
        List<VoteDTO> voteDTOs = voteDAO.findByTopicAndMember(topicId, memberId);
        // Convert the result
        List<Vote> votes = new VoteConverter().convert(voteDTOs);
        // Return the result
        return Response.status(200).entity(votes).build();
       }
       catch (Exception e) {
        Response response = ResponseUtils.serverError(e);
        throw new ServerErrorException(response);
    }
   }
项目:otus-domain-api    文件:AuthenticationFilter.java   
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
    String authorizationHeader = containerRequestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    if (authorizationHeader == null || !authorizationHeader.startsWith("Bearer ")) {
        throw new NotAuthorizedException("Authorization header must be provided");
    }

    String token = TokenParser.parse(authorizationHeader);

    try{
        securityContextService.validateToken(token);
    } catch (Exception e){
        containerRequestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
}
项目:microbule    文件:AbstractErrorResponseStrategyTest.java   
@Test
public void testCreateException() {
    assertExceptionType(Response.Status.INTERNAL_SERVER_ERROR, InternalServerErrorException.class);
    assertExceptionType(Response.Status.NOT_FOUND, NotFoundException.class);
    assertExceptionType(Response.Status.FORBIDDEN, ForbiddenException.class);
    assertExceptionType(Response.Status.BAD_REQUEST, BadRequestException.class);
    assertExceptionType(Response.Status.METHOD_NOT_ALLOWED, NotAllowedException.class);
    assertExceptionType(Response.Status.UNAUTHORIZED, NotAuthorizedException.class);
    assertExceptionType(Response.Status.NOT_ACCEPTABLE, NotAcceptableException.class);
    assertExceptionType(Response.Status.UNSUPPORTED_MEDIA_TYPE, NotSupportedException.class);
    assertExceptionType(Response.Status.SERVICE_UNAVAILABLE, ServiceUnavailableException.class);
    assertExceptionType(Response.Status.TEMPORARY_REDIRECT, RedirectionException.class);
    assertExceptionType(Response.Status.LENGTH_REQUIRED, ClientErrorException.class);
    assertExceptionType(Response.Status.BAD_GATEWAY, ServerErrorException.class);
    assertExceptionType(Response.Status.NO_CONTENT, WebApplicationException.class);
}
项目:jcronofy    文件:CronofyClientImpl.java   
@Override
public CronofyResponse<ListNotificationChannelsResponse> listNotificationChannels(final ListNotificationChannelsRequest request) {
    assertCronofyRequest(request);
    try {
        return getClient()
                .target(BASE_PATH)
                .path(API_VERSION)
                .path(CHANNELS_PATH)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .header(AUTH_HEADER_KEY, getAccessTokenFromRequest(request))
                .get(new GenericType<CronofyResponse<ListNotificationChannelsResponse>>() {
                });
    } catch (final NotAuthorizedException ignore) {
        LOGGER.warn(NOT_AUTHORIZED_EXCEPTION_MSG, ignore, request);
        return new CronofyResponse<>(ErrorTypeModel.NOT_AUTHORIZED);
    }
}
项目:jcronofy    文件:CronofyClientImpl.java   
@Override
public CronofyResponse<UserInfoResponse> userInfo(final UserInfoRequest request) {
    assertCronofyRequest(request);
    try {
        return getClient()
                .target(BASE_PATH)
                .path(API_VERSION)
                .path(USER_PATH)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .header(AUTH_HEADER_KEY, getAccessTokenFromRequest(request))
                .get(new GenericType<CronofyResponse<UserInfoResponse>>() {
                });
    } catch (final NotAuthorizedException ignore) {
        LOGGER.warn(NOT_AUTHORIZED_EXCEPTION_MSG, ignore, request);
        return new CronofyResponse<>(ErrorTypeModel.NOT_AUTHORIZED);
    }
}
项目:jcronofy    文件:CronofyClientImpl.java   
@Override
public CronofyResponse<AccountInfoResponse> accountInfo(final AccountInfoRequest request) {
    assertCronofyRequest(request);
    try {
        return getClient()
                .target(BASE_PATH)
                .path(API_VERSION)
                .path(ACCOUNT_PATH)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .header(AUTH_HEADER_KEY, getAccessTokenFromRequest(request))
                .get(new GenericType<CronofyResponse<AccountInfoResponse>>() {
                });
    } catch (final NotAuthorizedException ignore) {
        LOGGER.warn(NOT_AUTHORIZED_EXCEPTION_MSG, ignore, request);
        return new CronofyResponse<>(ErrorTypeModel.NOT_AUTHORIZED);
    }
}
项目:jcronofy    文件:CronofyClientImpl.java   
@Override
public CronofyResponse<ProfileInformationResponse> profileInfo(final ProfileInformationRequest request) {
    assertCronofyRequest(request);
    try {
        return getClient()
                .target(BASE_PATH)
                .path(API_VERSION)
                .path(PROFILES_PATH)
                .request(MediaType.APPLICATION_JSON_TYPE)
                .header(AUTH_HEADER_KEY, getAccessTokenFromRequest(request))
                .get(new GenericType<CronofyResponse<ProfileInformationResponse>>() {
                });
    } catch (final NotAuthorizedException ignore) {
        LOGGER.warn(NOT_AUTHORIZED_EXCEPTION_MSG, ignore, request);
        return new CronofyResponse<>(ErrorTypeModel.NOT_AUTHORIZED);
    }
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testListCalendarsScenario3() {
    resetAll();
    // test data
    final ListCalendarsRequest request = getHelper().getListCalendarsRequest();

    final CronofyResponse<ListCalendarsResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<ListCalendarsResponse> result = cronofyClient.listCalendars(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testReadEventsScenario4() {
    resetAll();
    // test data
    final ReadEventsRequest request = getHelper().getReadEventsRequest();
    final CronofyResponse<ReadEventsResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<ReadEventsResponse> result = cronofyClient.readEvents(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testFreeBusyScenario3() {
    resetAll();
    // test data
    final FreeBusyRequest request = getHelper().getFreeBusyRequest();
    final CronofyResponse<FreeBusyResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<FreeBusyResponse> result = cronofyClient.freeBusy(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testCreateNotificationChannelScenario3() {
    resetAll();
    // test data
    final CreateNotificationChannelRequest request = getHelper().getCreateNotificationChannelRequest();
    final CronofyResponse<CreateNotificationChannelResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<CreateNotificationChannelResponse> result = cronofyClient.createNotificationChannel(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testListNotificationChannelsScenario3() {
    resetAll();
    // test data
    final ListNotificationChannelsRequest request = getHelper().getListNotificationChannelsRequest();
    final CronofyResponse<ListNotificationChannelsResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<ListNotificationChannelsResponse> result = cronofyClient.listNotificationChannels(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testAccountInfoScenario3() {
    resetAll();
    // test data
    final AccountInfoRequest request = getHelper().getAccountInfoRequest();
    final CronofyResponse<AccountInfoResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<AccountInfoResponse> result = cronofyClient.accountInfo(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testProfileInfoScenario3() {
    resetAll();
    // test data
    final ProfileInformationRequest request = getHelper().getProfileInformationRequest();
    final CronofyResponse<ProfileInformationResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<ProfileInformationResponse> result = cronofyClient.profileInfo(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:jcronofy    文件:CronofyClientImplTest.java   
/**
 * When not authorized exception has been thrown
 */
@Test
public void testUserInfoScenario3() {
    resetAll();
    // test data
    final UserInfoRequest request = getHelper().getUserInfoRequest();
    final CronofyResponse<UserInfoResponse> expectedResponse = new CronofyResponse<>(
            ErrorTypeModel.NOT_AUTHORIZED
    );
    // expectations
    expect(client.target(BASE_PATH)).andThrow(new NotAuthorizedException(new CronofyResponse<>()));
    replayAll();
    final CronofyResponse<UserInfoResponse> result = cronofyClient.userInfo(request);
    getHelper().assertResultResponse(expectedResponse, result);
    verifyAll();
}
项目:vso-intellij    文件:AuthHelper.java   
public static boolean isNotAuthorizedError(final Throwable throwable) {
    //We get VssServiceResponseException when token is valid but does not have the required scopes
    //statusCode on VssServiceResponseException is set to 401 but that is not accessible, so we have to check the message
    //If the message gets localized, we won't detect the auth error
    if (throwable != null && (throwable instanceof NotAuthorizedException ||
            (throwable instanceof VssServiceResponseException &&
                    StringUtils.containsIgnoreCase(throwable.getMessage(), "unauthorized")))) {
        return true;
    }

    if (throwable != null && throwable.getCause() != null && (throwable.getCause() instanceof NotAuthorizedException ||
            (throwable.getCause() instanceof VssServiceResponseException &&
                    (StringUtils.containsIgnoreCase(throwable.getMessage(), "unauthorized"))))) {
        return true;
    }

    return false;
}
项目:vso-intellij    文件:TFSVcs.java   
/**
 * This method is used by the environment classes to get the ServerContext.
 * We do not cache it here because it should already be cached in the ServerContextManager.
 */
public ServerContext getServerContext(boolean throwIfNotFound) {
    final RepositoryContext repositoryContext = VcsHelper.getRepositoryContext(getProject());
    logger.info("TFSVcs.getServerContext repositoryContext is null: " + (repositoryContext == null));

    final ServerContext serverContext = repositoryContext != null
            && StringUtils.isNotEmpty(repositoryContext.getTeamProjectName())
            && StringUtils.isNotEmpty(repositoryContext.getUrl()) ?
            ServerContextManager.getInstance().createContextFromTfvcServerUrl(
                    repositoryContext.getUrl(), repositoryContext.getTeamProjectName(), true)
            : null;

    if (serverContext == null && throwIfNotFound) {
        // TODO: throw a better error b/c this is what the user sees and it's confusing
        throw new NotAuthorizedException(repositoryContext != null ? repositoryContext.getUrl() : "");
    }
    return serverContext;
}
项目:vso-intellij    文件:WorkspaceModelTest.java   
@Test(expected = NotAuthorizedException.class)
public void testLoadWorkspace_NoRepoContextFound() {
    final WorkspaceModel m = new WorkspaceModel();
    // mockProject2 will return a repository context that does not have a project
    // this will in turn call a null server context to be returned
    when(serverContextManager.createContextFromTfvcServerUrl("bad url", "bad team name", true))
            .thenReturn(null);
    final Project localMockProject = mock(Project.class);
    final RepositoryContext mockRepositoryContext = mock(RepositoryContext.class);
    when(mockRepositoryContext.getUrl()).thenReturn("bad url");
    when(mockRepositoryContext.getTeamProjectName()).thenReturn("bad team name");
    when(VcsHelper.getRepositoryContext(localMockProject)).thenReturn(mockRepositoryContext);
    m.loadWorkspace(localMockProject);

    // make sure the runnable task was submitted
    ArgumentCaptor<Runnable> taskArgument = ArgumentCaptor.forClass(Runnable.class);
    verify(executor).submitOperationTask(taskArgument.capture());

    // Make sure we starting loading
    Assert.assertEquals(true, m.isLoading());

    // Now force the runnable to run
    taskArgument.getValue().run();
}
项目:dropwizard-auth-example    文件:UserInfoResource.java   
/**
 * Gets the info about a user given their ID
 *
 * @param id The id of the user to fetch
 * @return The user
 */
@GET
@Path(("/{id}"))
@Timed
@RolesAllowed({Role.USER_READ_ONLY, Role.ADMIN})
public UserInfo getUser(@Min(1) @PathParam("id") long id, @Auth User user) {
    // User should only be null when testing because the Auth annotation won't work.
    // In our case, we want to continue with the logic in the method to test it.
    if (user != null && !user.getRoles().contains(Role.ADMIN) && !user.getId().equals(String.valueOf(id))) {
        throw new NotAuthorizedException(format("User(%s) trying to access info for user(%d)", user.getId(), id),
                Response.status(Response.Status.UNAUTHORIZED).build());
    }

    if (id > names.size()) {
        throw new NotFoundException("User with id=" + id + " was not found");
    }

    int userIndex = (int) (id - 1);
    return new UserInfo(id, names.get(userIndex));
}
项目:REST-API-Client    文件:RestClient.java   
/**
 * Checks if is status code ok.
 *
 * @param response
 *            the response
 * @param uri
 *            the uri
 * @return true, if is status code ok
 */
private boolean isStatusCodeOK(Response response, String uri) {
    if (response.getStatus() == Status.OK.getStatusCode()
            || response.getStatus() == Status.CREATED.getStatusCode()) {
        return true;
    } else if (response.getStatus() == Status.UNAUTHORIZED.getStatusCode()) {
        throw new NotAuthorizedException("UNAUTHORIZED: Your credentials are wrong. "
                + "Please check your username/password or the secret key.", response);
    } else if (response.getStatus() == Status.CONFLICT.getStatusCode()
            || response.getStatus() == Status.NOT_FOUND.getStatusCode()
            || response.getStatus() == Status.FORBIDDEN.getStatusCode()
            || response.getStatus() == Status.BAD_REQUEST.getStatusCode()) {
        ErrorResponse errorResponse = response.readEntity(ErrorResponse.class);
        throw new ClientErrorException(errorResponse.toString(), response);
    } else {
        throw new WebApplicationException("Unsupported status", response);
    }
}
项目:MoodCat.me-Core    文件:AuthorizationFilter.java   
@Override
public void filter(final ContainerRequestContext containerRequestContext) throws IOException {
    final MultivaluedMap<String, String> parameters = containerRequestContext.getUriInfo()
            .getQueryParameters();
    final String token = parameters.getFirst(TOKEN_PARAMETER);

    if (!Strings.isNullOrEmpty(token)) {
        try {
            final User user = userBackend.loginUsingSoundCloud(token);
            containerRequestContext.setProperty(
                    Key.get(User.class, Names.named(CURRENT_USER_NAME))
                            .toString(), user);
        } catch (final NotAuthorizedException e) {
            final Response response = notAuthorizedExceptionMapper.toResponse(e);
            containerRequestContext.abortWith(response);
        }
    }

}
项目:ROAD    文件:CarServer.java   
@Override
public String addMovement(String apiKey, Long sequence, String xml)
{
    if(this.authentication.checkApiKey(apiKey))
    {
        List<Movement> movements = this.parser.parse(xml, sequence.intValue());
        //List<Movement> movements = this.movementParser.parseChanges(xml, sequence.intValue());
        MovementEvent.fire(movements);

        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
               + "<response status=\"ok\"> <VEHICLE_ID>2</VEHICLE_ID></response></xml>";
    }
    else
    {
        return "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<response status=\"error\"><cause>"
                + new NotAuthorizedException("API Key not valid").getLocalizedMessage()
                + "</cause></response>"
                + "</xml>";
    }
}
项目:lens    文件:BaseLensService.java   
/**
 * Do passwd auth.
 *
 * @param userName the user name
 * @param password the password
 */
private void doPasswdAuth(String userName, String password) {
  // Lens confs to Hive Confs.
  for (ConfVars var : new ConfVars[]{ConfVars.HIVE_SERVER2_PLAIN_LDAP_DOMAIN}) {
    if (cliService.getHiveConf().getVar(var) == null) {
      cliService.getHiveConf().setVar(var, cliService.getHiveConf().get(LensConfConstants.SERVER_DOMAIN));
    }
  }
  String authType = getHiveConf().getVar(ConfVars.HIVE_SERVER2_AUTHENTICATION);
  // No-op when authType is NOSASL
  if (!authType.equalsIgnoreCase(HiveAuthFactory.AuthTypes.NOSASL.toString())) {
    try {
      AuthenticationProviderFactory.AuthMethods authMethod = AuthenticationProviderFactory.AuthMethods
        .getValidAuthMethod(authType);
      PasswdAuthenticationProvider provider = AuthenticationProviderFactory
        .getAuthenticationProvider(authMethod, getHiveConf());
      provider.Authenticate(userName, password);
    } catch (Exception e) {
      log.error("Auth error: ", e);
      throw new NotAuthorizedException(e);
    }
  }
}
项目:sinavi-jfw    文件:NotAuthorizedExceptionMapper.java   
/**
 * {@inheritDoc}
 */
@Override
public Response toResponse(final NotAuthorizedException exception) {
    if (L.isDebugEnabled()) {
        L.debug(R.getString("D-REST-JERSEY-MAPPER#0007"));
    }
    ErrorMessage error = ErrorMessages.create(exception)
        .code(ErrorCode.UNAUTHORIZED.code())
        .resolve()
        .get();
    L.warn(error.log(), exception);
    return Response.status(exception.getResponse().getStatusInfo())
        .entity(error)
        .type(MediaType.APPLICATION_JSON)
        .build();
}
项目:cloudbreak    文件:CloudbreakClient.java   
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object result;
    try {
        result = method.invoke(endpoint, args);
    } catch (InvocationTargetException ite) {
        if (ite.getTargetException() instanceof NotAuthorizedException) {
            LOGGER.warn("Unauthorized request on {}.{}(): {}, refreshing the auth token and try again...", endpointType.getCanonicalName(),
                    method.getName(), ite.getTargetException().getMessage());
            refresh(true);
            try {
                result = method.invoke(endpoint, args);
            } catch (InvocationTargetException iite) {
                throw iite.getTargetException();
            }
        } else {
            throw ite.getTargetException();
        }
    }
    return result;
}
项目:cananolab    文件:SampleServicesTest.java   
@Test
public void testDeleteSample() {

    try {

        String jsonString = client.target(urlbase)
                .register(SampleServices.class)
                .path("sample/deleteSample")
                .queryParam("sampleId", "20917507") //ncl-23
                .request("application/json")
                .header("some-header", "true")
                .get(String.class);

        assertNotNull(jsonString);
        assertTrue(jsonString.contains("expired"));

    } catch (Exception e) {
        assertTrue(e instanceof NotAuthorizedException);
    }

}
项目:whois    文件:WhoisRestServiceEndToEndTest.java   
@Test
public void create_assignment__mntby_2valid_SSO_no_pw__not_logged_in() {
    databaseHelper.addObjects(
            makeMntner("LIR", "auth: SSO " + USER1, "auth: SSO " + USER2),
            makeInetnum("10.0.0.0 - 10.255.255.255", "mnt-lower: OWNER-MNT"));

    final RpslObject assignment = makeInetnum("10.0.0.0 - 10.0.255.255", "status: ASSIGNED PA", "mnt-by: LIR-MNT");

    try {
        RestTest.target(getPort(), "whois/test/inetnum?password=owner")
                .request(mediaType)
                .post(Entity.entity(whoisObjectMapper.mapRpslObjects(FormattedClientAttributeMapper.class, assignment), mediaType), String.class);
        fail();
    } catch (NotAuthorizedException expected) {
        assertUnauthorizedErrorMessage(expected, "inetnum", "10.0.0.0 - 10.0.255.255", "mnt-by", "LIR-MNT");
    }
}