简体   繁体   English

使用Apache Shiro保护Rest Service资源

[英]Securing Rest Service Resources Using Apache Shiro

I'm trying to secure my rest services written using dropwizard by Apache Shiro. 我试图保护我使用Apache Shiro的dropwizard编写的其余服务的安全。 First I initialized the security manager in the main method. 首先,我在main方法中初始化了安全管理器。

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

Then I wrote a service for user login. 然后,我编写了一个用于用户登录的服务。

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 .................");
        }
    }

Then I declared a method with some java annotations. 然后,我声明了带有一些Java批注的方法。

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

But when I accessed this resource without logging in, I was successful. 但是,当我不登录而访问此资源时,我就成功了。

What mistake am I doing? 我在做什么错? Or should I add something more? 还是应该添加更多内容? Like in the web.xml? 像在web.xml中一样?

I found this repo very useful. 我发现此回购非常有用。 https://github.com/silb/dropwizard-shiro/tree/release-0.2 . https://github.com/silb/dropwizard-shiro/tree/release-0.2 I followed the instructions given in this. 我遵循了此处给出的说明。 But there is one more thing I added in the configuration file. 但是我在配置文件中添加了另外一件事。

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

Then in the resources class, I wrote login and logout as two services. 然后在资源类中,我将登录和注销写为两个服务。

@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!";
}

And then I annotated the secured resources with @RequiresAuthentication annotation. 然后,我使用@RequiresAuthentication批注对安全资源进行批注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM