如何通过 json 响应/请求使用具有 Spring 安全性的 Android/IOs 应用程序对用户进行身份验证

sho*_*aib 2 spring android spring-mvc spring-security

我在 spring MVC rest full web 服务中有服务器端(后端)代码。现在我有一个应用程序(android/IOs),用户可以在其中注册自己以访问不同的功能,并且通过 JSON 响应和请求一切正常。但现在我想使用应用程序中的登录字段对用户进行身份验证。如何验证用户身份。

到目前为止,我们可以通过使用 spring 安全性的表单身份验证来进行搜索。但是移动应用程序没有表单,而且我将获得的登录凭据是 JSON 格式,然后身份验证将如何发生。那么,如何使用 JSON 格式的数据使用 Spring Security 对来自 android/IOs 应用程序的用户进行身份验证

Rob*_*nch 5

我的建议是查看Spring Session REST 指南。以下是重点。

我建议使用 HTTP Basic 提交您的凭据。这可以通过以下 Java 配置在 spring security 中完成:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    // @formatter:off
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .anyRequest().authenticated()
                .and()
            .requestCache()
                .requestCache(new NullRequestCache())
                .and()
            .httpBasic();
    }
    // @formatter:on

    // @formatter:off
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
    // @formatter:on
}
Run Code Online (Sandbox Code Playgroud)

然后通过休息端点公开您的用户对象

// NOTE could replace Principal w/ Spring Security's Authentication object too
// Just be careful you don't expose the password over REST!
@RequestMapping(value="/user",produces = "application/json")
public Map<String,String> helloUser(Principal principal) {
    HashMap<String,String> result = new HashMap<String,String>();
    result.put("username", principal.getName());
    return result;
}
Run Code Online (Sandbox Code Playgroud)

现在您可以使用基本身份验证提交用户名/密码。例如卷曲:

curl -v http://localhost:8080/ -u user:password

HTTP/1.1 200 OK
...
Set-Cookie: JSESSIONID=0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3; ...

{"username":"user"}
Run Code Online (Sandbox Code Playgroud)

问题是 cookie 确实是为浏览器设计的。它还使您的应用程序集群变得困难。进入春季会议。

Spring Session 允许您使用 Redis 或其他任意数据存储轻松支持您的 HttpSession。要使用它,首先创建 Spring Session Filter:

@Configuration
@EnableRedisHttpSession 
public class HttpSessionConfig {

        // this will hit redis on localhost and the default port
        @Bean
        public JedisConnectionFactory connectionFactory() {
                JedisConnectionFactory factory = new JedisConnectionFactory();  
                // ... customize ...
                return factory;
        }

        // override the default of using cookies and instead use headers
        @Bean
        public HttpSessionStrategy httpSessionStrategy() {
                return new HeaderHttpSessionStrategy(); 
        }
}
Run Code Online (Sandbox Code Playgroud)

然后确保将 Spring Session 的 SessionRepositoryFilter 添加到您的容器中。例如,在 AbstractAnnotationConfigDispatcherServletInitializer 的子类中,确保您的配置加载在根上下文中:

@Override
protected Class<?>[] getRootConfigClasses() {
    return new Class[] {SecurityConfig.class, HttpSessionConfig.class};
}
Run Code Online (Sandbox Code Playgroud)

接下来,创建一个 的子类AbstractHttpSessionApplicationInitializerSessionRepositoryFilter为所有请求注册。例如:

public class Initializer extends AbstractHttpSessionApplicationInitializer {

}
Run Code Online (Sandbox Code Playgroud)

现在你可以这样做:

curl -v http://localhost:8080/ -u user:password

HTTP/1.1 200 OK
...
x-auth-token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3; ...

{"username":"user"}
Run Code Online (Sandbox Code Playgroud)

标头现在可用于发出其他请求:

curl -v http://localhost:8080/messages/ -H "x-auth-token: 0dc1f6e1-c7f1-41ac-8ce2-32b6b3e57aa3"
Run Code Online (Sandbox Code Playgroud)

有关其他信息(包括基于 XML 的配置),请参阅Spring Session 文档