我为 REST 应用程序启用了 Spring Security,但在使用curl 时未获得授权。
Security.xml
<sec:http use-expressions="true" entry-point-ref="restAuthenticationEntryPoint">
<sec:intercept-url pattern="/rest/**" access="hasRole('ROLE_USER')" />
<sec:form-login authentication-success-handler-ref="mySuccessHandler" />
<sec:logout />
</sec:http>
<beans:bean id="mySuccessHandler" class="net.himalay.security.MySavedRequestAwareAuthenticationSuccessHandler" />
<sec:authentication-manager alias="authenticationManager">
<sec:authentication-provider>
<sec:user-service>
<sec:user name="temporary" password="temporary" authorities="ROLE_ADMIN" />
<sec:user name="user" password="userPass" authorities="ROLE_USER" />
</sec:user-service>
</sec:authentication-provider>
</sec:authentication-manager>
自定义入口点
@Component
public final class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
private static final Logger LOG = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class);
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException {
LOG.info("---------RestAuthenticationEntryPoint----------");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}
}
Controller
@Controller
@RequestMapping("rest")
public class MultitenantController {
@Autowired
private MultitenantService service;
@RequestMapping(value = "/user/{id}", method = RequestMethod.GET)
@ResponseBody
public User getUserInfo(@PathVariable Long id) {
return service.getUser(id);
}
@RequestMapping(value = "/user", method = RequestMethod.GET)
@ResponseBody
public List<User> getCustomers() {
return service.getUsers();
}
@RequestMapping(value = "/user/{id}/todo", method = RequestMethod.GET)
@ResponseBody
public List<TodoItem> getTransactions(@PathVariable Long id) {
HttpHeaders headers = addAccessControllAllowOrigin();
return getUserInfo(id).getTodoItems();
}
}
$curl -i -X -u user:userPass http://localhost:8080/mt-rest/rest/user/1/todo
curl: (6) Could not resolve host: user
HTTP/1.1 401 Unauthorized
Server: Apache-Coyote/1.1
Set-Cookie: JSESSIONID=ADA11C09484E658C38D8385CABA0CFAE; Path=/mt-rest/; HttpOnly
Content-Type: text/html;charset=utf-8
Content-Language: en
Content-Length: 975
Date: Fri, 31 Jan 2014 17:14:45 GMT
从 security.xml 中取出安全模式后,它工作正常。我到底错过了什么?
最佳答案
您只定义了一个表单登录模块。我相信您还需要指定http-basic。例如:
<sec:http-basic />
关于java - REST 的 Spring Security,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21488724/