доступ запрещен, пользователь анонимный - весенняя загрузка с базовой аутентификацией - PullRequest
0 голосов
/ 22 апреля 2019

Я работаю над демонстрационным приложением, использующим весеннюю загрузку.поэтому идея состоит в том, чтобы создать мыльный веб-сервис и добавить к нему базовую http-аутентификацию.Я следовал некоторым учебникам в сети, но это не помогло мне решить проблему.

Сначала я создал простой веб-сервис мыла и протестировал его с помощью soapui.это работает отлично.Когда я добавил весеннюю защиту в classpath, мне удалось открыть wsdl, предоставленный моим приложением (используя мой браузер и форму входа, предоставленную Spring по умолчанию).но он не смог использовать веб-сервис, используя soapui, даже после добавления заголовков аутентификации.

Вот моя конфигурация приложения.

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web-services</artifactId>
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
  </dependency>
</dependencies>

application.yml

spring:
  security:
    basic:
      enabled: true
    user:
      name: client
      password: password

WebServiceConfig.java

@EnableWs
@Configuration
public class WebServiceConfig extends WsConfigurerAdapter {

@Bean
public ServletRegistrationBean<Servlet> messageDispatcherServlet(ApplicationContext applicationContext) {
    MessageDispatcherServlet servlet = new MessageDispatcherServlet();
    servlet.setApplicationContext(applicationContext);
    return new ServletRegistrationBean<>(servlet, "/ws/library/*");
}

@Bean(name = "books")
public Wsdl11Definition defaultWsdl11Definition() {
    SimpleWsdl11Definition wsdl11Definition = new SimpleWsdl11Definition();
    wsdl11Definition.setWsdl(new ClassPathResource("/book.wsdl"));
    return wsdl11Definition;
}
}

BookEndpoint.java

@Endpoint
public class BookEndpoint {

@PayloadRoot(
        namespace = "http://www.cleverbuilder.com/BookService/",
        localPart = "GetBook")
@ResponsePayload
public GetBookResponse getBook(@RequestPayload GetBook book) {

    ObjectFactory factory = new ObjectFactory();
    GetBookResponse response = factory.createGetBookResponse();
    response.setID("A"+book.getID());
    return response;
}
}

запрос, сгенерированный soapui, выглядит следующим образом:

POST http://localhost:8080/ws/library/BookService HTTP/1.1
Accept-Encoding: gzip,deflate
Content-Type: text/xml;charset=UTF-8
SOAPAction: "http://www.cleverbuilder.com/BookService/GetBook"
Authorization: Basic Y2xpZW50OnBhc3N3b3Jk
Content-Length: 280
Host: localhost:8080
Connection: Keep-Alive
User-Agent: Apache-HttpClient/4.1.1 (java 1.5)
Cookie: JSESSIONID=77EF4FFB2B5A52EC21A47C230624B6DE
Cookie2: $Version=1

<soapenv:Envelope     xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"     xmlns:book="http://www.cleverbuilder.com/BookService/">
<soapenv:Header/>
<soapenv:Body>
  <book:GetBook>
     <ID>85</ID>
  </book:GetBook>
</soapenv:Body>
</soapenv:Envelope>

и ответ сервера:

HTTP/1.1 401 
X-Content-Type-Options: nosniff
X-XSS-Protection: 1; mode=block
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Pragma: no-cache
Expires: 0
X-Frame-Options: DENY
WWW-Authenticate: Basic realm="Realm"
Content-Length: 0
Date: Mon, 22 Apr 2019 09:08:43 GMT

и зарегистрированная ошибка:

Voter: org.springframework.security.web.access.expression.WebExpressionVoter@77114100, returned: -1
ExceptionTranslationFilter     : Access is denied (user is anonymous); redirecting to authentication entry point

org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.1.5.RELEASE.jar:5.1.5.RELEASE]

Может кто-нибудь мне помочь, пожалуйста?

1 Ответ

0 голосов
/ 01 мая 2019

Проблема была в защите crsf.Я смог решить проблему, отключив ее.Вот мой конфиг, который я добавил.

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {


        http
            .csrf()
            .disable();
    }
}
...