简体   繁体   中英

How to authenticate in Spring Boot using Backbone and REST?

I am trying to wrap my head around the high level concepts and I'm just starting to learn Spring Security at the same time. While eventually I want to support "Login via Google" (and other social media), for now I am just prototyping so all I want is a quick way to add user support to my app for testing purposes.

I am using Spring Boot and Backbone. After the initial page load, all requests are made via REST through Backbone. So far, I haven't done much with Spring Security, but if I add this config:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
DataSource dataSource;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth
        .jdbcAuthentication()
            .dataSource(dataSource)             
            .usersByUsernameQuery("SELECT username, password,enabled FROM users WHERE username=?")               
            .authoritiesByUsernameQuery("SELECT username, authority FROM authorities WHERE username = ?")                
            .rolePrefix("ROLE_");
}

Then when I go to my app I get a login form and if I enter a valid user, I can access the app which is a great start.

But when Backbone tries a REST call it doesn't work. I just get a 403 - Forbidden .

I think I understand why this is happening at a high-level. I assume I need to send user details with every request to the server. But I'm not sure how that works with Spring Security and I can't find any documentation to explain it.

I would rather follow Spring Security guidelines here rather than attempt to roll my own solution and re-invent the wheel.

Is there a idiomatic way to do this in Spring Security?

The browser should be sending session cookies with its requests, so once you have authenticated it should work fine. The fact that you have a 403 response (not a 401) suggests that it is working. Maybe you are asking for a resource you are not permitted to see, or maybe it's something else. If you crank up the debug logging on org.springframework.security it should tell you what's going on.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM