且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Android的Spring Security调用REST Web服务

更新时间:2022-10-14 22:34:41

Spring安全 支持基本身份验证和基于表单的身份验证(嵌入用户名/ URL中的密码。)



REST服务通常在每个请求上进行身份验证,通常不是通过会话进行身份验证。默认的spring安全认证(假设您使用的是3.x)应查找基本认证参数或表单参数(j_username和j_password)(格式为 http://you.com/rest_service?j_username=xyz&j_password=abc )。



手动将j_username / j_password添加到URL上,将它们添加为post参数(我相信),或者设置基本身份验证用户名/密码都应该可以根据默认的Spring Security拦截器验证REST服务。 / p>

我会承认我没有在REST服务上试过这个,虽然我确实清楚地记得在文档中读到这一点,因为我对春天的基本页面登录做了同样的事情安全最近。免责声明。


I'm hosting a REST web service in a Grails application, using Spring Security, i.e.:

@Secured(['IS_AUTHENTICATED_REMEMBERED'])
def save = {
    println "Save Ride REST WebMethod called"
}

I'm calling it from an Android app. (Calling the unsecured service works just fine.)

To call the service, I'm manually building up a request (HttpUriRequest) and executing it with an HttpClient.

I'm wondering what the best practices are, and how to implement them... Specifically, should I:

  1. Perform a login once, to retrieve a JSESSION_ID, then add a header containing it into the HttpUriRequest for each subsequent request?
  2. Or (not sure how I would even do this) include the login and password directly on each request, foregoing the cookie/server-side session

I think I can get option 1 working, but am not sure if Spring Security permits (2), if that's the way to go... Thanks!

--also, there isn't any library I'm missing that would do all this for me is there? :)

Spring security does support both basic authentication and form based authentication (embedding the username/password in the URL).

A REST service is generally authenticated on each and every request, not normally by a session. The default spring security authentication (assuming you're on 3.x) should look for basic authentication parameters or form parameters (j_username and j_password) (in the form http://you.com/rest_service?j_username=xyz&j_password=abc).

Manually tacking the j_username/j_password onto the URL, adding them as post parameters (I believe), or setting the basic authentication username/password should all work to authenticate a REST service against the default Spring Security interceptors, right out of the box.

I will admit that I haven't tried this on REST services, though I do clearly recall reading exactly this in the docs as I did the same for basic page logins on spring security recently. Disclaimer over.