簡體   English   中英

未經授權的錯誤 401 返回內部服務器錯誤 500

[英]Unauthorised error 401 returns internal server error 500

我已經使用 spring ide 在本地機器嵌入式 apache 服務器上部署了我的 spring boot web 應用程序,並使用不正確的令牌訪問了一個 url,在這種情況下,它返回我未經授權的訪問錯誤 401 和托管異常處理拋出的特定錯誤消息,而如果我部署在獨立但相同的 apache 服務器上使用相同的應用程序,它給了我 500 個內部服務器錯誤,而不是 401 或任何其他服務器端錯誤。

我捕獲的日志只有以下一行差異:

local
------------------
2021-10-13 16:59:51 - Authentication Failed. Invalid signature in token.
2021-10-13 16:59:51 - Servlet.service() for servlet [dispatcherServlet] in context with path [/myapplication] threw exception
java.lang.RuntimeException: Authentication Failed. Invalid signature in token.

server
------------------
2021-10-13 16:59:35 - Authentication Failed. Invalid signature in token.
2021-10-13 16:59:35 - Forwarding to error page from request [/user/get_user_profile] due to exception [Authentication Failed. Invalid signature in token.]
java.lang.RuntimeException: Authentication Failed. Invalid signature in token.

以下是我用來處理異常的配置:

@Autowired
private JwtAuthenticationEntryPoint unauthorizedHandler;
http.cors().and().csrf().disable()
        .authorizeRequests()
        .antMatchers("admin/**").permitAll()
        .anyRequest().authenticated()
        .and()
        .exceptionHandling().authenticationEntryPoint(unauthorizedHandler)
        .and()
        .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

http.addFilterBefore(authenticationFilter(), UsernamePasswordAuthenticationFilter.class);

這是處理異常的類:

public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint, Serializable {
    private static final long serialVersionUID = -90731367144543199L;

    @Override
    public void commence(HttpServletRequest request,
                     HttpServletResponse response,
                     AuthenticationException authException) throws IOException {

        response.getOutputStream().println(authException);
    }
}

您應該像這樣設置它的狀態,而不是在過濾器中拋出異常:

response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);  
response.getWriter().write("Here will be your message string"); //show error message
return;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM