Android设备针对Spring Security Rest API进行身份验证

时间:2015-01-03 13:14:50

标签: java android spring rest spring-mvc

我有一个带有REST-API的SPRING后端。它由用户名和密码保护。当我用我的电脑浏览器打开它时,首先显示登录屏幕,在我添加凭据后,我可以访问api fluendly。

当我通过Android APP尝试相同的操作时,我每次都会进入登录界面。要在Android端进行身份验证,请使用默认可访问的REST API请求。 内部Android应用程序浏览器与存储会话cookie不兼容吗?每次创建新的HTTP会话时。我正在使用Volley来提出请求

弹簧security.xml文件

    <http auto-config="true" use-expressions="true">
    <intercept-url pattern="/api/user/login" access="permitAll" /> <!--IS_AUTHENTICATED_ANONYMOUSLY-->
    <intercept-url pattern="/admin/**" access="hasAnyRole('ROLE_ADMIN','ROLE_GROUP_LEADER')" />
    <intercept-url pattern="/api/**" access="hasAnyRole('ROLE_USER','ROLE_ADMIN','ROLE_GROUP_LEADER')" />

    <form-login 
        login-page="/login" 
        default-target-url="/admin" 
        authentication-failure-url="/login?error" 
        username-parameter="username"
        password-parameter="password"    
    />
    <access-denied-handler error-page="/403" />
    <logout logout-success-url="/login?logout" />
</http>


<authentication-manager alias="authManager">
   <authentication-provider >

        <password-encoder ref="encoder" />

        <jdbc-user-service data-source-ref="dataSource"
      users-by-username-query=
        "select username,password, enabled from user where username=?"
      authorities-by-username-query=
        "select username, name as role from role r,user u where u.role_id = r.id and username =? " />
    </authentication-provider>
</authentication-manager>

来自其余api的控制器中的代码

    UserDetails userDetails = userDetailsSvc.loadUserByUsername(user.getUsername());

    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userDetails, "123",userDetails.getAuthorities());

    Authentication authentication = authManager.authenticate(token);

    log.debug("Logging in with [{}]", authentication.getPrincipal());
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);
    HttpSession session = request.getSession(true);
    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);

Spring Security DEBUG

************************************************************

Request received for POST '/api/user/create':

org.apache.catalina.connector.RequestFacade@36dc8ced

servletPath:/api/user/create
pathInfo:null
headers: 
if-modified-since: Sat, 03 Jan 2015 12:35:50 GMT+00:00
content-type: application/json; charset=utf-8
user-agent: Dalvik/1.6.0 (Linux; U; Android 4.0.4; GT-P7100 Build/IMM76D)
host: 192.168.178.36:8088
connection: Keep-Alive
accept-encoding: gzip
content-length: 124


Security filter chain: [
  SecurityContextPersistenceFilter
  WebAsyncManagerIntegrationFilter
  LogoutFilter
  UsernamePasswordAuthenticationFilter
  BasicAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


2015-01-03 13:53:46 INFO  Spring Security Debugger:39 - 

************************************************************

New HTTP session created: A430DD754F7F6E466D07B10D1DDCCEF7

Call stack: 

    at org.springframework.security.web.debug.Logger.info(Logger.java:29)
    at org.springframework.security.web.debug.DebugRequestWrapper.getSession(DebugFilter.java:144)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
    at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:238)
    at org.springframework.security.web.savedrequest.HttpSessionRequestCache.saveRequest(HttpSessionRequestCache.java:40)
    at org.springframework.security.web.access.ExceptionTranslationFilter.sendStartAuthentication(ExceptionTranslationFilter.java:184)
    at org.springframework.security.web.access.ExceptionTranslationFilter.handleSpringSecurityException(ExceptionTranslationFilter.java:168)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:131)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
    at org.springframework.security.web.debug.DebugFilter.invokeWithWrappedRequest(DebugFilter.java:70)
    at org.springframework.security.web.debug.DebugFilter.doFilter(DebugFilter.java:59)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:74)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:516)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1015)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:652)
    at org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1575)
    at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1533)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)


************************************************************


2015-01-03 13:53:46 INFO  Spring Security Debugger:39 - 

************************************************************

Request received for GET '/login':

org.apache.catalina.connector.RequestFacade@36dc8ced

servletPath:/login
pathInfo:null
headers: 
if-modified-since: Sat, 03 Jan 2015 12:35:50 GMT+00:00
content-type: application/json; charset=utf-8
user-agent: Dalvik/1.6.0 (Linux; U; Android 4.0.4; GT-P7100 Build/IMM76D)
host: 192.168.178.36:8088
connection: Keep-Alive
accept-encoding: gzip


Security filter chain: [
  SecurityContextPersistenceFilter
  WebAsyncManagerIntegrationFilter
  LogoutFilter
  UsernamePasswordAuthenticationFilter
  BasicAuthenticationFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************


MonitorFilter::WARNING: the monitor filter must be the first filter in the chain.

凌空

    CookieManager manager = new CookieManager();
    CookieHandler.setDefault( manager  );

    mQueue = Volley.newRequestQueue(context);

2 个答案:

答案 0 :(得分:9)

我怀疑问题可能是你正在实现自己的自定义身份验证控制器端点而不是使用完整的spring-security链。

根据你的xml配置,仍然可以在所有请求上调用普通的过滤器链,但是只需在控制器中调用authenticate()方法就可以了,而不是其余的身份验证成功处理程序。您实际上不会使用您的adhoc控制器身份验证设置响应cookie

测试这个的最简单方法是直接卷曲网址,或者使用postman(用于rest apis的chrome插件)来测试api身份验证endpoit并查看是否在响应中设置了任何cookeis。

如果您可以控制服务器端代码(例如,您可以更改它而不只是在Android应用程序上工作),请注意以下几点:

  • 我会避免使用自定义身份验证端点并尝试手动推送安全内容 - Spring安全性确实很好用。

  • 假设您不想使用oauth以及API解决方案的复杂性,请查看Google's recommended approach for securing APIs for mobile apps。它与您采用的方法类似,但是对于登录,您只需在Android应用程序中嵌入Web视图并使用它来让用户直接登录标准的spring安全表单(因此可以利用Spring-security默认行为,例如cookies等),然后在应用程序中,您只需从Web响应中获取用户令牌,然后将其存储 - 然后可以将其用作所有API请求作为请求标头(因此用户不必继续登录移动应用程序)

我在这里写了这个方法的概述:

Securing your API for mobile access

并在此处整合了一个Spring安全实现。

Securing your mobile API with Spring Security

答案 1 :(得分:0)

尝试了你的建议并让它发挥作用。

在我检查后,后端传输了所需的cookie,我调整了凌空,以便它存储传输的cookie并在每次请求后重新发送它作为令牌。 cookie存储在首选项中。

public GsonRequest(...)
  .....

if(PreferencesManager.getInstance().getSessionCookie()!=null)
       this.headers.put("Cookie", "JSESSIONID="+ PreferencesManager.getInstance().getSessionCookie());

@Override
    protected Response<T> parseNetworkResponse(NetworkResponse response) {
            String cookie = MyApp.get().checkSessionCookie(response.headers);
            PreferencesManager.getInstance().setSessionCookie(cookie);
               .....
    }

如vmirinov在go here上所说的滑动修改

public final String checkSessionCookie(Map<String, String> headers) {
        if (headers.containsKey(SET_COOKIE_KEY)
                && headers.get(SET_COOKIE_KEY).toLowerCase().contains(SESSION_COOKIE)) {
            String cookie = headers.get(SET_COOKIE_KEY);
            if (cookie.length() > 0) {
                String[] splitCookie = cookie.split(";");
                String[] splitSessionId = splitCookie[0].split("=");
                cookie = splitSessionId[1];
                SharedPreferences.Editor prefEditor = _preferences.edit();
                prefEditor.putString(SESSION_COOKIE, cookie);
                prefEditor.commit();
                return cookie;
            }
        }
        return "";
    }