您的位置:首页 > 编程语言 > Java开发

记录一下springmvc中shiro的使用过程

2019-03-21 20:45 106 查看
版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。 本文链接:https://blog.csdn.net/xuelong222/article/details/88715613
  1. 在web.xml中我们需要配置shiro的过滤器
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext.xml
classpath:applicationContext-shiro.xml
</param-value>
</context-param>
<!-- Shiro配置 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

DelegatingFilterProxy这个过滤器的功能是通知spring将所有的filter都交给shiro进行管理
这里还需要将spring整合shiro的配置文件applicationContext-shiro引入
2.接下来需要是shiro的关键配置applicationContext-shiro

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">

<!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!-- 调用我们配置的权限管理器 -->
<property name="securityManager" ref="securityManager" />
<!-- 配置登录的url-->
<property name="loginUrl" value="/login" />
<!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址,可以不要 -->
<property name="unauthorizedUrl" value="/unauthorized" />
<!-- 退出 -->
<property name="filters">
<util:map>
<entry key="logout" value-ref="logoutFilter" />
</util:map>
</property>
<!-- 权限配置 -->
<property name="filterChainDefinitions">
<value>
<!-- anon表示此地址不需要任何权限即可访问 -->
/login=anon
/index=anon
/static/**=anon
/doLogout=logout
<!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login -->
/** = authc
</value>
</property>
</bean>
<!-- 退出过滤器 -->
<bean id="logoutFilter" class="org.apache.shiro.web.filter.authc.LogoutFilter">
<property name="redirectUrl" value="/index" />
</bean>

<!-- 会话ID生成器 -->
<bean id="sessionIdGenerator"
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" />
<!-- 会话Cookie模板 关闭浏览器立即失效 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="sid" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="-1" />
</bean>
<!-- 会话DAO -->
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean>
<!-- 会话验证调度器,每30分钟执行一次验证 ,设定会话超时及保存 -->
<bean name="sessionValidationScheduler"
class="org.apache.shiro.session.mgt.ExecutorServiceSessionValidationScheduler">
<property name="interval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- 全局会话超时时间(单位毫秒),默认30分钟 -->
<property name="globalSessionTimeout" value="1800000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionValidationSchedulerEnabled" value="true" />
<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
<property name="sessionDAO" ref="sessionDAO" />
<property name="sessionIdCookieEnabled" value="true" />
<property name="sessionIdCookie" ref="sessionIdCookie" />
</bean>

<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="databaseRealm" />
<property name="sessionManager" ref="sessionManager" />
</bean>
<!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean>

<!-- 密码匹配器 -->
<bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<property name="hashAlgorithmName" value="md5"/>
<property name="hashIterations" value="2"/>
<property name="storedCredentialsHexEncoded" value="true"/>
</bean>
<!--唯一需要自己写的-->
<bean id="databaseRealm" class="com.xl.realm.DatabaseRealm">
<property name="credentialsMatcher" ref="credentialsMatcher"/>
</bean>

<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>

这里大多数都不用动,只需要改一下自己登录和登出的url
/login=anon这里的anon表示不需要任何权限不作处理,这里的意思是/login这个url不需要权限即可访问, /static/*=anon 是通配符,表示/static/下的任何资源都不需要权限,这里设置的是静态资源
/doLogout=logout表示 /doLogout是登出的url,这几个权限设置是有优先级的,靠前的优先,所以我们最后配置了 / = authc,表示其他任何资源都需要登录才能访问,authc表示登录,否则就跳转到设置好的登录url
3.现在开始写唯一需要自己写的Realm,这里是真正进行登录验证和授权的地方

package com.xl.realm;

import com.xl.pojo.Blogger;
import com.xl.service.BloggerService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

p
3ff7
ublic class DatabaseRealm extends AuthorizingRealm {

@Autowired
private BloggerService bloggerService;
@Autowired
private RoleService roleService;
@Autowired
private PermissionService permissionService;
//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
//能进入到这里,表示账号已经通过验证了
String userName =(String) principalCollection.getPrimaryPrincipal();
//通过service获取角色和权限
Set<String> permissions = permissionService.listPermissions(userName);
Set<String> roles = roleService.listRoleNames(userName);

//授权对象
SimpleAuthorizationInfo s = new SimpleAuthorizationInfo();
//把通过service获取到的角色和权限放进去
s.setStringPermissions(permissions);
s.setRoles(roles);
return s;
}
//验证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        获得令牌对象
UsernamePasswordToken t = (UsernamePasswordToken) token;
//        获得登录的用户名
String username = t.getPrincipal().toString();
//        去数据库中查询此用户的密码和盐
Blogger blogger = bloggerService.findByUserName(username);
String password = blogger.getPassword();
String salt = blogger.getSalt();
//        将用户名密码和盐让shiro自己去验证
SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(username, password, ByteSource.Util.bytes(salt), getName());
return authenticationInfo;
}
}

shiro会根据用户名密码和盐验证用户,之后查询数据库用户拥有的权限和角色再给用户授权
4.此时一切配置完成,当用户发起登录请求时,获取用户名密码。进行登录验证授权

@RequestMapping("/login")
public String login(Blogger currentUser, HttpSession session,Model model){
//        代表一个登录的主体
Subject subject = SecurityUtils.getSubject();
//        将登录的用户名和密码封装进令牌对象中
UsernamePasswordToken token = new UsernamePasswordToken(currentUser.getUser_name(),currentUser.getPassword());
try {
//            登录验证
subject.login(token);
//            验证通过,将此主体放入session中
session.setAttribute("subject",subject);
//            跳转页面
return "admin/main";
}catch (AuthenticationException e){
//            抛出异常,证明验证失败,返回错误信息
model.addAttribute("errorInfo","用户名或密码错误");
//           返回登录页面
return "login";
}
}

处理登录请求,先用SecurityUtils工具类获取Subject对象,将用户输入的用户名密码封装进UsernamePasswordToken中,然后调用login方法,将令牌对象传入进行登录验证,此时就是上面的reaml发生作用的时候,shiro会自动调用reaml里面的两个方法进行验证和授权,若验证失败,会抛出
AuthenticationException 异常,否则验证成功

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: