在java应用程序中使用apache shiro为Rest服务方法提供授权

时间:2016-12-02 03:24:35

标签: apache rest authorization shiro

在我的简单Web应用程序中,我有两种Web服务方法。一个是storeName(),另一个是viewAllNames()方法。

管理员角色可以访问这两种方法。但是用户角色应该是访问viewAllNames()方法。

我将使用 Apache shiro,maven与基于Web的项目和休息服务。仅为这两种方法提供授权。

我的实际休息网址是:

http://localhost:8080/SimpleRest/simpleservice/store/jackreobert  --> admin only
http://localhost:8080/SimpleRest/simpleservice/viewall/           --> user only

如何配置shiro.ini,web.xml和annotaion / xml。

对于shiro方法,我是否需要将任何其他信息传递到Web服务URL,如何实现此目的。

SimpleService.java

package com.simple.rest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.json.JSONException;

@Path("/simpleservice")
public class SimpleService {
   @Path("/store/{name}")
@GET
@Produces("application/json")
public Response storeName(@PathParam("name") String name) throws JSONException { 
/**
 * Here insert logic 
 */
String result = "Given name: " + name + " successfully stored";
return Respo}nse.status(200).entity(result).build();
}
@Path("/viewall")
@GET
@Produces("application/json")
public Response viewAllNames() throws JSONException { 
   /**
 * Here retrieve logic 
 */
String result = "All names are taken";
return Response.status(200).entity(result).build();
}}

感谢您阅读我的帖子。 帮我, 提前致谢。

1 个答案:

答案 0 :(得分:0)

我的建议是使用权限。使用权限保护您的应用程序资源为角色分配权限并为用户分配角色。

从Shiro 1.4.0-RC2开始,有正式的JAX-RS支持,请看sample

相关问题