authorization cache cannot be obtained

有时候shiro会出现这个异常,只需要修改shiro配置文件,关闭cache

原来:
<bean id="userRealm" class="com.qingqing.bpt.shiro.UserRealm"/>
改为:
    <bean id="userRealm" class="com.qingqing.bpt.shiro.UserRealm">
        <property name="cachingEnabled" value="true"></property>
        <property name="authenticationCachingEnabled" value="false"></property>
    </bean>
在Spring Security中,当用户必须先被身份验证(Authentication)成功之后才能进行授权(Authorization)操作时,通常涉及到权限控制和访问控制的流程。如果遇到这个问题,你可以按照以下步骤来解决: 1. **配置Spring Security**: 首先,在你的Spring Boot应用中,确保已经添加了Spring Security依赖,并配置了相应的`WebSecurityConfigurerAdapter`或`@Configuration`类。这通常包括`@EnableWebSecurity`注解、`SecurityConfigurer`接口的实现以及一个`HttpSecurity`对象来定义安全规则。 ```java @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { // 添加身份验证管理器 @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.inMemoryAuthentication() .withUser("user").password(passwordEncoder().encode("password")).roles("USER"); } // 定义HTTP会话管理 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/resources/**").permitAll() // 允许无授权访问资源目录 .anyRequest().authenticated() // 所有其他请求需要认证 .and() .formLogin() // 添加表单登录 .loginPage("/login") // 登录页面地址 .defaultSuccessUrl("/") // 登录成功后的默认URL .permitAll(); } } ``` 2. **创建登录页面**: 创建一个登录界面(如`/login`),使用Spring Security的`formLogin()`方法指定。确保用户输入用户名和密码后能正确提交到服务器进行验证。 3. **处理登录请求**: 当用户提交登录表单后,你需要有一个后端控制器或服务接收这些请求,验证用户凭证并返回一个`Authentication`对象。如果验证失败,可以重定向到登录页面显示错误信息。 4. **处理授权**: 使用`Secured`注解或者`@PreAuthorize`表达式语言对需要授权的方法或控制器进行标记。Spring Security会在方法执行前检查用户是否已通过身份验证。 ```java @RestController @RequestMapping("/api") @Secured("ROLE_USER") // 或者 @PreAuthorize("hasRole('USER')") public class ProtectedController { @GetMapping("/secret") public String secretArea() { // 只有已授权的用户才能访问这个方法 return "Welcome to the secret area!"; } } ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值