ssm+freemark集成shiro.docx
- 文档编号:23492529
- 上传时间:2023-05-17
- 格式:DOCX
- 页数:35
- 大小:151.42KB
ssm+freemark集成shiro.docx
《ssm+freemark集成shiro.docx》由会员分享,可在线阅读,更多相关《ssm+freemark集成shiro.docx(35页珍藏版)》请在冰豆网上搜索。
ssm+freemark集成shiro
ssm+freemark集成shiro
1.导入的jar包
[html]viewplaincopy在CODE上查看代码片派生到我的代码片
--shirostart-->
--freemarker+shiro(标签)begin-->
--freemarker+shiro(标签)end-->
--shiroend-->
2.在web.xml中加入shirofilter
[html]viewplaincopy在CODE上查看代码片派生到我的代码片
--Shiro过滤器-->
此过滤器要放在第一个,且名称要与spring-shiro,xml中shirofilter一致
3.在freemarker中加入shiro标签
3.1新建一个FreeMarkerConfigExtend类继承FreeMarkerConfigurer,
[java]viewplaincopy在CODE上查看代码片派生到我的代码片
packagecom.business.util;
importjava.io.IOException;
importorg.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
importcom.jagregory.shiro.freemarker.ShiroTags;
importfreemarker.template.Configuration;
importfreemarker.template.TemplateException;
publicclassFreeMarkerConfigExtendextendsFreeMarkerConfigurer{
@Override
publicvoidafterPropertiesSet()throwsIOException,TemplateException{
super.afterPropertiesSet();
Configurationcfg=this.getConfiguration();
cfg.setSharedVariable("shiro",newShiroTags());//shiro标签
cfg.setNumberFormat("#");//防止页面输出数字,变成2,000
//可以添加很多自己的要传输到页面的[方法、对象、值]
/*
*在controller层使用注解再加一层判断
*注解@RequiresPermissions("/delete")
*/
/*shiro标签*/
/**
1.游客
<@shiro.guest>
您当前是游客, void(0);"class="dropdown-toggleqqlogin">登录 @shiro.guest> 2.user(已经登录,或者记住我登录) <@shiro.user> 欢迎[<@shiro.principal/>]登录, @shiro.user> 3.authenticated(已经认证,排除记住我登录的) <@shiro.authenticated> 用户[<@shiro.principal/>]已身份验证通过 @shiro.authenticated> 4.notAuthenticated(和authenticated相反) <@shiro.notAuthenticated> 当前身份未认证(包括记住我登录的) @shiro.notAuthenticated> 5.principal标签(能够取到你在realm中保存的信息比如我存的是ShiroUser对象,取出其中urlSet属性) --需要指定property--> <@shiro.principalproperty="urlSet"/> 6.hasRole标签(判断是否拥有这个角色) <@shiro.hasRolename="admin"> 用户[<@shiro.principal/>]拥有角色admin @shiro.hasRole> 7.hasAnyRoles标签(判断是否拥有这些角色的其中一个) <@shiro.hasAnyRolesname="admin,user,member"> 用户[<@shiro.principal/>]拥有角色admin或user或member @shiro.hasAnyRoles> 8.lacksRole标签(判断是否不拥有这个角色) <@shiro.lacksRolename="admin"> 用户[<@shiro.principal/>]不拥有admin角色 @shiro.lacksRole> 9.hasPermission标签(判断是否有拥有这个权限) <@shiro.hasPermissionname="user: add"> 用户[<@shiro.principal/>]拥有user: add权限 @shiro.hasPermission> 10.lacksPermission标签(判断是否没有这个权限) <@shiro.lacksPermissionname="user: add"> 用户[<@shiro.principal/>]不拥有user: add权限 @shiro.lacksPermission> **/ } } 3.2修改spring-mvc-servlet.xml中的freemarker配置 4.新建CustomCredentialsMatcher类继承shiro的SimpleCredentialsMatcher类,这个类作用是自定义密码验证 [java]viewplaincopy在CODE上查看代码片派生到我的代码片 packagecom.business.shiro; importorg.apache.shiro.authc.AuthenticationInfo; importorg.apache.shiro.authc.AuthenticationToken; importorg.apache.shiro.authc.UsernamePasswordToken; importorg.apache.shiro.authc.credential.SimpleCredentialsMatcher; importcom.business.util.MD5Util; /** *Description: 告诉shiro如何验证加密密码,通过SimpleCredentialsMatcher或HashedCredentialsMatcher *@Author: zh *@CreateDate: 2017-5-9 */ publicclassCustomCredentialsMatcherextendsSimpleCredentialsMatcher{ @Override publicbooleandoCredentialsMatch(AuthenticationTokenauthcToken,AuthenticationInfoinfo){ UsernamePasswordTokentoken=(UsernamePasswordToken)authcToken; ObjecttokenCredentials=MD5Util.hmac_md5(String.valueOf(token.getPassword())); ObjectaccountCredentials=getCredentials(info); //将密码加密与系统加密后的密码校验,内容一致就返回true,不一致就返回false returnequals(tokenCredentials,accountCredentials); } } 5.新建ShiroDbRealm类 [java]viewplaincopy在CODE上查看代码片派生到我的代码片 packagecom.business.shiro; importjava.util.List; importjava.util.Set; importjavax.annotation.PostConstruct; importorg.apache.log4j.Logger; importorg.apache.shiro.authc.AuthenticationException; importorg.apache.shiro.authc.AuthenticationInfo; importorg.apache.shiro.authc.AuthenticationToken; importorg.apache.shiro.authc.DisabledAccountException; importorg.apache.shiro.authc.SimpleAuthenticationInfo; importorg.apache.shiro.authc.UsernamePasswordToken; importorg.apache.shiro.authc.credential.CredentialsMatcher; importorg.apache.shiro.authz.AuthorizationInfo; importorg.apache.shiro.authz.SimpleAuthorizationInfo; importorg.apache.shiro.cache.CacheManager; importorg.apache.shiro.realm.AuthorizingRealm; importorg.apache.shiro.subject.PrincipalCollection; importorg.apache.shiro.subject.SimplePrincipalCollection; importorg.springframework.beans.factory.annotation.Autowired; importcom.business.dao.UserDao; importcom.business.entity.Menu; importcom.business.entity.Role; importcom.business.entity.User; importcom.business.entity.UserRole; importcom.business.service.sysService.MenuService; importcom.business.service.sysService.RoleService; importcom.business.service.sysService.UserRoleService; importcom.business.service.sysService.UserService; importcom.business.util.SessionUtil; importmon.util.BizUtil; importmon.collect.Sets; /** *@description: shiro权限认证 *@author: zhanghao *@date: 2017/5/814: 51 */ publicclassShiroDbRealmextendsAuthorizingRealm{ privatestaticfinalLoggerLOGGER=Logger.getLogger(ShiroDbRealm.class); @AutowiredprivateUserServiceuserService; @AutowiredprivateUserDaouserDao; @AutowiredprivateRoleServiceroleService; @AutowiredprivateUserRoleServiceuserRoleService; @AutowiredprivateMenuServicemenuService; publicShiroDbRealm(CacheManagercacheManager,CredentialsMatchermatcher){ super(cacheManager,matcher); } /** *Shiro登录认证(原理: 用户提交用户名和密码---shiro封装令牌----realm通过用户名将密码查询返回----shiro自动去比较查询出密码和用户输入密码是否一致----进行登陆控制) */ @Override protectedAuthenticationInfodoGetAuthenticationInfo( AuthenticationTokenauthcToken)throwsAuthenticationException{ LOGGER.info("Shiro开始登录认证"); UsernamePasswordTokentoken=(UsernamePasswordToken)authcToken; Useruser=userDao.getByName(token.getUsername()); //账号不存在 if(user==null){ returnnull; } //账号未启用 if(user.getStatus()==1){ thrownewDisabledAccountException(); } //将用户信息保存在session中 SessionUtil.addSession(user); UserRoleuserRole=userRoleService.getByUserId(user.getId()); Rolerole=roleService.getById(userRole.getRoleId()); //读取用户的url和角色 Set List List
List
Set
urls.remove("");
urls.remove(null);
ShiroUsershiroUser=newShiroUser(user.getId(),user.getLoginName(),user.getUsername(),urls);
shiroUser.setRoles(roles);
//认证缓存信息
returnnewSimpleAuthenticationInfo(shiroUser,user.getPassword().toCharArray(),getName());
}
/**
*Shiro权限认证
*/
@Override
protectedAuthorizationInfodoGetAuthorizationInfo(
PrincipalCollectionprincipals){
ShiroUsershiroUser=(ShiroUser)principals.getPrimaryPrincipal();
SimpleAuthorizationInfoinfo=newSimpleAuthorizationInfo();
info.setRoles(shiroUser.getRoles());
info.addStringPermissions(shiroUser.getUrlSet());
returninfo;
}
@Override
publicvoidonLogout(PrincipalCollectionprincipals){
super.clearCachedAuthorizationInfo(principals);
ShiroUsershiroUser=(ShiroUser)principals.getPrimaryPrincipal();
removeUserCache(shiroUser);
}
/**
*清除用户缓存
*@paramshiroUser
*/
publicvoidremoveUserCache(ShiroUsershiroUser){
removeUserCache(shiroUser.getLoginName());
}
/**
*清除用户缓存
*@paramloginName
*/
publicvoidremoveUserCache(StringloginName){
SimplePrincipalCollectionprincipals=newSimplePrincipalCollection();
principals.add(loginName,super.getName());
super.clearCachedAuthenticationInfo(principals);
}
@PostConstruct
publicvoidinitCredentialsMatcher(){
//该句作用是重写shiro的密码验证,让shiro用我自己的验证-->指向重写的CustomCredentialsMatcher
setCredentialsMatcher(newCustomCredentialsMatcher());
}
}
6.自定义shiroUser
[java]viewplaincopy在CODE上查看代码片派生到我的代码片
packagecom.business.shiro;
importjava.io.Serializable;
importjava.util.Set;
/**
*@description:
自定义Authentication对象,使得Subject除了携带用户的登录名外还可以携带更多信息
*@author:
zhanghao
*@date:
2017/5/9
*/
publicclassShiroUserimplementsSerializable{
privatestaticfinallongserialVersionUID=-1373760761780840081L;
privateLongid;
privatefinalStringloginName;
privateStri
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- ssm freemark 集成 shiro