This subject is anonymous - it does not have any identifying principals and authorization operations

大家好,我是烤鸭:

    最近使用shiro,遇到如下问题:

严重: Servlet.service() for servlet [dispatcherServlet] in context with path [/etc] threw exception [Request processing failed; nested exception is org.apache.shiro.authz.UnauthenticatedException: This subject is anonymous - it does not have any identifying principals and authorization operations require an identity to check against.  A Subject instance will acquire these identifying principals automatically after a successful login is performed be executing org.apache.shiro.subject.Subject.login(AuthenticationToken) or when 'Remember Me' functionality is enabled by the SecurityManager.  This exception can also occur when a previously logged-in Subject has logged out which makes it anonymous again.  Because an identity is currently not known due to any of these conditions, authorization is denied.] with root cause

 

1.    场景介绍

    项目是前后端分离的,接口用postman自测的时候是没有问题的。但是前端登录后访问有权限限制的接口会报错。

    前端是 react 项目,后端是 springboot 项目。

 

2.    原因猜想

    可能是前端每次请求并没有携带cookie。由于前端项目本地启动请求后端项目需要使用代理。

    默认访问的域名应该是localhost:3000

 

3.   解决方式

   如果前端联调的是测试环境,建议将前端项目也部署测试环境,并且和后端项目部署在同一个域名下(nginx配置一下就可以了)。这种就不存在跨域和携带cookie的问题了。

   如果前端联调的是开发同学的本地环境。需要前后端都做一些修改。

前端:

     fetch请求默认不携带cookie

增加

credentials: "include"   

            var myHeaders = new Headers();
            fetch(url, {
              method: 'GET',
              headers: myHeaders,
              credentials: "include"
            })

withCredentials: true

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

后端:

    如果是和本地联调,肯定存在跨域问题。需要设置  Access-Control-Allow-Origin 为指定ip,不能设置为 *

    浏览器的安全角度 如果设置 为 * ,是不能携带cookie的。

    本例中如下设置。(Access-Control-Allow-Origin 设置 为 localhost:3000)

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedHeader("*"); // 允许任何头
        corsConfiguration.addAllowedOrigin("localhost:3000"); // 允许任何头
        corsConfiguration.addAllowedMethod("*"); // 允许任何方法(post、get等)
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 对接口配置跨域设置
        return new CorsFilter(source);
    }

}
@Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        //每一次的请求先校验cookie
        HttpServletRequest reqeust = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "localhost:3000");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        chain.doFilter(req, res);
    }

总结:

    最开始前端说后端接口访问不同,想到是shiro的问题,但是第一时间并没有想到cookie的问题。 

    找到问题比较慢,解决问题也是。最好的方式就是都部署到测试环境,避免跨域的问题出现就好了。


 

<think>嗯,用户问的是如何处理Shiro框架中的UnauthenticatedException异常,当用户未登录或身份未验证时出现的。首先,我需要回忆一下Shiro的相关知识,以及之前提供的引用内容。根据引用[2],UnauthenticatedException属于登录认证异常,和AuthenticationException同一类。那处理这类异常的方法可能包括全局异常处理或者检查权限配置。 用户提到的问题场景是用户未登录或未验证身份时抛出这个异常。首先,我应该考虑如何确保用户在进行需要认证的操作前已经登录。可能需要在访问受保护资源前检查认证状态,或者在代码中添加登录验证的逻辑。 根据引用[3],有时候权限信息中的空值可能导致异常,但这里的情况是未认证,所以可能更直接的原因是没有登录。用户可能需要配置Shiro的过滤器链,确保某些URL需要认证才能访问,否则跳转到登录页面。比如在ShiroConfig中配置拦截规则,比如将/auth/**设置为anon,而其他路径设置为authc,这样未登录的用户访问时会自动跳转到登录页面,而不是直接抛出异常。 另外,异常处理方面,可以定义一个全局异常处理器,捕获UnauthenticatedException,然后返回相应的错误信息或跳转到登录页面。引用[2]提到定义异常处理类来处理登录认证异常,比如使用Spring的@ControllerAdvice来捕获异常,并返回JSON响应或重定向。 同时,用户可能在代码中没有正确使用Shiro的注解,比如@RequiresAuthentication,导致在未认证的情况下访问了需要认证的方法。这时候需要检查服务层或控制器的方法是否有正确的权限注解,并确保这些注解被Shiro的AOP支持。 另外,引用[4]中提到了凭证错误的问题,虽然这里不是密码错误,但可能用户没有正确处理认证流程,比如登录成功后没有正确创建Subject的会话,导致后续请求仍然被认为是未认证。需要确保登录成功后调用subject.login(token)并保存会话。 可能还需要检查Shiro的Session管理配置,是否启用了Session管理,以及会话超时时间是否合理。如果用户长时间未操作导致会话过期,也可能出现此异常,此时需要重新登录。 总结起来,处理步骤可能包括:配置过滤器链、使用全局异常处理、检查权限注解、确保登录流程正确、以及处理会话过期。需要分步骤回答用户,并给出具体的代码示例,比如ShiroConfig的配置和异常处理类的写法。</think>### 处理 Shiro 中 UnauthenticatedException 的解决方案 #### 1. 明确异常触发场景 `UnauthenticatedException` 表示当前用户未通过身份认证(未登录)时尝试访问受保护资源[^2]。典型场景包括: - 直接访问需要登录的接口 - 会话过期后继续操作 - 未正确执行登录流程 #### 2. 基础配置验证 在 `ShiroConfig` 中配置过滤器链,确保资源访问规则正确定义: ```java @Bean public ShiroFilterFactoryBean shiroFilter(DefaultSecurityManager securityManager) { ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean(); factoryBean.setSecurityManager(securityManager); Map<String, String> filterMap = new LinkedHashMap<>(); filterMap.put("/login", "anon"); // 匿名访问 filterMap.put("/static/**", "anon"); filterMap.put("/api/**", "authc"); // 需要认证 filterMap.put("/admin/**", "authc, roles[admin]"); factoryBean.setFilterChainDefinitionMap(filterMap); factoryBean.setLoginUrl("/login"); // 未认证时跳转地址 return factoryBean; } ``` #### 3. 全局异常处理(推荐方案) 通过 `@ControllerAdvice` 实现统一异常处理: ```java @ControllerAdvice public class ShiroExceptionHandler { @ExceptionHandler(UnauthenticatedException.class) @ResponseBody public ResponseEntity<Map<String, Object>> handleUnauth(Exception ex) { Map<String, Object> response = new HashMap<>(); response.put("code", 401); response.put("message", "请先登录系统"); return ResponseEntity.status(401).body(response); } } ``` #### 4. 强制认证检查 在控制器方法中使用注解验证: ```java @GetMapping("/user/profile") @RequiresAuthentication // 必须登录才能访问 public ResponseEntity<UserProfile> getUserProfile() { // 业务逻辑 } ``` #### 5. 会话管理优化 ```properties # application.properties 配置会话超时(单位:毫秒) shiro.session.globalSessionTimeout=1800000 # 30分钟 ``` #### 6. 登录流程验证 确保登录控制器正确执行认证: ```java @PostMapping("/login") public ResponseEntity<?> login(@RequestBody LoginRequest request) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken( request.getUsername(), request.getPassword() ); try { subject.login(token); // 核心认证调用 return ResponseEntity.ok("登录成功"); } catch (AuthenticationException e) { return ResponseEntity.status(401).body("认证失败"); } } ``` #### 7. 前端联动处理 推荐前端配合实现: ```javascript // Axios 响应拦截器 axios.interceptors.response.use(response => { return response; }, error => { if (error.response.status === 401) { router.push('/login'); // 跳转登录页 } return Promise.reject(error); }); ```
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

烤鸭的世界我们不懂

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值