Spring启动和安全:从Android应用程序访问安全URL。

问题描述 投票:0回答:1

我已经使用以下配置为表单登录开发了一个简单的Spring启动和弹簧安全性

@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实现来获取用户。

现在,当我使用登录表单从网页登录时,我能够成功登录并能够访问安全的endPoints(我能够在后续响应中看到JSESSIONID)。

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

我也无法在回复中看到JSESSIONID

总的来说,我的配置适用于网页,但无法从其他API获得它。

web-services spring-boot spring-security
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.