REST Service within a Web Application

Asked

Viewed 114 times

2

I have a web application with Spring MVC and there is a need for a client to consume a service, so I created in the same project a resource mapped with Restcontroller, when testing the service using as a client Postman came across a problem, as response came the html of the login page and not the data as json.

In Postman I configured the Authorization of type Basic informed user and password I thought that with this would be all ok

It would not be possible to have a Rest resource in the same application?

or would have to make some specific security configuration?

Updated at 01/02/2019

I spent the day yesterday studying about Spring Security and understood that yes I can create an authentication configuration for my API and when not the other one through the login form. My configuration class however is not yet ok, I have configured two instances of Websecurityconfigureradapter more still not rolling in Postman I get the html of the login form.

@EnableWebSecurity
@ComponentScan(basePackageClasses = AppUserDetailsService.class)
@EnableGlobalMethodSecurity(securedEnabled = true, prePostEnabled = true, 
proxyTargetClass = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //@Autowired
    //private RestAuthenticationEntryPoint authenticationEntryPoint;    
    @Bean
    public static PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

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

        @Autowired
        private UserDetailsService userDetailsService;      

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring()
             .antMatchers("/resources/**");
        }

        @Override
        protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService)
              .passwordEncoder(passwordEncoder());
        }   

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.authorizeRequests()
               .antMatchers("/images/**", "/javascripts/**", "/layout/**", "/stylesheets/**", "/h2-console/**").permitAll()
                 .anyRequest().authenticated()
                 .and()
               .formLogin()
                  .loginPage("/login").permitAll()
                  .and()
                .logout()
                   .logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
                   .and()
                .exceptionHandling()
                .accessDeniedPage("/403")
                .and()
                .sessionManagement()
                .invalidSessionUrl("/login");
            }   

    }

    @Configuration
    @Order(1)
    public static class ApiWebConfigurationAdapter extends WebSecurityConfigurerAdapter {

        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication()
            .withUser("admin")
            .password("admin").roles("ADMIN");
        }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .antMatcher("/api/**")
                .authorizeRequests()
                .anyRequest().hasRole("ADMIN")
            .and()
                .httpBasic()
                .and()
                .csrf().disable();        
        }

        @Bean
        public AuthenticationEntryPoint authenticationEntryPoint(){
            BasicAuthenticationEntryPoint entryPoint = new  BasicAuthenticationEntryPoint();
            entryPoint.setRealmName("admin realm");
            return entryPoint;
        }
    }

Here’s the code for one of the resources I’m exposing

@RestController
@RequestMapping(value = "/api/produtos")
public class ProdutosResources {

    @Autowired
    private ProdutoService service;

    @GetMapping
    public ResponseEntity<List<Produto>> listar(){

        return ResponseEntity.status(HttpStatus.OK).
                body(service.findAll());
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> buscarPorId(@PathVariable Long id){

        Optional<Produto> entidade = service.findById(id);

        return ResponseEntity.status(HttpStatus.OK).body(entidade);
   }    
}
  • What type of html is returned to you? How is your endpoint code Rest?

  • Hello Dherik good afternoon, man when I use a client to test in case the returned html is the one of the login page, this page should only be called when I am accessing the web system, about the code of the endpoint Rest I will update the question with it, and face thanks for the interaction, it may seem that no one else comment already help believe.

  • You would like to have a Json feedback on the login problem, not an html, right? I think the problem is in the configuration you made, putting formLogin.

  • Hello good afternoon Dherik, after these days I could not solve, I know that the normal is to have a Rest Api and the Client to consume, in this case the Web Application came first so I wanted to provide a resource in it, what I simply want is when consuming the /api/products feature to get the json return for it, and note that in Postman I am sending in the Basic type authorizadion header. addHeader("Authorization", "Basic YWR......") so something is not configured correctly in config but I don’t know how.

  • About formLogin Dherik it is because I need a configuration for the Web system, because it is a Web system that has a Rest feature, so the thing is to hit one configuration for Web and another for the API is more difficult, I think the easiest is to create a Rest project just for this feature, a pity then have two Tomcat running on the server.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.