简体   繁体   中英

Spring-Security Basic HTML authentication

I am trying to develop a RESTful webservice for a project I am involved in, and this is all very new to me.

I am trying to add a basic authentication to the webserver (my idea is that every application that uses the service to have credentials). There won't be any web interface to access it, at least at this point. I have been following a tutorial from Spring ( http://spring.io/guides/tutorials/rest/ ), trying to change some things, mostly because I am trying to use the most recent releases of spring.

I am stuck at what apparently seems to be a pretty simple part, that is, only allowing the user to insert a new value to the system with a valid username and password, however for some reason I keep getting the error 403 when I run the particular test.

Here is my configuration:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Autowired
    protected void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
        .withUser("user").password("password").roles("USER");
    }

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

}

And in the test class the error comes from the class that buildindividual() builds the JSON

private ResponseEntity<Individual> buildIndividual() {

     HttpEntity<String> requestEntity = new HttpEntity<String>(
             RestDataFixture.standardIndividualJSON2(),
             getHeaders("user:password"));
     RestTemplate template = new RestTemplate();


     ResponseEntity<Individual> entity = template.postForEntity(
             "http://localhost:8080/aggregators/individuals",
             requestEntity, Individual.class);

     return entity;
 }

 static HttpHeaders getHeaders(String auth) {
     HttpHeaders headers = new HttpHeaders();
     headers.setContentType(MediaType.APPLICATION_JSON);
     headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));

     byte[] codedString = Base64.encode(auth.getBytes());
     headers.add("Authorization", "Basic " + new String(codedString));

     return headers;
 }

The function standardndividualJSON2() just returns a JSON string like: "{ "key" : "12345" , "name" : "StrackOverflow" }" .

I also have a method that tries to create an Individual with a wrong password, and the error I get is also 403 (when it should be 401 if I am not mistaken). That is why I am thinking the configuration might be wrong, but I can't understand why.

Is it any problem with the configuration that I have? It would be really great if anyone could help me.

Thank you for any help!

Edit

Just decided to add the initializer class, maybe the problem is there:

public class WebAppInitializer implements WebApplicationInitializer{

    private static Logger LOG = LoggerFactory.getLogger(WebAppInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext)
        throws ServletException {

        WebApplicationContext rootContext = createRootContext(servletContext);

        configureSpringMvc(servletContext, rootContext);

        configureSpringSecurity(servletContext, rootContext);

    }


    private WebApplicationContext createRootContext(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(CoreConfig.class, SecurityConfig.class);
        rootContext.refresh();

        servletContext.addListener(new ContextLoaderListener(rootContext));
        servletContext.setInitParameter("defaultHtmlEscape", "true");

        return rootContext;
    }

    private void configureSpringMvc(ServletContext servletContext, WebApplicationContext rootContext) {
        AnnotationConfigWebApplicationContext mvcContext = new AnnotationConfigWebApplicationContext();
        mvcContext.register(MVCConfig.class);

        mvcContext.setParent(rootContext);
        ServletRegistration.Dynamic appServlet = servletContext.addServlet(
               "webservice", new DispatcherServlet(mvcContext));
        appServlet.setLoadOnStartup(1);
        Set<String> mappingConflicts = appServlet.addMapping("/");

        if (!mappingConflicts.isEmpty()) {
            for (String s : mappingConflicts) {
                LOG.error("Mapping conflict: " + s);
            }
            throw new IllegalStateException(
                    "'webservice' cannot be mapped to '/'");
        }
    }

    private void configureSpringSecurity(ServletContext servletContext, WebApplicationContext rootContext)   {
        FilterRegistration.Dynamic springSecurity = servletContext.addFilter("springSecurityFilterChain",
            new DelegatingFilterProxy("springSecurityFilterChain", rootContext));
        springSecurity.addMappingForUrlPatterns(null, true, "/*");
      }
}

Edit 2

Solved by disabling the CSRF:

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

Solved by disabling the CSRF:

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

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