All Downloads are FREE. Search and download functionalities are using the official Maven repository.

de.yourinspiration.spring.jwt.JwtServiceInterceptor Maven / Gradle / Ivy

package de.yourinspiration.spring.jwt;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * Interceptor for Spring webmvc controller methods. Handles the
 * {@link RolesAllowed} annotations.
 * 
 * @author Marcel Härle - [email protected]
 *
 */
public class JwtServiceInterceptor extends HandlerInterceptorAdapter {

    private static final Logger log = LoggerFactory.getLogger(JwtServiceInterceptor.class);

    private final JwtService jwtService;

    /**
     * Constructs a new object.
     * 
     * @param jwtService
     *            the service
     */
    public JwtServiceInterceptor(final JwtService jwtService) {
        this.jwtService = jwtService;
    }

    @Override
    public boolean preHandle(final HttpServletRequest request, final HttpServletResponse response, final Object handler)
            throws Exception {
        // Ignore requests where the handler object is not a instance of
        // HandlerMethod, because we retrieve fields by the reflection API that
        // only exists on this type of object.
        if (handler instanceof HandlerMethod) {
            // This cast is save!
            final HandlerMethod handlerMethod = (HandlerMethod) handler;
            // Check if the method has an annotation for RolesAllowed.
            if (hasRolesAllowed(handlerMethod)) {
                // Get the declared roles from the RolesAllowed annotation.
                final String[] roles = getRoles(handlerMethod);
                // Let the service authenticate this request for the current
                // roles.
                if (jwtService.authenticate(request, roles)) {
                    log.debug("Authorized request for {} method {} and subject {}", handlerMethod.getBeanType(),
                            handlerMethod.getMethod().getName(), jwtService.getJwtSubject(request).get());
                    // The user is allowed to invoke this method. Store the
                    // current subject in a request attribute for later
                    // retrieval.
                    request.setAttribute(jwtService.getRequestAttribute(), jwtService.getJwtSubject(request).get());
                    return true;
                } else {
                    log.info("Unauthorized request for {} method {}", handlerMethod.getBeanType(), handlerMethod
                            .getMethod().getName());
                    // The current request has not a valid token or the subject
                    // has not the required role.
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
                    return false;
                }
            } else {
                log.debug("No RolesAllowed annotation found");
                // No RolesAllowed annotation found.
                return true;
            }
        } else {
            log.debug("Ignored intercepted method, because the handler was no HandlerMethod");
            // Ignore the request, because the handler is not a HandlerMethod.
            return true;
        }
    }

    private boolean hasRolesAllowed(final HandlerMethod handlerMethod) {
        return handlerMethod.getMethodAnnotation(RolesAllowed.class) != null;
    }

    private String[] getRoles(final HandlerMethod handlerMethod) {
        final RolesAllowed rolesAllowedAnnotation = handlerMethod.getMethodAnnotation(RolesAllowed.class);
        final String[] roles = rolesAllowedAnnotation.roles();
        return roles;
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy