我对Spring + Spring安全性(都是3.2.8版本)有问题。嗯,我有一个REST服务,它以xml格式返回应用程序中存储的所有设备。我就是这么叫它的:
{baseUrl}/service/equipment这就是方法签名,其中返回一个EquipmentExchangeSet实体。该实体使用java绑定注释。
@RequestMapping(value = "equipment", method = RequestMethod.GET, headers = XML_JSON_HEADERS, produces = {
XML, JSON })
@ResponseBody
public EquipmentExchangeSet getEquipment() {
}我现在要做的是接受该文件并使用xsl样式处理它,以便稍后获得一个输出HTML或PDF。所以我实现了这个Spring服务:
@RequestMapping(value = "/equipment/format/html", method = RequestMethod.GET, produces = { MediaType.TEXT_HTML_VALUE })
@ResponseBody
public String getEquipmentHTML() throws TransformerException, IOException {
/* Create a TransformerFactory object */
TransformerFactory tFactory = TransformerFactory.newInstance();
ByteArrayOutputStream os = new ByteArrayOutputStream();
/* Get the incoming XSLT file */
Transformer transformer = tFactory.newTransformer(new StreamSource(
"equipment.xsl"));
URL xmlServiceUrl = new URL(
"http://localhost:8080/myapp/service/equipment/");
/* Get the XML file and apply the XSLT transformation to convert to HTML */
transformer.transform(new StreamSource(xmlServiceUrl.openStream()),
new StreamResult(os));
return os.toString();
}它访问第一个服务的url,获取xml内容并对其进行处理以获得时髦的输出HTML内容。但是,当删除Spring安全约束时,一切都很有魅力,但是,我需要它们只允许记录在案的用户访问服务。我的spring安全配置就是这样为web服务配置的:
<http entry-point-ref="restAuthenticationEntryPoint" pattern="/service/**"
use-expressions="true">
<intercept-url pattern="/service/**" access="isAuthenticated()" />
<form-login authentication-success-handler-ref="restSuccessHandler"
authentication-failure-handler-ref="restFailureHandler"
login-processing-url="/service/j_spring_security_check" />
<logout />
</http>此配置仅允许已通过身份验证的用户进行访问。但是,当我试图从Spring服务本身发出请求时,我会得到401 (未授权)代码。是否有一种方法可以从服务中检索凭据,或者以相同的上下文执行该请求?
发布于 2014-06-24 07:39:13
我将重新设计Controller方法,并拆分在服务中生成XML的实际逻辑。这样,您就可以在另一个控制器中注入服务并调用它,而不必对同一个应用程序实际提出额外的请求。实际上,像localhost:8080/...这样的内部请求是错误的做法,因为一旦部署到不同的端口,该代码就会中断。
@Service
public class EquipmentService {
public InputStream getEquipmentAsXml(){
....
}
}
@Controller
public class EquipmentController {
@Autowired
private EquipmentService equipmentService;
@RequestMapping(value = "/equipment/format/html", method = RequestMethod.GET, produces = { MediaType.TEXT_HTML_VALUE })
@ResponseBody
public String getEquipmentHTML() throws TransformerException, IOException {
/* Create a TransformerFactory object */
TransformerFactory tFactory = TransformerFactory.newInstance();
ByteArrayOutputStream os = new ByteArrayOutputStream();
/* Get the incoming XSLT file */
Transformer transformer = tFactory.newTransformer(new StreamSource(
"equipment.xsl"));
transformer.transform(new StreamSource(equipmentService.getEquipmentAsXml()),
new StreamResult(os));
return os.toString();
}
}这样,您不仅可以绕过身份验证的整个问题,而且还可以使代码更可重用,并消除bug。
https://stackoverflow.com/questions/24324233
复制相似问题