当前位置: 首页>>代码示例>>Java>>正文


Java NotAuthorizedException类代码示例

本文整理汇总了Java中javax.ws.rs.NotAuthorizedException的典型用法代码示例。如果您正苦于以下问题:Java NotAuthorizedException类的具体用法?Java NotAuthorizedException怎么用?Java NotAuthorizedException使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


NotAuthorizedException类属于javax.ws.rs包,在下文中一共展示了NotAuthorizedException类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: toApplicationUser

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
/**
 * 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);
}
 
开发者ID:ligoj,项目名称:plugin-id-ldap,代码行数:28,代码来源:LdapPluginResource.java

示例2: testLoginFailed

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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);
}
 
开发者ID:XMBomb,项目名称:InComb,代码行数:23,代码来源:LoggedInUserServiceTest.java

示例3: testLoginUnknownUser

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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);
}
 
开发者ID:XMBomb,项目名称:InComb,代码行数:23,代码来源:LoggedInUserServiceTest.java

示例4: testFilterAppend

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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));
}
 
开发者ID:trellis-ldp,项目名称:trellis,代码行数:20,代码来源:WebACFilterTest.java

示例5: filter

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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());

}
 
开发者ID:awslabs,项目名称:aws-photosharing-example,代码行数:24,代码来源:AuthenticationFilter.java

示例6: filter

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:sundarcse1216,项目名称:rest-api,代码行数:27,代码来源:JWTTokenNeededFilter.java

示例7: filter

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:code-obos,项目名称:servicebuilder,代码行数:25,代码来源:UserTokenFilter.java

示例8: sendRequest

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
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;
}
 
开发者ID:ser316asu,项目名称:Reinickendorf_SER316,代码行数:22,代码来源:ApiClient.java

示例9: filter

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
/**
 * 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));
}
 
开发者ID:Crunchy-Torch,项目名称:coddy,代码行数:31,代码来源:AuthorizationRequestFilter.java

示例10: preprocessRequest

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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;
}
 
开发者ID:fabric8io,项目名称:fabric8-forge,代码行数:27,代码来源:GitCommandCompletePostProcessor.java

示例11: tokenReattempt

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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
}
 
开发者ID:RoboZonky,项目名称:robozonky,代码行数:24,代码来源:AuthenticatedTest.java

示例12: getVotes

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
/**
 * 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);
	}
   }
 
开发者ID:vasttrafik,项目名称:wso2-community-api,代码行数:33,代码来源:TopicsApiServiceImpl.java

示例13: filter

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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());
    }
}
 
开发者ID:ccem-dev,项目名称:otus-domain-api,代码行数:17,代码来源:AuthenticationFilter.java

示例14: testCreateException

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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);
}
 
开发者ID:Microbule,项目名称:microbule,代码行数:17,代码来源:AbstractErrorResponseStrategyTest.java

示例15: listNotificationChannels

import javax.ws.rs.NotAuthorizedException; //导入依赖的package包/类
@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);
    }
}
 
开发者ID:Biacode,项目名称:jcronofy,代码行数:18,代码来源:CronofyClientImpl.java


注:本文中的javax.ws.rs.NotAuthorizedException类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。