當前位置: 首頁>>代碼示例>>Java>>正文


Java ContainerRequestContext.abortWith方法代碼示例

本文整理匯總了Java中javax.ws.rs.container.ContainerRequestContext.abortWith方法的典型用法代碼示例。如果您正苦於以下問題:Java ContainerRequestContext.abortWith方法的具體用法?Java ContainerRequestContext.abortWith怎麽用?Java ContainerRequestContext.abortWith使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在javax.ws.rs.container.ContainerRequestContext的用法示例。


在下文中一共展示了ContainerRequestContext.abortWith方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(final ContainerRequestContext ctx) throws IOException {
    final List<String> exts = ctx.getUriInfo().getQueryParameters().getOrDefault("ext", emptyList());
    if (exts.contains(UPLOADS)) {
        if (INVALID_EXT_METHODS.contains(ctx.getMethod())) {
            ctx.abortWith(status(METHOD_NOT_ALLOWED).build());
        }

        if (ctx.getMethod().equals("POST")) {
            final String path = ctx.getUriInfo().getPath();
            final String urlBase = nonNull(baseUrl) ? baseUrl : ctx.getUriInfo().getBaseUri().toString();
            final String contentType = ofNullable(ctx.getMediaType()).map(MediaType::toString)
                .orElse(APPLICATION_OCTET_STREAM);
            final String identifier = ofNullable(ctx.getHeaderString("Slug"))
                .orElseGet(resourceService.getIdentifierSupplier());
            final String uploadId = binaryService.initiateUpload(rdf.createIRI(TRELLIS_PREFIX + path + identifier),
                            contentType);
            if (isNull(uploadId)) {
                throw new WebApplicationException("Cannot initiate multipart upload", BAD_REQUEST);
            }
            ctx.abortWith(status(CREATED).location(create(urlBase + UPLOAD_PREFIX + uploadId)).build());
        }
    }
}
 
開發者ID:trellis-ldp,項目名稱:trellis,代碼行數:25,代碼來源:MultipartUploader.java

示例2: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) {
    if (requestContext instanceof ContainerRequest) {

        final Principal principal = (Principal) requestContext.getProperty("Principal");
        if (principal == null) {
            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
            return;
        }

        final PermissionRequired annotation = resourceInfo.getResourceMethod().getDeclaredAnnotation(PermissionRequired.class);

        try (AlpineQueryManager qm = new AlpineQueryManager()) {
            if (principal instanceof LdapUser) {
                final LdapUser user = qm.getLdapUser(((LdapUser) principal).getUsername());

                final String[] permissions = annotation.value();
                for (String permission: permissions) {
                    // todo check if user has one of these required permissions
                }
            }
        }
    }
}
 
開發者ID:stevespringett,項目名稱:Alpine,代碼行數:25,代碼來源:AuthorizationFilter.java

示例3: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
/**
* 
*
*     -----Algorithm-----
*  Since client makes preflight request we need to be aware of it, hence this algorithm manages to workout 
*     the authentication process 
*  1. First comes the preflight request, we get the header and check the Authorization header, since it fails the condition
*     we let go the request without any interception.
*  2. Second comes the request, the case is that preflight request header is null
*      2.1 If header is null then user has not been logged in before, we need to authenticate it, we let request to follow its source.
*      2.2 If header is null and user tries to access any other uri we abort the request with 403 code.
* 
* @throws java.io.IOException    
*/
   @Override
   public void filter(ContainerRequestContext requestContext) throws IOException {
       String headerString = requestContext.getHeaderString("Authorization");
       String preflightRequest = requestContext.getHeaderString("Access-Control-Request-Headers");
       String uriPath = requestContext.getUriInfo().getAbsolutePath().toString();
       if (preflightRequest == null) {
           if (headerString == null || headerString.equals("null")) {
               try {
                   System.out.println("in condition");
                   if (!uriPath.contains("/login/auth")) {
                       requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
                   }
               } catch (Exception ex) {
                   requestContext.abortWith(Response.status(Response.Status.FORBIDDEN).build());
               }
           }
       }
       
       
   }
 
開發者ID:Fatlonder,項目名稱:E-Clinic,代碼行數:35,代碼來源:SecurityRequestFilter.java

示例4: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的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

示例5: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
    public void filter(ContainerRequestContext containerRequestContext) throws IOException {

        UriInfo info = containerRequestContext.getUriInfo();
        if (info.getPath().contains("user/login")) {
            return;
        }

        if (!isAuthTokenValid(containerRequestContext)) {
//            throw new NotAuthorizedException("You Don't Have Permission");
            containerRequestContext.abortWith(Response
                    .seeOther(URI.create("/tastjava/user/login")).build());
        }

        return;

    }
 
開發者ID:xujiajun,項目名稱:tastjava,代碼行數:18,代碼來源:ResourceAuthFilter.java

示例6: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的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: preflight

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
protected void preflight(String origin, ContainerRequestContext requestContext) throws IOException {
    checkOrigin(requestContext, origin);

    Response.ResponseBuilder builder = Response.ok();
    builder.header(ACCESS_CONTROL_ALLOW_ORIGIN, origin);
    if (allowCredentials)
        builder.header(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true");
    String requestMethods = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_METHOD);
    if (requestMethods != null) {
        if (allowedMethods != null) {
            requestMethods = this.allowedMethods;
        }
        builder.header(ACCESS_CONTROL_ALLOW_METHODS, requestMethods);
    }
    String allowHeaders = requestContext.getHeaderString(ACCESS_CONTROL_REQUEST_HEADERS);
    if (allowHeaders != null) {
        if (allowedHeaders != null) {
            allowHeaders = this.allowedHeaders;
        }
        builder.header(ACCESS_CONTROL_ALLOW_HEADERS, allowHeaders);
    }
    if (corsMaxAge > -1) {
        builder.header(ACCESS_CONTROL_MAX_AGE, corsMaxAge);
    }
    requestContext.abortWith(builder.build());

}
 
開發者ID:fabric8-launcher,項目名稱:launcher-backend,代碼行數:28,代碼來源:CorsFilter.java

示例8: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	String userIdStr = requestContext.getHeaderString("userId");
	String securityToken = requestContext.getHeaderString("securityToken");
	if (userIdStr == null || securityToken == null || userIdStr.isEmpty() || securityToken.isEmpty()) {
		throw new NotAuthorizedException("Authorization header must be provided");
	}
	Long userId = Long.valueOf(userIdStr);
	try {
		validateToken(userId, securityToken);
	} catch (Exception e) {
		requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
	}
}
 
開發者ID:SoapboxRaceWorld,項目名稱:soapbox-race-core,代碼行數:15,代碼來源:AuthenticationFilter.java

示例9: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    final Charset CHARACTER_SET = Charset.forName("utf-8");

    String authHeader = requestContext.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
    if (authHeader != null && authHeader.startsWith("Basic")) {
        String decoded =
                new String(Base64.getDecoder().decode(authHeader.substring(6).getBytes()), CHARACTER_SET);
        final String[] split = decoded.split(":");
        final String username = split[0];
        final String password = split[1];
        // FIXME: 這裏要驗證登陸並在請求頭或者參數中加入token
        boolean verify = false;
        if (!verify) {
            requestContext.abortWith(Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, "Basic")
                .build());
        }
        else {
            requestContext.setSecurityContext(new SecurityContext() {
                @Override
                public Principal getUserPrincipal() {
                    return new Principal() {
                        @Override
                        public String getName() {
                            return username;
                        }
                    };
                }


                @Override
                public boolean isUserInRole(String role) {
                    return true;
                }


                @Override
                public boolean isSecure() {
                    return false;
                }


                @Override
                public String getAuthenticationScheme() {
                    return "BASIC";
                }
            });
        }
    }

}
 
開發者ID:jiumao-org,項目名稱:wechat-mall,代碼行數:53,代碼來源:BasicAuthFilter.java

示例10: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    final HttpSession session = httpServletRequest.getSession(false);
    if (null == session || null == session.getAttribute(attributeName)) {
        requestContext.abortWith(Response.seeOther(URI.create("/")).build());
    }
}
 
開發者ID:CloudWise-OpenSource,項目名稱:SAPNetworkMonitor,代碼行數:8,代碼來源:NiPingAuthFilter.java

示例11: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
	User subject = ResteasyProviderFactory.getContextData(User.class);
	if(subject == null){
		UriBuilder builder = requestContext.getUriInfo().getBaseUriBuilder();
		Session session = ResteasyProviderFactory.getContextData(Session.class);
		session.put(BaseSecurityResource.REDIRECT_KEY, requestContext.getUriInfo().getPath(false));
		URI loginUri = builder.path(BaseSecurityResource.class).path(BaseSecurityResource.class, "login").build();
		requestContext.abortWith(Response.status(Status.TEMPORARY_REDIRECT).location(loginUri).build());
	}
}
 
開發者ID:FroMage,項目名稱:redpipe,代碼行數:12,代碼來源:LoginRedirectFilter.java

示例12: handle

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
public static void handle(ContainerRequestContext requestContext) {
  final UriInfo info = requestContext.getUriInfo();
  final String path = info.getPath();
  final boolean openUrl = path.startsWith("bootstrap/firstuser") || path.startsWith("test/create");

  if(openUrl){
    return;
  }

  requestContext.abortWith(Response.status(Response.Status.FORBIDDEN)
      .entity(new GenericErrorMessage(GenericErrorMessage.NO_USER_MSG))
      .build());
}
 
開發者ID:dremio,項目名稱:dremio-oss,代碼行數:14,代碼來源:NoUserFilter.java

示例13: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    OidcClientTokenContext ctx = (OidcClientTokenContext) JAXRSUtils.getCurrentMessage().getContent(ClientTokenContext.class);
    IdToken idToken = ctx.getIdToken();
    String email = idToken.getEmail();
    String hdParam = idToken.getStringProperty("hd");
    boolean fromGsuite = config.getGSuiteDomain().equalsIgnoreCase(hdParam);
    Set<String> externalAccounts = externalAccountsCache.get();
    if (!fromGsuite && !externalAccounts.contains(email)) {
        log.error("Unauthorized access from {}", hdParam);
        ServerError err = new ServerError("E001", "Sorry you are not allowed to enter this site");
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).entity(err).type(MediaType.APPLICATION_JSON).build());
    }
}
 
開發者ID:hlavki,項目名稱:g-suite-identity-sync,代碼行數:15,代碼來源:GSuiteGroupAuthorizationFilter.java

示例14: handleErrorUnauthorizedForEndpoint

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
private void handleErrorUnauthorizedForEndpoint(ContainerRequestContext requestContext, String apptokenid, TokenCheckResult result) {
    String feilref = UUID.randomUUID().toString();
    String msg = "Apptokenid '" + apptokenid + "' is UNAUTHORIZED for this endpoint";
    log.warn(msg);
    ProblemResponse problemResponse = new ProblemResponse("ERROR", msg, Status.UNAUTHORIZED.getStatusCode(), feilref);
    Response response = Response.status(Status.UNAUTHORIZED).entity(problemResponse).build();
    requestContext.abortWith(response);
}
 
開發者ID:code-obos,項目名稱:servicebuilder,代碼行數:9,代碼來源:ApplicationTokenFilter.java

示例15: filter

import javax.ws.rs.container.ContainerRequestContext; //導入方法依賴的package包/類
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
    try {
        String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
        String token = authorizationHeader.substring("Bearer".length()).trim();
        final Key key = KeyGenerator.getKey(deskDroidService.getApplicationContext());
        final JwtParser jwtParser = Jwts.parser().setSigningKey(key);
        jwtParser.parseClaimsJws(token);
    } catch (Exception e) {
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
}
 
開發者ID:PacktPublishing,項目名稱:Java-9-Programming-Blueprints,代碼行數:13,代碼來源:SecureFilter.java


注:本文中的javax.ws.rs.container.ContainerRequestContext.abortWith方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。