【问题标题】:Securing Rest Service Resources Using Apache Shiro使用 Apache Shiro 保护 Rest 服务资源
【发布时间】:2016-10-08 15:24:58
【问题描述】:

我正在尝试保护我使用 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 中一样?

【问题讨论】:

    标签: java rest shiro


    【解决方案1】:

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

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

    然后在资源类中,我把登录和注销写成了两个服务。

    @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 注解对安全资源进行了注解。

    【讨论】:

      猜你喜欢
      • 2013-12-29
      • 2012-07-07
      • 2013-05-24
      • 2011-01-12
      • 2021-11-16
      • 2012-08-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多