Skip to content
This repository has been archived by the owner on May 30, 2022. It is now read-only.

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

Open
JinAirsOs opened this issue May 21, 2019 · 5 comments

Comments

@JinAirsOs
Copy link

发布一个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
Copy link
Author

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

@QilongZhang
Copy link
Contributor

@leizhiyuan 关注下这个问题

@leizhiyuan
Copy link
Contributor

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

@JinAirsOs
Copy link
Author

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

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

@leizhiyuan
Copy link
Contributor

好的,我看下。

@QilongZhang QilongZhang transferred this issue from sofastack/sofa-boot May 28, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants