Свернуть "ПОЛУЧИТЬ" успешно, но Свернуть "ПОЧТА" безуспешно - PullRequest
1 голос
/ 19 июня 2019

Я использую Spring Boot + Rest + Spring Security (Basic Auth) в качестве моего внутреннего API.Я могу свернуться с помощью GET, но я не могу свернуться с помощью POST.

Я использую application.property + WebSecurityConfigurerAdapter для установки моей безопасности.

Application.property

spring.security.user.name=a
spring.security.user.password=b

WebSecurityConfigurerAdapter

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
    }
}

Контроллер

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

    Logger logger = LoggerFactory.getLogger(ExploreController.class);

    @RequestMapping(value="/exploregethead", method = RequestMethod.GET)
    public HashMap<String, String> exploregethead(HttpServletRequest request, HttpServletResponse response) {
        Enumeration headerNames = request.getHeaderNames();
        HashMap<String, String> map = new HashMap<>();

        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            logger.info(key + " : " + value);
            map.put(key, value);
        }
        return map;
    }

    @RequestMapping(value="/exploreposthead", method = RequestMethod.POST)
    public HashMap<String, String> exploreposthead(HttpServletRequest request, HttpServletResponse response) {
        Enumeration headerNames = request.getHeaderNames();
        HashMap<String, String> map = new HashMap<>();

        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            logger.info(key + " : " + value);
            map.put(key, value);
        }
        return map;
    }
}

для CORS

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        final HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
        response.setHeader("Access-Control-Max-Age", "3600");

        if ("OPTIONS".equalsIgnoreCase(((HttpServletRequest) servletRequest).getMethod())) {
            response.setStatus(HttpServletResponse.SC_OK);
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }

}

Оба остальных запроса аналогичны, за исключением того, что один принимает GET идругой принимает POST.

Я использую curl, чтобы проверить его, и у меня два разных вывода.

curl -i -X GET -H "Authorization:Basic YTpi" http://localhost:8080/api/exploregethead

GET Result

Когда я использую curl для POST API, я сталкиваюсь с ошибкой 401

curl -i -X POST -H "Authorization:Basic YTpi" http://localhost:8080/api/exploreposthead

POST Result

Я пытался использовать оставшийся клиент для POST API, он запрашиваетмне ввести имя пользователя и пароль.Но я ввел имя пользователя 'a' и пароль 'b', он все еще не работает.

Rest Client

Пожалуйста, сообщите часть, которую я сделал неправильно.Спасибо.

1 Ответ

0 голосов
/ 20 июня 2019

Я следую инструкциям ниже. https://www.mkyong.com/spring-boot/spring-rest-spring-security-example/

Спасибо, Мкёнг!

Application.property - удалено

Контроллер - без изменений

CorsFilter - без изменений

WebSecurityConfig - обновление ниже

пакет app.mootor.api;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityJavaConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

        auth.inMemoryAuthentication()
                .withUser("user").password("{noop}password").roles("USER")
                .and()
                .withUser("admin").password("{noop}password").roles("USER", "ADMIN");

    }

    // Secure the endpoins with HTTP Basic authentication
    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
                //HTTP Basic authentication
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/api/**").hasRole("USER")
                .antMatchers(HttpMethod.POST, "/api/**").hasRole("USER")
                .antMatchers(HttpMethod.GET, "/aapi/**").hasRole("ADMIN")
                .antMatchers(HttpMethod.POST, "/aapi/**").hasRole("ADMIN")
                .and()
                .csrf().disable()
                .formLogin().disable();
    }

}

Тест GET

curl localhost:8080/api/explore -u user:password

POST теста

curl localhost:8080/api/exploreposthead -X POST -u user:password
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...