java-@secured注释不起作用

时间:2018-08-18 15:34:00

标签: java eclipse authorization jwt

我正在eclipse上用Java(JPA)编写我的应用程序的后端,目前,我正在尝试编写一个身份验证过滤器以强制某些请求具有有效的jwt。但是,当我发送不带授权令牌的请求时,我的过滤器不会“捕获”该请求,并且该函数已成功调用返回状态:200(尽管预期会出现未经授权的401)。

filters.AuthenticationFilter.java

package filters;

import java.io.IOException;
import java.security.Key;
import java.util.Date;

import javax.annotation.Priority;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ext.Provider;

import org.apache.cxf.jaxrs.ext.MessageContext;
import javax.ws.rs.NotAuthorizedException;
import javax.ws.rs.Priorities;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.Response;

import annotations.Secured;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;

@Secured
@Provider
@Priority(Priorities.AUTHENTICATION)
public class AuthenticationFilter implements ContainerRequestFilter {

    @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();

    try {

        // Validate the token
        validateToken(token);

    } catch (Exception e) {
        requestContext.abortWith(
            Response.status(Response.Status.UNAUTHORIZED).build());
    }
    }

    private void validateToken(String token) throws Exception {

        Key key = utilities.KeyHolder.key;
        try {

            Claims claims = Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody();
            long nowMillis = System.currentTimeMillis();
            Date now = new Date(nowMillis);
            if (now.after(claims.getExpiration()))
                throw new Exception();
        } 
        catch (SignatureException e) {
            throw e;
        }
    }
}

annotations.Secured.java

package annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.ws.rs.NameBinding;

@NameBinding
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD})
public @interface Secured { }

还有一个名为的服务示例:

@POST
@Secured
@Consumes({"application/json"})
@Path("/changeEmail")
public Response changeEmail(ChangeEmailBean changeEmailBean) {
    UserDB userDao = new UserDB();
    entities.User userd = userDao.getById(changeEmailBean.getUserId());
    userd.setEmail(changeEmailBean.getEmail());
    userDao.mergeUser(userd);

    return Response.status(200).build();
}

大部分过滤器来自:Best practice for REST token-based authentication with JAX-RS and Jersey
我想念什么吗?

0 个答案:

没有答案