一、添加一个Shiro拦截器
import com.jfinal.aop.Interceptor; import com.jfinal.aop.Invocation; import com.jfinal.core.Controller; import com.jfinal.kit.LogKit; import org.apache.shiro.aop.MethodInvocation; import org.apache.shiro.authz.AuthorizationException; import org.apache.shiro.authz.aop.AnnotationsAuthorizingMethodInterceptor; import java.lang.reflect.Method; /** * Shiro 拦截器 */ public class ShiroInterceptor extends AnnotationsAuthorizingMethodInterceptor implements Interceptor { public ShiroInterceptor() { getMethodInterceptors(); //用来扩展其他注解 } @Override public void intercept(final Invocation inv) { try { invoke(new MethodInvocation() { @Override public Object proceed() throws Throwable { inv.invoke(); return inv.getReturnValue(); } @Override public Method getMethod() { return inv.getMethod(); } @Override public Object[] getArguments() { return inv.getArgs(); } @Override public Object getThis() { return inv.getController(); } }); } catch (Throwable e) { if (e instanceof AuthorizationException) { doProcessuUnauthorization(inv.getController()); } LogKit.warn("权限错误:", e); } } /** * 未授权处理 * * @param controller controller */ private void doProcessuUnauthorization(Controller controller) { controller.renderError(401); } }
二、依赖包
<dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.3.2</version> </dependency>
三、Config中添加拦截器配置
me.add(new ShiroInterceptor());
四、web.xml配置filter
<filter> <filter-name>shiro</filter-name> <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class> </filter> <filter-mapping> <filter-name>shiro</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
五、shiro.ini配置
例如:
[main] sessionIdCookie = org.apache.shiro.web.servlet.SimpleCookie sessionIdCookie.name = JFIANL_SHIRO sessionIdCookie.path = / sessionIdCookie.maxAge = 1800 sessionIdCookie.httpOnly = true #jdbcRealm ##数据源 dataSource = dataSource.driverClassName = dataSource.url = dataSource.username = dataSource.password = dataSource.filters = ##加密方式 credentialsMatcher = credentialsMatcher.hashAlgorithmName = credentialsMatcher.hashSalted = ##认证方式 jdbcRealm = jdbcRealm.credentialsMatcher = $credentialsMatcher jdbcRealm.dataSource = $dataSource jdbcRealm.permissionsLookupEnabled = true jdbcRealm.authenticationQuery = jdbcRealm.userRolesQuery = jdbcRealm.permissionsQuery = securityManager.realms = $jdbcRealm #缓存实现 cacheManager = org.apache.shiro.cache.MemoryConstrainedCacheManager securityManager.cacheManager = $cacheManager [urls] /** = anon
realm 具体根据项目实际情况进行调整。
六、权限控制
通过“RequiresAuthentication”、“RequiresGuest”、“RequiresPermissions”、“RequiresRoles”、“RequiresUser” 几个注解在 Controller 上进行配置:
例如:
@RequiresAuthentication public class DashboardController extends Controller {
@RequiresPermissions("报表权限") public void index() { render("/report/index.html"); }
七、模板指令扩展
参照Jboot的指令拓展,加入 Engine
http://git.oschina.net/fuhai/jboot/tree/master/src/main/java/io/jboot/component/shiro/directives