预授权返回状态码500,而不是401

时间:2019-02-09 10:02:11

标签: spring spring-security authorization

我正在使用JWT Spring安全性,我做了一个简单的示例,其中用户/管理员单击2按钮来检查预授权是否正常工作。我知道失败时应通过身份验证入口点处理“ @PreAuthorize”,但与其返回状态401,不返回状态401,而是返回状态500。

enter image description here

我的WebSecurityConfig:

@Override
protected void configure(HttpSecurity httpSecurity) throws Exception {
    httpSecurity
        // we don't need CSRF because our token is invulnerable
        .csrf().disable()

        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

        // don't create session
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

        .authorizeRequests()

        // Un-secure H2 Database
        .antMatchers("/h2-console/**/**").permitAll()

        .antMatchers("/auth/**").permitAll()
        .anyRequest().authenticated();

   httpSecurity
        .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

    // disable page caching
    httpSecurity
        .headers()
        .frameOptions().sameOrigin()  // required to set for H2 else H2 Console will be blank.
        .cacheControl();
}

@Override
public void configure(WebSecurity web) throws Exception {
    // AuthenticationTokenFilter will ignore the below paths
    web
        .ignoring()
        .antMatchers(
            HttpMethod.POST,
            authenticationPath
        )

        // allow anonymous resource requests
        .and()
        .ignoring()
        .antMatchers(
            HttpMethod.GET,
            "/",
            "/**",
            "/*.html",
            "/favicon.ico",
            "/**/*.html",
            "/**/*.css",
            "/**/*.js"
        )

        // Un-secure H2 Database (for testing purposes, H2 console shouldn't be unprotected in production)
        .and()
        .ignoring()
        .antMatchers("/h2-console/**/**");
}

AuthenticationEntryPoint

@Override
public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException authException) throws IOException {
    // This is invoked when user tries to access a secured REST resource without supplying any credentials
    // We should just send a 401 Unauthorized response because there is no 'login page' to redirect to
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
}

我的控制器:

@RequestMapping(value = "/testa", method = RequestMethod.GET)
public ResponseEntity<?> getProtectedGreetinga() {
    return ResponseEntity.ok("THIS IS A NORMAL USER!!");
}

@RequestMapping(value = "/testb", method = RequestMethod.GET)
@PreAuthorize("hasRole('ADMIN')")
public ResponseEntity<?> getProtectedGreetingb() {
    return ResponseEntity.ok("THIS IS AN ADMIN!!");
}

从上图可以看到我的访问被拒绝,但是为什么我的状态为500?这是否意味着我映射错误?

0 个答案:

没有答案
相关问题