簡體   English   中英

使用Apache Shiro保護Rest Service資源

[英]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中一樣?

我發現此回購非常有用。 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批注對安全資源進行批注。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM