<commit_before>/*
###############################################################################
#                                                                             #
#    Copyright 2016, AdeptJ (http://www.adeptj.com)                           #
#                                                                             #
#    Licensed under the Apache License, Version 2.0 (the "License");          #
#    you may not use this file except in compliance with the License.         #
#    You may obtain a copy of the License at                                  #
#                                                                             #
#        http://www.apache.org/licenses/LICENSE-2.0                           #
#                                                                             #
#    Unless required by applicable law or agreed to in writing, software      #
#    distributed under the License is distributed on an "AS IS" BASIS,        #
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
#    See the License for the specific language governing permissions and      #
#    limitations under the License.                                           #
#                                                                             #
###############################################################################
*/
package com.adeptj.modules.jaxrs.core;

import com.adeptj.modules.security.jwt.JwtService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.Optional;

import static javax.ws.rs.Priorities.AUTHENTICATION;
import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE;

/**
 * Gets the JWT from HTTP Authorization header or Cookie and verify it using JwtService.
 *
 * @author Rakesh.Kumar, AdeptJ
 */
@Provider
@RequiresJwt
@Priority(AUTHENTICATION)
public class JwtFilter implements ContainerRequestFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtFilter.class);

    /**
     * Bearer schema string length + 1
     */
    private static final int LEN = 7;

    private static final String JWT_COOKIE_NAME = "jwt";

    private volatile JwtService jwtService;

    public void setJwtService(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (this.jwtService == null) {
            LOGGER.warn("Can't verify JWT as JwtService unavailable!");
            this.abort(requestContext, SERVICE_UNAVAILABLE, "JwtService unavailable!!");
            return;
        }
        this.handleSecurity(requestContext);
    }

    private void handleSecurity(ContainerRequestContext requestContext) {
        String jwt = this.resolveJwt(requestContext);
        if (StringUtils.isEmpty(jwt)) {
            this.abort(requestContext, BAD_REQUEST, "JWT missing from request!!");
        } else if (!this.jwtService.verify(jwt)) {
            this.abort(requestContext, FORBIDDEN, "Invalid JWT!!");
        }
    }

    private String resolveJwt(ContainerRequestContext requestContext) {
        return Optional.ofNullable(this.resolveFromHeaders(requestContext)).orElseGet(() ->
                this.resolveFromCookies(requestContext));
    }

    private String resolveFromHeaders(ContainerRequestContext requestContext) {
        return StringUtils.substring(requestContext.getHeaderString(AUTHORIZATION), LEN);
    }

    private String resolveFromCookies(ContainerRequestContext requestContext) {
        Cookie jwtCookie = requestContext.getCookies().get(JWT_COOKIE_NAME);
        String jwtCookieValue = null;
        if (jwtCookie == null) {
            LOGGER.warn("Exhausted all options to resolve JWT!!");
        } else {
            jwtCookieValue = jwtCookie.getValue();
        }
        return jwtCookieValue;
    }

    private void abort(ContainerRequestContext ctx, Response.Status status, Object entity) {
        ctx.abortWith(Response.status(status).entity(entity).type(TEXT_PLAIN).build());
    }
}
<commit_msg>delete any whitespace from JWT.<commit_after>/*
###############################################################################
#                                                                             #
#    Copyright 2016, AdeptJ (http://www.adeptj.com)                           #
#                                                                             #
#    Licensed under the Apache License, Version 2.0 (the "License");          #
#    you may not use this file except in compliance with the License.         #
#    You may obtain a copy of the License at                                  #
#                                                                             #
#        http://www.apache.org/licenses/LICENSE-2.0                           #
#                                                                             #
#    Unless required by applicable law or agreed to in writing, software      #
#    distributed under the License is distributed on an "AS IS" BASIS,        #
#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #
#    See the License for the specific language governing permissions and      #
#    limitations under the License.                                           #
#                                                                             #
###############################################################################
*/
package com.adeptj.modules.jaxrs.core;

import com.adeptj.modules.security.jwt.JwtService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.Provider;
import java.io.IOException;
import java.util.Optional;

import static javax.ws.rs.Priorities.AUTHENTICATION;
import static javax.ws.rs.core.HttpHeaders.AUTHORIZATION;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import static javax.ws.rs.core.Response.Status.BAD_REQUEST;
import static javax.ws.rs.core.Response.Status.FORBIDDEN;
import static javax.ws.rs.core.Response.Status.SERVICE_UNAVAILABLE;

/**
 * Gets the JWT from HTTP Authorization header or Cookie and verify it using JwtService.
 *
 * @author Rakesh.Kumar, AdeptJ
 */
@Provider
@RequiresJwt
@Priority(AUTHENTICATION)
public class JwtFilter implements ContainerRequestFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(JwtFilter.class);

    /**
     * Bearer schema string length + 1
     */
    private static final int LEN = 7;

    private static final String JWT_COOKIE_NAME = "jwt";

    private volatile JwtService jwtService;

    public void setJwtService(JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public void filter(ContainerRequestContext requestContext) throws IOException {
        if (this.jwtService == null) {
            LOGGER.warn("Can't verify JWT as JwtService unavailable!");
            this.abort(requestContext, SERVICE_UNAVAILABLE, "JwtService unavailable!!");
            return;
        }
        this.handleSecurity(requestContext);
    }

    private void handleSecurity(ContainerRequestContext requestContext) {
        String jwt = this.resolveJwt(requestContext);
        if (StringUtils.isEmpty(jwt)) {
            this.abort(requestContext, BAD_REQUEST, "JWT missing from request!!");
        } else if (!this.jwtService.verify(jwt)) {
            this.abort(requestContext, FORBIDDEN, "Invalid JWT!!");
        }
    }

    private String resolveJwt(ContainerRequestContext requestContext) {
        return Optional.ofNullable(this.resolveFromHeaders(requestContext)).orElseGet(() ->
                this.resolveFromCookies(requestContext));
    }

    private String resolveFromHeaders(ContainerRequestContext requestContext) {
        return StringUtils.substring(requestContext.getHeaderString(AUTHORIZATION), LEN);
    }

    private String resolveFromCookies(ContainerRequestContext requestContext) {
        Cookie jwtCookie = requestContext.getCookies().get(JWT_COOKIE_NAME);
        String jwtCookieValue = null;
        if (jwtCookie == null) {
            LOGGER.warn("Exhausted all options to resolve JWT!!");
        } else {
            jwtCookieValue = StringUtils.deleteWhitespace(jwtCookie.getValue());
        }
        return jwtCookieValue;
    }

    private void abort(ContainerRequestContext ctx, Response.Status status, Object entity) {
        ctx.abortWith(Response.status(status).entity(entity).type(TEXT_PLAIN).build());
    }
}

{'fraction_non_alphanumeric': 0.11626907371588223, 'fraction_numerical': 0.0027938964109176876, 'mean_word_length': 2.306216696269982, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 34, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2770376', 'n_tokens_mistral': 2347, 'n_tokens_neox': 2296, 'n_words': 556}