Spring 安全 HTTP 403 禁止访问

Spring Security HTTP 403 Forbidden

我一直在尝试获取 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();

}

这是在 WebSecurityConfigclass 上扩展 WebSecurityConfigurerAdapter

这里是 spring 安全调试日志

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!";
    } 

}

让我们清楚一点,我正在使用 Jersey + Spring Boot

这是 Jersey 配置

@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);
    }
}

现在,正如我对 configure 方法中的 http 方法系列的理解。

首先http授权请求,匹配/auth/**允许,其他请求需要授权。但是,当我尝试请求 http://localhost:8080/api/v1/auth/login 时,它总是 returns 403 Forbidden

谁能指出错误或者我的理解不正确。

您的配置只允许 http://localhost:8080/auth/** not http://localhost:8080/api/v1/auth/**,

所以将其更改为:

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

它应该是顺序中的第一个