sofa-rpc-boot-projects icon indicating copy to clipboard operation
sofa-rpc-boot-projects copied to clipboard

jax.rs 包原生的@Provider无效,自定义rest api annotation不生效

Open JinAirsOs opened this issue 5 years ago • 5 comments

发布一个facade,定义interface,然后自己新建了一个Auth的annotation,但是发现不生效
@GET @Path("user/{id}") @Auth Result getUser(@PathParam("id") String id); annotation的定义在这 @NameBinding @Retention(RUNTIME) @Target({METHOD, TYPE}) public @interface Auth { } @Provider @Auth @Priority(Priorities.AUTHENTICATION) public class JWTAuthFilter1 implements ContainerRequestFilter {

private Logger logger = LoggerFactory.getLogger(JWTAuthFilter1.class);
@Resource
private Environment environment;

private String secret;

private UserDAO userDAO;

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

    // Get the HTTP Authorization header from the request
    String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

    // Extract the token from the HTTP Authorization header
    String token = authorizationHeader.substring("Bearer".length()).trim();

    try {

        secret = environment.getProperty("spring.application.secret");

        Claims claims = JWT.parseJWT(token,secret);
        logger.info("valid token : " + token);
        Date now = new Date();
        if(claims.getExpiration().after(now)) {
            throw new Exception("token expired");
        }
        String userId = claims.getId();
        Long id = Long.parseLong(userId);
        Optional userOptional = userDAO.findById(id);
        if(!userOptional.isPresent()){
            //no such user
            throw new Exception("token invalid");
        } else {
            requestContext.setProperty("user",userOptional.get());
        }

    } catch (Exception e) {
        logger.info("invalid token : " + token);
        requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
    }
}

}

我实际测试过,在jax.rs 空项目中定义这个annotation是会生效的,但是没法在sofaboot里生效?

JinAirsOs avatar May 21 '19 10:05 JinAirsOs

这样子怎么定义带有验证的rest api呢? 请教解决方式

JinAirsOs avatar May 21 '19 10:05 JinAirsOs

@leizhiyuan 关注下这个问题

QilongZhang avatar May 21 '19 12:05 QilongZhang

能否提供一个可复现的demo?

leizhiyuan avatar May 22 '19 00:05 leizhiyuan

能否提供一个可复现的demo?

可以的,就是要简单搭建一下,我开源了的,就是练手的sofaboot example,https://github.com/JinAirsOs/sofaboot-sample-standard,分支jwt,要跑起来详见readme,需要跑一个mysql的docker,然后新建名为test的数据库,JWTAuth这个annotation不生效的。

JinAirsOs avatar May 22 '19 02:05 JinAirsOs

好的,我看下。

leizhiyuan avatar May 22 '19 02:05 leizhiyuan