繁体   English   中英

使用Spring Security保护REST API

[英]Securing REST API with Spring Security

我正在尝试为我的Spring应用程序实现REST API。 由于有些资源可能并非所有人都可以访问,因此我需要一个安全层。

在此应用程序中,我已经在使用Spring Security(可以很好地工作)保护我的Web应用程序。

我在spring-security.xml添加了以下http配置:

<http pattern = "/api/**" use-expressions = "true" disable-url-rewriting = "true">
    <http-basic />
</http>

因此,我假设对以api/开头的URL的所有请求都将得到保护。

问题是我无需任何身份验证即可访问我的安全方法。 但是,如果我使用REST客户端访问它,则会收到此错误:

message: Full authentication is required to access this resource
description: This request requires HTTP authentication.

我不知道该如何进行。 使用Spring Security保护REST API的最佳方法是什么?

如果您在应用程序中使用Spring Security,则您的Spring配置文件之一中可能已经有一个<http>部分。 您可以使用此部分来保护您的REST API。

<http>不能单独保护任何内容。 您必须在其中添加<intercept-url>规则:

<intercept-url pattern="/api/**" access="hasRole('ROLE_USER')" />

Spring的官方网站上有一个tuto。 稍微复杂一点: 官方Spring Tuto

只需使用Spring Security。 <http>标记中添加: <security:intercept-url pattern="your url" access="hasAnyRole('Your_User_Role1', 'Your_User_Role2')" />
或尝试使用注释 在您的spring-config.xml中启用安全注释:
<security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled"/> @PreAuthorize <security:global-method-security jsr250-annotations="enabled" pre-post-annotations="enabled" secured-annotations="enabled"/>并在Controller中添加@PreAuthorize

@PreAuthorize("hasAnyRole('Your_User_Role1', 'Your_User_Role2')")
@RequestMapping(value = "/address_planing/load_employee_info")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM