ssm+freemark集成shiro.docx

上传人:b****2 文档编号:23492529 上传时间:2023-05-17 格式:DOCX 页数:35 大小:151.42KB
下载 相关 举报
ssm+freemark集成shiro.docx_第1页
第1页 / 共35页
ssm+freemark集成shiro.docx_第2页
第2页 / 共35页
ssm+freemark集成shiro.docx_第3页
第3页 / 共35页
ssm+freemark集成shiro.docx_第4页
第4页 / 共35页
ssm+freemark集成shiro.docx_第5页
第5页 / 共35页
点击查看更多>>
下载资源
资源描述

ssm+freemark集成shiro.docx

《ssm+freemark集成shiro.docx》由会员分享,可在线阅读,更多相关《ssm+freemark集成shiro.docx(35页珍藏版)》请在冰豆网上搜索。

ssm+freemark集成shiro.docx

ssm+freemark集成shiro

ssm+freemark集成shiro

1.导入的jar包

[html]viewplaincopy在CODE上查看代码片派生到我的代码片

--shirostart-->

--freemarker+shiro(标签)begin-->

net.mingsoft

shiro-freemarker-tags

0.1

--freemarker+shiro(标签)end-->

org.apache.shiro

shiro-core

org.apache.shiro

shiro-web

org.apache.shiro

shiro-ehcache

org.apache.shiro

shiro-spring

--shiroend-->

2.在web.xml中加入shirofilter

[html]viewplaincopy在CODE上查看代码片派生到我的代码片

--Shiro过滤器-->

shiroFilter

org.springframework.web.filter.DelegatingFilterProxy

targetFilterLifecycle

true

shiroFilter

/*

REQUEST

FORWARD

此过滤器要放在第一个,且名称要与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">登录

2.user(已经登录,或者记住我登录)

<@shiro.user>

欢迎[<@shiro.principal/>]登录,退出

3.authenticated(已经认证,排除记住我登录的)

<@shiro.authenticated>

用户[<@shiro.principal/>]已身份验证通过

4.notAuthenticated(和authenticated相反)

<@shiro.notAuthenticated>

当前身份未认证(包括记住我登录的)

5.principal标签(能够取到你在realm中保存的信息比如我存的是ShiroUser对象,取出其中urlSet属性)

--需要指定property-->

<@shiro.principalproperty="urlSet"/>

6.hasRole标签(判断是否拥有这个角色)

<@shiro.hasRolename="admin">

用户[<@shiro.principal/>]拥有角色admin

7.hasAnyRoles标签(判断是否拥有这些角色的其中一个)

<@shiro.hasAnyRolesname="admin,user,member">

用户[<@shiro.principal/>]拥有角色admin或user或member

8.lacksRole标签(判断是否不拥有这个角色)

<@shiro.lacksRolename="admin">

用户[<@shiro.principal/>]不拥有admin角色

9.hasPermission标签(判断是否有拥有这个权限)

<@shiro.hasPermissionname="user:

add">

用户[<@shiro.principal/>]拥有user:

add权限

10.lacksPermission标签(判断是否没有这个权限)

<@shiro.lacksPermissionname="user:

add">

用户[<@shiro.principal/>]不拥有user:

add权限

**/

}

}

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和角色

Setroles=Sets.newHashSet(role.getName());

ListmenuIds=BizUtil.stringToLongList(role.getMenu(),",");

List

menuList=menuService.getListByIds(menuIds);

ListmenuStr=BizUtil.extractToList(menuList,"url");

Seturls=Sets.newHashSet(menuStr);

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 考试认证 > 从业资格考试

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1