Spring Security HTTP 403 запрещено - PullRequest
0 голосов
/ 18 ноября 2018

Я пытался защитить ресурс rest-api. Однако, похоже, что /auth/** REST-API всегда выбрасывает 403 Forbidden, хотя я разрешил его в конфигурации. см. ниже

@Override
protected void configure(HttpSecurity http) throws Exception {
    logger.info("Setting Endpoint Security.");

    http
        .authorizeRequests()
        .antMatchers("/auth/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .csrf().disable();

}

Это расширение класса WebSecurityConfig WebSecurityConfigurerAdapter

Вот журналы весенней отладки безопасности

2018-11-18 20:14:27.923  INFO 8476 --- [nio-8080-exec-1] Spring Security Debugger                 : 

************************************************************

Request received for POST '/api/v1/auth/login':

org.apache.catalina.connector.RequestFacade@1a183946

servletPath:/api/v1
pathInfo:/auth/login
headers: 
content-type: application/x-www-form-urlencoded
cache-control: no-cache
postman-token: 5bd56859-b8e9-4ebf-977c-452f1bce837e
user-agent: PostmanRuntime/7.4.0
accept: */*
host: localhost:8080
cookie: JSESSIONID=D80F964AA5B53DC7F20ACF59606FA719
accept-encoding: gzip, deflate
content-length: 29
connection: keep-alive


Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  LogoutFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]


************************************************************

и вот ресурс, к которому я пытаюсь получить доступ

@Path("/auth")
@Component
public class Auth {

    private static final Logger logger = LoggerFactory.getLogger(Auth.class);

    @POST
    @Path("/login")
    @Consumes(MediaType.APPLICATION_FORM_URLENCODED)
    public Response login(@FormParam("username") String user, 
                          @FormParam("password") String pass) {
        logger.info("Form-data [username] {}",user);
        logger.info("Form-data [password] {}",pass);
        return Response.ok().build();
    }

    @POST
    @Path("/logout")
    @Produces({ MediaType.APPLICATION_JSON })
    public String logout() {
        return "Login!";
    } 

}

Просто чтобы нам было ясно, я использую Джерси + Spring Boot

Вот Конфиг Джерси

@Configuration
@ApplicationPath("api/v1")
public class JerseyConfig extends ResourceConfig{
    public JerseyConfig() {

    }

    @PostConstruct
    public void setUp() {
        register(Wish.class);
        register(Auth.class);
        register(User.class);
        register(GenericExceptionMapper.class);
    }
}

Теперь, как я понимаю, по методу http в методе configure.

Во-первых, http авторизует запрос, соответствует /auth/** и разрешает его, другие запросы должны быть авторизованы. Однако, когда я пытаюсь запросить http://localhost:8080/api/v1/auth/login, он всегда возвращает 403 Forbidden.

Может кто-нибудь указать на ошибки или, может быть, мое понимание неверно.

1 Ответ

0 голосов
/ 18 ноября 2018

ваша конфигурация разрешает только http://localhost:8080/auth/**, а не http://localhost:8080/api/v1/auth/**,

поэтому измените его на что-то вроде:

.antMatchers("/api/v1/auth/**").permitAll()

должен быть первым в заказе

...