返回

剖析Springboot-Shiro的404之谜:构建未授权响应的正确姿势

后端

前言

Springboot-Shiro是轻量级的Java安全框架,能够轻松整合到Springboot项目中。然而,在使用Springboot-Shiro时,我们可能遇到各种问题,比如使用Postman时返回404错误。这可能会让我们感到困惑和沮丧。

问题分析

当我们使用Postman向Springboot-Shiro项目发送请求时,可能会遇到404错误。这是因为Shiro默认将未授权的请求重定向到404页面。这是Shiro的默认行为,它将所有未授权的请求重定向到404页面。

解决方法

要解决这个问题,我们需要在Springboot-Shiro中配置一个自定义的过滤器,当未授权的请求到达时,它将返回一个JSON格式的未授权响应。

步骤 1:创建自定义过滤器

创建一个名为UnauthorizedFilter的自定义过滤器。此过滤器将处理未授权的请求。

public class UnauthorizedFilter extends Filter {

    @Override
    protected boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        // 如果未授权,则返回JSON格式的未授权响应
        if (!SubjectUtils.isAuthorized()) {
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            out.write("{\"code\": 401, \"message\": \"未授权\"}");
            out.flush();
            return false;
        }
        // 如果授权,则继续执行下一个过滤器
        return true;
    }
}

步骤 2:注册自定义过滤器

将自定义过滤器注册到Springboot-Shiro中。

@Configuration
public class ShiroConfig {

    @Bean
    public FilterRegistrationBean<UnauthorizedFilter> unauthorizedFilterRegistrationBean() {
        FilterRegistrationBean<UnauthorizedFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new UnauthorizedFilter());
        registrationBean.addUrlPatterns("/*");
        return registrationBean;
    }
}

步骤 3:测试

现在,我们可以使用Postman再次向Springboot-Shiro项目发送请求。这次,我们应该会得到一个JSON格式的未授权响应。

{
  "code": 401,
  "message": "未授权"
}

总结

通过在Springboot-Shiro中配置一个自定义的过滤器,我们可以轻松地将未授权的请求重定向到一个JSON格式的未授权响应。这将使我们的应用程序更加安全和易于使用。