使用 Apache Shiro 保护 Rest 服务资源

Securing Rest Service Resources Using Apache Shiro

我正在尝试保护我使用 Apache Shiro 的 dropwizard 编写的其余服务。首先我在main方法中初始化了安全管理器。

    Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
    SecurityManager securityManager = factory.getInstance();
    SecurityUtils.setSecurityManager(securityManager);

然后我写了一个用户登录的服务

if (!currentUser.isAuthenticated()) {
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        token.setRememberMe(true);
        try {
            currentUser.login(token);
            System.out.println("USER AUTHENTICATED!!!!!!!!");
        } catch (Exception uae) {
            System.out.println("Error logging in .................");
        }
    }

然后我用一些 java 注释声明了一个方法。

    @RequiresAuthentication 
    @RequiresRoles("admin")
    @GET
    @Path("/account")
    @ApiOperation(value = "getAccount")
    public void getAccount() {
        //do something
    }

但是当我在没有登录的情况下访问这个资源时,我成功了。

我做错了什么?还是我应该添加更多内容?就像在 web.xml?

我发现这个 repo 非常有用。 https://github.com/silb/dropwizard-shiro/tree/release-0.2。我按照此中给出的说明进行操作。但是我在配置文件里又加了一件东西

@Valid
@JsonProperty("shiro-configuration")
public ShiroConfiguration shiro = new ShiroConfiguration();

然后在资源class里面,我把登录和注销写成了两个服务

@POST
@Path("/session")
@Produces(MediaType.TEXT_PLAIN)
public String login(@FormParam("username") String username, @FormParam("password") String password, @Auth Subject subject) {
    subject.login(new UsernamePasswordToken(username, password));
    return username;
}

@PUT
@Path("/logout")
@Produces(MediaType.TEXT_PLAIN)
public String logout(@Auth Subject subject){
    subject.logout();
    return "Successfully logged out!";
}

然后我用@RequiresAuthentication 注释对安全资源进行了注释。