【问题标题】:Spring boot and Security: accessing secured URL from android app.Spring boot 和 Security:从 android 应用程序访问安全 URL。
【发布时间】:2018-09-06 17:22:41
【问题描述】:

我为表单登录开发了一个简单的 Spring boot 和 Spring Security,配置如下

@Configuration

@EnableWebSecurity

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Bean
    public BCryptPasswordEncoder bCryptPasswordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                    .antMatchers("/resources/**", "/registration").permitAll()
                    .anyRequest().authenticated()
                    .and()
                .formLogin()
                    .loginPage("/login")
                    .permitAll()
                    .and()
                .logout()
                    .permitAll();

        http.csrf().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder());
    }

我还创建了自定义 userDetailsS​​ervice 实现来获取用户。

现在,当我使用登录表单从网页登录时,我能够成功登录并能够访问受保护的端点(我也能够在后续响应中看到 JSESSIONID。

但是,当我尝试使用带有 url 的 httpPost:http://localhost:9090/login 通过不同的服务(Android 应用程序)登录时,我可以看到用户已通过身份验证。 但我随后无法从 android 应用程序访问安全端点。响应返回一个HTML 字符串(登录页面数据)。

我也看不到回复中的JSESSIONID

总的来说,我的配置在网页上运行良好,但无法从其他 api 上运行。

【问题讨论】:

    标签: web-services spring-boot spring-security


    【解决方案1】:

    当您使用网页登录表单时它可以工作,因为您的 UI 和服务器在同一个域中。当 Spring Security 对用户进行身份验证时,我相信它会在 cookie 标头中添加一个会话 ID,因此它能够在您登录后对每个请求进行身份验证。当从另一个域访问您的 Spring API 时,在本例中是您的 Android 应用程序,它不再位于同一个域中,因此 Spring Security 不会将会话 ID 添加到 cookie 标头中。所以要做你想做的事,我相信你必须编写自己的身份验证过滤器来向请求添加 cookie 或标头。这是一个使用 JSON Web Tokens 使用 spring boot 对 api 进行身份验证的链接。 https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/

    【讨论】:

      猜你喜欢
      • 2016-12-27
      • 2014-05-14
      • 2015-05-27
      • 2019-10-09
      • 1970-01-01
      • 1970-01-01
      • 2014-07-16
      • 2019-06-25
      相关资源
      最近更新 更多