Arpit Singh
Arpit Singh

Reputation: 95

Spring boot and Security: accessing secured URL from android app.

I have developed a simple Spring boot and spring security for form login with the below configuration

@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());
    }

I have also created custom userDetailsService Implementation to get the user.

Now, When I login in from a web page using a login form, I am able to login successfully and able to access secured endPoints as well(I am able to see JSESSIONID as well in subsequent response.

But when I try to login via a different service(An Android app) using httpPost with url : http://localhost:9090/login, I can see that the user is authenticated. But I am then unable to access the secured endPoints from the android app. The response returns back a HTML string(The login page data).

I can also not see the JSESSIONID in the response.

Overall, My configuration is working fine for web pages, but unable to get it worked from other api's.

Upvotes: 0

Views: 323

Answers (1)

Jefferson Vivanco
Jefferson Vivanco

Reputation: 21

It works when you use the web page login form because your UI and server are in the same domain. When Spring Security authenticates a user I believe it adds a session id to the cookie header so it is able to authenticate every request after you login. When hitting your Spring API from another domain, in this case your Android App, it is no longer in the same domain, so Spring Security won't add the session id to the cookie header. So to do what you want to do I believe you have to write your own authentication filter to add a cookie or header to the request. Here is a link that uses JSON Web Tokens to authenticate an api using spring boot. https://auth0.com/blog/implementing-jwt-authentication-on-spring-boot/

Upvotes: 1

Related Questions