您的位置:首页 > 其它

web中采用shiro实现登录认证与权限授权管理

2017-11-01 17:35 956 查看
Apache Shiro是Java的一个安全框架。

官网对shiro的介绍:Apache
Shiro™ is a powerful and easy-to-use Java security framework that performs authentication, authorization, cryptography, and
session management. With Shiro’s easy-to-understand API, you can quickly and easily secure any application – from the smallest mobile applications to the largest web and enterprise applications.

翻译一下:Apache Shiro™是强大且易于使用的Java安全框架,可执行认证,授权,加密和会话管理。借助Shiro易于理解的API,您可以快速轻松地确保任何应用程序
- 从最小的移动应用程序到最大的Web和企业应用程序。

本篇介绍shiro进行登陆认证和权限授权,并与web集成。

1、在pom.xml中引入shiro的jar包

<!-- shiro -->
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-web</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-ehcache</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.2.1</version>
</dependency>
2、在web.xml中添加shiro过滤器(启动web程序的时候,javaweb会自动读取web.xml文件,创建servelet上下文并共享)

<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/admin/*</url-pattern>
</filter-mapping>


3、创建spring-shiro.xml,在spring中集成shiro

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- web.xml中shiro的filter对应的bean -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 管理器,必须设置 -->
<property name="securityManager" ref="securityManager" />
<!-- 拦截到,跳转到的地址,通过此地址去认证 -->
<property name="loginUrl" value="/admin/login.do" />
<!-- 认证成功统一跳转到/admin/index.do,建议不配置,shiro认证成功自动到上一个请求路径 -->
<property name="successUrl" value="/admin/index.do" />
<!-- 通过unauthorizedUrl指定没有权限操作时跳转页面 -->
<property name="unauthorizedUrl" value="/refuse.jsp" />
<!-- 自定义filter,可用来更改默认的表单名称配置 -->
<property name="filters">
<map>
<!-- 将自定义 的FormAuthenticationFilter注入shiroFilter中 -->
<entry key="authc" value-ref="formAuthenticationFilter" />
</map>
</property>
<property name="filterChainDefinitions">
<value>
<!-- 对静态资源设置匿名访问 -->
/images/** = anon
/js/** = anon
/styles/** = anon
<!-- 验证码,可匿名访问 -->
/validatecode.jsp = anon
<!-- 请求 logout.do地址,shiro去清除session -->
/admin/logout.do = logout
<!--商品查询需要商品查询权限 ,取消url拦截配置,使用注解授权方式 -->
<!-- /items/queryItems.action = perms[item:query] /items/editItems.action
= perms[item:edit] -->
<!-- 配置记住我或认证通过可以访问的地址 -->
/welcome.jsp = user
/admin/index.do = user
<!-- /** = authc 所有url都必须认证通过才可以访问 -->
/** = authc
</value>
</property>
</bean>

<!-- securityManager安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="customRealm" />
<!-- 注入缓存管理器 -->
<property name="cacheManager" ref="cacheManager" />
<!-- 注入session管理器 -->
<!-- <property name="sessionManager" ref="sessionManager" /> -->
<!-- 记住我 -->
<property name="rememberMeManager" ref="rememberMeManager" />
</bean>

<!-- 自定义realm -->
<bean id="customRealm" class="com.zhijianj.stucheck.shiro.CustomRealm">
<!-- 将凭证匹配器设置到realm中,realm按照凭证匹配器的要求进行散列 -->
<!-- <property name="credentialsMatcher" ref="credentialsMatcher" /> -->
</bean>

<!-- 凭证匹配器 -->
<bean id="credentialsMatcher"
class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 选用MD5散列算法 -->
<property name="hashAlgorithmName" value="md5" />
<!-- 进行一次加密 -->
<property name="hashIterations" value="1" />
</bean>

<!-- 自定义form认证过虑器 -->
<!-- 基于Form表单的身份验证过滤器,不配置将也会注册此过虑器,表单中的用户账号、密码及loginurl将采用默认值,建议配置 -->
<!-- 可通过此配置,判断验证码 -->
<bean id="formAuthenticationFilter"
class="com.zhijianj.stucheck.shiro.CustomFormAuthenticationFilter ">
<!-- 表单中账号的input名称,默认为username -->
<property name="usernameParam" value="username" />
<!-- 表单中密码的input名称,默认为password -->
<property name="passwordParam" value="password" />
<!-- 记住我input的名称,默认为rememberMe -->
<property name="rememberMeParam" value="rememberMe" />
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- session的失效时长,单位毫秒 -->
<property name="globalSessionTimeout" value="600000" />
<!-- 删除失效的session -->
<property name="deleteInvalidSessions" value="true" />
</bean>
<!-- 缓存管理器 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:shiro-ehcache.xml" />
</bean>
<!-- rememberMeManager管理器,写cookie,取出cookie生成用户信息 -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie" ref="rememberMeCookie" />
</bean>
<!-- 记住我cookie -->
<bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<!-- rememberMe是cookie的名字 -->
<constructor-arg value="rememberMe" />
<!-- 记住我cookie生效时间30天 -->
<property name="maxAge" value="2592000" />
</bean>
</beans>


4、shiro中唯一需要用户管理的就是realm了,因为realm是做登陆认证和权限认证的,具体的认证规则需要用户自定义

创建CustomRealm,如下

public class CustomRealm extends AuthorizingRealm {
// 设置realm的名称
@Override
public void setName(String name) {
super.setName("customRealm");
}

@Autowired
private AdminUserService adminUserService;

/**
* 认证
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

// token中包含用户输入的用户名和密码
// 第一步从token中取出用户名
String userName = (String) token.getPrincipal();
// 第二步:根据用户输入的userCode从数据库查询
TAdminUser adminUser = adminUserService.getAdminUserByUserName(userName);
// 如果查询不到返回null
if (adminUser == null) {//
return null;
}
// 获取数据库中的密码
String password = adminUser.getPassword();
/**
* 认证的用户,正确的密码
*/
AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password, this.getName());
//MD5 加密+加盐+多次加密
//<span style="color:#ff0000;">SimpleAuthenticationInfo authcInfo = new SimpleAuthenticationInfo(adminUser, password,ByteSource.Util.bytes(salt), this.getName());</span>
return authcInfo;
}

/**
* 授权,只有成功通过<span style="font-family: Arial, Helvetica, sans-serif;">doGetAuthenticationInfo方法的认证后才会执行。</span>
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
// 从 principals获取主身份信息
// 将getPrimaryPrincipal方法返回值转为真实身份类型(在上边的doGetAuthenticationInfo认证通过填充到SimpleAuthenticationInfo中身份类型),
TAdminUser activeUser = (TAdminUser) principals.getPrimaryPrincipal();
// 根据身份信息获取权限信息
// 从数据库获取到权限数据
TAdminRole adminRoles = adminUserService.getAdminRoles(activeUser);
// 单独定一个集合对象
List<String> permissions = new ArrayList<String>();
if (adminRoles != null) {
permissions.add(adminRoles.getRoleKey());
}
// 查到权限数据,返回授权信息(要包括 上边的permissions)
SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
// 将上边查询到授权信息填充到simpleAuthorizationInfo对象中
simpleAuthorizationInfo.addStringPermissions(permissions);
return simpleAuthorizationInfo;
}

// 清除缓存
public void clearCached() {
PrincipalCollection principals = SecurityUtils.getSubject().getPrincipals();
super.clearCache(principals);
}
}


5、创建shiro-ehcache.xml,在spring-shiro.xml中会读取这个配置文件,作为缓存配置。

<ehcache updateCheck="false" name="shiroCache">

<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="false"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
/>
</ehcache>


6、用户登陆方法,用户登录时,需要先在后台做一次用户空判断(虽然前端已经做了,但是为了防止有人通过http恶意访问网站,获取网站信息),登录方法如下:

public Object loginPost(HttpServletRequest request, HttpServletResponse response,
String username, String password, String captcha,
@RequestParam(value = "rememberMe", defaultValue = "0") Integer rememberMe) {
logger.info("POST请求登录");
// 改为全部抛出异常,避免ajax csrf token被刷新
if (StringUtils.isBlank(username)) {
throw new RuntimeException("用户名不能为空");
}
if (StringUtils.isBlank(password)) {
throw new RuntimeException("密码不能为空");
}
if (StringUtils.isBlank(captcha)) {
throw new RuntimeException("验证码不能为空");
}
if (!dreamCaptcha.validate(request, response, captcha)) {//验证码生成和验证的方法需要自己实现,如果不开启验证码则可以去掉
throw new RuntimeException("验证码错误");
}
Subject user = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// 设置记住密码
token.setRememberMe(1 == rememberMe);
try {
user.login(token);
return renderSuccess();
} catch (UnknownAccountException e) {
throw new RuntimeException("账号不存在!", e);
} catch (DisabledAccountException e) {
throw new RuntimeException("账号未启用!", e);
} catch (IncorrectCredentialsException e) {
throw new RuntimeException("密码错误!", e);
} catch (Throwable e) {
throw new RuntimeException(e.getMessage(), e);
}
}


7、如果开启了验证码登陆功能,则需要在后台加一个验证码生成类,生成验证码之后存在session中,然后在用户登陆时进行验证码的验证。

虽然shiro框架是一种轻量级的Java安全框架,官网描述的多么多么简单,但是真正使用起来还是有一定的难度,特别是shiro加入的一些专业名词和验证步骤,推荐大家一个好的项目,通过git克隆下来就可以直接使用,基本上可以作为一个权限控制框架练练手

项目地址:https://gitee.com/wangzhixuan/spring-shiro-training
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐