当前位置: 首页>>代码示例>>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;未经允许,请勿转载。