对于shiro 注解授权不起作用的解决方案如下:
1.如果是springmvc进行整合的话 开启注解需要写在springmvc对应的配置文件内
//配置异常捕获
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.apache.shiro.authz.UnauthorizedException">/error/302</prop>
</props>
</property>
</bean>
//开启shiro注解
<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
<property name="securityManager" ref="securityManager"/>
</bean>
shiro.xml配置如下:
<description>Shiro安全配置</description>
<!-- Shiro's main business-tier object for web-enabled applications -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="shiroDbRealm" />
</bean>
<!-- 項目自定义的Realm, 所有accountService依赖的dao都需要用depends-on声明 -->
<bean id="shiroDbRealm" class="com.hengbao.shiro.service.realm.ShiroDbRealm">
</bean>
<!-- Shiro Filter -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/index.jsp" />
<property name="unauthorizedUrl" value="/error/302.jsp"/>//没有授权时跳转的错误页面
<property name="filterChainDefinitions">
<value>
/login = authc
/logout = logout
/static/** = anon
/api/** = anon
/register/** = anon
/admin/** = roles[admin]
/** = authc
</value>
</property>
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
3.登陆界面接受准确的错误信息提示
接收准确的异常信息需要自定义filter 继承FormAuthenticationFilter 重写onLoginFailure方法 异常信息捕获到后传递给controller 详细代码如下:
protected boolean onLoginFailure(AuthenticationToken token,AuthenticationException e, ServletRequest request,ServletResponse response) {
boolean result = super.onLoginFailure(token, e, request, response);
String errorMessage = "用户名或者密码错误";
if (e instanceof CaptchaException) {
errorMessage = "验证码输入错误";
}
request.setAttribute("authenticationErrorMessage", errorMessage);
return result;
}