简体   繁体   中英

Spring security with Html pages and Rest web service authentication

I'm using Spring security and database login in my application (in the future I'll have to implement LDAP authentication). Through web all work right, but now when I call web services from external (I have some web service for internal javascript and some for external calls) I receive the HTML code of login page. It's correct, but now how can I make REST call? I have to protect them, I thought to use a token or username and password for each web services call, but how can I set username and password in REST call? For example with postman. Then I will set the credentials also in

restTemplate.setRequestFactory(requestFactory);
responseEntity  = restTemplate.getForEntity(serverIp + "ATS/client/file/?filePath={filePath}", byte[].class, filePath); 

and in

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
ContentBody cbFile = new FileBody(file);
ContentBody cbPath= new StringBody(toStorePath,ContentType.TEXT_PLAIN);
builder.addPart("file", cbFile);
builder.addPart("toStorePath",cbPath);
httppost.setEntity(builder.build());
CloseableHttpResponse httpResponse = httpClient.execute(httppost);
HttpEntity resEntity = httpResponse.getEntity();

On the web I have even the roles for the user, maybe I'll have to use them also for the web services. Thanks for the advices. Regards UPDATE: As @Gergely Bacso advices me, I have updated my code, but now I have the opposite problems: When I call web services they return all the information without username and password. This is security config:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, proxyTargetClass = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("userDetailsService")
    UserDetailsService userDetailsService;

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

    @Bean
    public PasswordEncoder passwordEncoder(){
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        return encoder;
    }

    @Configuration
    @Order(1)
    public static class ApiWebSecurityConfig extends WebSecurityConfigurerAdapter{
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .antMatcher("/client/**")
                    .authorizeRequests()
                        .anyRequest().authenticated()
                        .and()
                    .httpBasic();
        }
    }

    @Configuration
    @Order(2)
    public static class FormWebSecurityConfig extends WebSecurityConfigurerAdapter{

        @Override
        public void configure(WebSecurity web) throws Exception {
            web
                    //Spring Security ignores request to static resources such as CSS or JS files.
                    .ignoring()
                        .antMatchers("/static/**");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .authorizeRequests() //Authorize Request Configuration
                        //.antMatchers("/", "/register").permitAll()
                       // .antMatchers("/admin/**").hasRole("ADMIN")
                        .anyRequest().authenticated()
                        .and() //Login Form configuration for all others
                    .formLogin()
                        .loginPage("/login").permitAll();
        }
    }

}

There was a similar question asked only a few days ago:

Securing REST service with Spring Security

The important part is that:

In case you want to secure something that is accessed programatically (for example a REST service being called by another program) then you should not use form-based authentication.

What you need is something much more suitable for the job. Like an HTTP-basic auth. Form-based login methods are more suited to use cases where users can enter their username/password.

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