gpt4 book ai didi

java - 使用 Apache Shiro 保护 Rest 服务资源

转载 作者:行者123 更新时间:2023-12-01 09:49:25 25 4
gpt4 key购买 nike

我正在尝试保护由 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 注释来注释 protected 资源。

关于java - 使用 Apache Shiro 保护 Rest 服务资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37701155/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com