本文整理匯總了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());
}
}
}
示例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
}
}
}
}
}
示例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());
}
}
}
}
示例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());
}
示例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;
}
示例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());
}
}
示例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());
}
示例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());
}
}
示例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";
}
});
}
}
}
示例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());
}
}
示例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());
}
}
示例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());
}
示例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());
}
}
示例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);
}
示例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());
}
}