问题描述
我正在尝试保护我使用 Apache Shiro 的 dropwizard 编写的休息服务.首先我在main方法中初始化了安全管理器.
I'm trying to secure my rest services written using dropwizard by Apache Shiro. First I initialized the security manager in the main method.
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 .................");
}
}
然后我声明了一个带有一些 java 注释的方法.
Then I declared a method with some java annotations.
@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.
我做错了什么?或者我应该添加更多的东西?就像在 web.xml 中一样?
What mistake am I doing? Or should I add something more? Like in the web.xml?
推荐答案
我发现这个 repo 非常有用.https://github.com/silb/dropwizard-shiro/tree/release-0.2.我按照this中给出的说明进行操作.但是我在配置文件中添加了另外一件事.
I found this repo very useful. 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!";
}
然后我用@RequiresAuthentication 注释对受保护的资源进行了注释.
And then I annotated the secured resources with @RequiresAuthentication annotation.
这篇关于使用 Apache Shiro 保护 Rest 服务资源的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!