[英]How to add security in java restfull webservices
我是一個寧靜的Web服務提供商。 我的服務被其他一些第三方使用,因此我決定為我的服務增加安全性。 閑逛時,我發現有些站點提供基於角色的訪問權限。 即認證和授權,而不是JAAS。 有其他選擇嗎?
您可以使用以下方法之一保護RESTful Web服務的安全,以支持身份驗證,授權或加密:
您可以像其他Java EE Web應用程序一樣,使用web.xml
部署描述符來保護RESTful Web服務。 有關完整的詳細信息,請參見《 Oracle WebLogic Server編程安全性》中的“開發安全Web應用程序”。
例如,要使用基本身份驗證保護RESTful Web服務,請執行以下步驟:
為您計划保護的每組RESTful資源(URI)定義一個<security-constraint>
。
使用<login-config>
元素定義要使用的身份驗證類型以及將應用安全約束的安全領域。
使用<security-role>
標記定義一個或多個安全角色,並將它們映射到步驟1中定義的安全約束。有關更多信息,請參見《 Oracle WebLogic Server編程安全性》中的“ security-role”。
要啟用加密,請添加<user-data-constraint>
元素,並將<transport-guarantee>
子元素設置為CONFIDENTIAL
。 有關更多信息,請參見《 Oracle WebLogic Server編程安全性》中的“用戶數據約束”。
更多細節,
示例5-1使用基本身份驗證保護RESTful Web服務
<web-app>
<servlet>
<servlet-name>RestServlet</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RestServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<security-constraint>
<web-resource-collection>
<web-resource-name>Orders</web-resource-name>
<url-pattern>/orders</url-pattern>
<http-method>GET</http-method>
<http-method>POST</http-method>
</web-resource-collection>
<auth-constraint>
<role-name>admin</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>default</realm-name>
</login-config>
<security-role>
<role-name>admin</role-name>
</security-role>
</web-app>
示例5-2使用SecurityContext保護RESTful Web服務的安全
package samples.helloworld;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.SecurityContext;
import javax.ws.rs.core.Context;
...
@Path("/stateless")
@Stateless(name = "JaxRSStatelessEJB")
public class StlsEJBApp {
...
@GET
@Produces("text/plain;charset=UTF-8")
@Path("/hello")
public String sayHello(@Context SecurityContext sc) {
if (sc.isUserInRole("admin")) return "Hello World!";
throw new SecurityException("User is unauthorized.");
}
示例5-3使用SecurityContext保護RESTful Web服務的安全
package samples.helloworld;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.annotation.Security.RolesAllowed;
@Path("/helloworld")
@RolesAllowed({"ADMIN", "ORG1"})
public class helloWorld {
@GET
@Path("sayHello")
@Produces("text/plain")
@RolesAllows("ADMIN")
public String sayHello() {
return "Hello World!";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.