Shiro使用(基于SSM)

一、配置文件

maven配置

    <!-- Shiro -->
   <dependency>  
        <groupId>org.apache.shiro</groupId>  
        <artifactId>shiro-core</artifactId>  
        <version>1.2.3</version>  
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-ehcache</artifactId>
        <version>1.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-web</artifactId>
        <version>1.2.3</version>
    </dependency>
    <dependency>
        <groupId>org.apache.shiro</groupId>
        <artifactId>shiro-spring</artifactId>
        <version>1.2.3</version>
    </dependency>

web.xml配置

<!-- Spring ApplicationContext 配置文件的路径,可使用通配符,多个路径用,号分隔 此参数用于后
面的 Spring Context Loader -->
<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>
		classpath*:/applicationContext-shiro.xml
	</param-value>
</context-param>
<!-- shiro security filter -->
<filter>
	<!-- 这里的 filter-name 要和 spring 的 applicationContext-shiro.xml 里的
	org.apache.shiro.spring.web.ShiroFilterFactoryBean 的 bean name 相同 -->
	<filter-name>shiroSecurityFilter</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>shiroSecurityFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

applicationContext-shiro.xml

<bean id="shiroSecurityFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- shiro 的核心安全接口 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 要求登录时的链接 -->
		<property name="loginUrl" value="/login.jsp" />
		<!-- 登陆成功后要跳转的连接 -->
		<property name="successUrl" value="/index.jsp" />
		<!-- 未授权时要跳转的连接 -->
		<property name="unauthorizedUrl" value="/unauthorized.jsp" />
		<!-- shiro 连接约束配置 -->
		<property name="filterChainDefinitions">
			<value>
				/login = authc
				/logout = logout
				/resource/** = anon
			</value>
		</property>
	</bean>
	
	<!-- securityManager -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<!--调用自定义realm -->
        <property name="realm" ref="realm" />
	</bean>
	<bean id="realm" class="cn.cc.shiro.Realm"></bean>
	
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
	
	<!-- AOP式方法级权限检查  -->
    <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
        <property name="proxyTargetClass" value="true" />
    </bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>
	
	<!-- 启用注解 -->
	<!-- <bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor"/>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
		<property name="securityManager" ref="securityManager"/>
	</bean> -->

二、登录验证-登录拦截器

 

    <bean id="shiroSecurityFilter"                    class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<!-- shiro 的核心安全接口 -->
		<property name="securityManager" ref="securityManager" />
		<!-- 要求登录时的链接 -->
		<property name="loginUrl" value="login.do" />
		<!-- 登陆成功后要跳转的连接 -->
		<property name="successUrl" value="/index.jsp" />
		<!-- 未授权时要跳转的连接 -->
		<property name="unauthorizedUrl" value="unauthorized.do" />
		
		<!-- shiro 连接约束配置  URL拦截规则-->
		<property name="filterChainDefinitions">
			<value>
				/css/** = anon
				/js/** = anon
				/images/** = anon
				/login.do = anon
				/checkLogin.do = anon
				/doGetAuthorizationInfo.do = perms["authorization"]
				/* = authc
			</value>
		</property>
	</bean>

首先要了解一下拦截规则

securityManager:这个属性是必须的
loginUrl :没有登录的用户请求需要登录的页面时自动跳转到登录页面,不是必须的属性,不输入地址的话会自动寻找项目web项目的根目录下的”/login.jsp”页面。
successUrl :登录成功默认跳转页面,不配置则跳转至”/”。如果登陆前点击的一个需要登录的页面,则在登录自动跳转到那个需要登录的页面。不跳转到此。
unauthorizedUrl :没有权限默认跳转的页面。

过滤器简称

对应的java

anon

org.apache.shiro.web.filter.authc.AnonymousFilter

authc

org.apache.shiro.web.filter.authc.FormAuthenticationFilter

authcBasic

org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter

perms

org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter

port

org.apache.shiro.web.filter.authz.PortFilter

rest

org.apache.shiro.web.filter.authz.HttpMethodPermissionFilter

roles

org.apache.shiro.web.filter.authz.RolesAuthorizationFilter

ssl

org.apache.shiro.web.filter.authz.SslFilter

user

org.apache.shiro.web.filter.authc.UserFilter 

logout

org.apache.shiro.web.filter.authc.LogoutFilter 

 

 

anon:例子/admins/**=anon 没有参数,表示可以匿名使用

authc:例如/admins/user/**=authc表示需要认证(登录)才能使用,没有参数

roles:例子/admins/user/**=roles[admin],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,当有多个参数时,例如admins/user/**=roles["admin,guest"],每个参数通过才算通过,相当于hasAllRoles()方法。

perms:例子
/admins/user/**=permsuser:add:*],参数可以写多个,多个时必须加上引号,并且参数之间用逗号分割,例如/admins/user/**=perms["user:add:*,user:modify:*"],当有多个参数时必须每个参数都通过才通过,想当于isPermitedAll()方法。

rest:例子/admins/user/**=rest[user],根据请求的方法,相当于/admins/user/**=perms[user:method] ,其中method为post,get,delete等。

port:例子/admins/user/**=port[8081],当请求的url的端口不是8081是跳转到schemal://serverName:8081?queryString,其中schmal是协议http或https等,serverName是你访问的host,8081是url配置里port的端口,queryString是你访问的url里的?后面的参数。

authcBasic:例如/admins/user/**=authcBasic没有参数表示httpBasic认证

ssl:例子/admins/user/**=ssl没有参数,表示安全的url请求,协议为https

user:例如/admins/user/**=user没有参数表示必须存在用户,当登入操作时不做检查

注:anon,authcBasic,auchc,user是认证过滤器,perms,roles,ssl,rest,port是授权过滤器
 

登录url和js一定要设置成anon不被拦截 要不然登录页面都进不去

其他可以设置/* = authc 必须登录才能访问

在shiro配置文件中配置realm路径

 登录校验Controller

// 使用shiro框架方式进行登录认证
Subject subject = SecurityUtils.getSubject();//获得当前用户 状态为“未认证”
// 从表单中获取登录信息传入进去
AuthenticationToken token = new UsernamePasswordToken(username, password);//创建用户名密码令牌
try {
    subject.login(token);  // 该方法会进入自定义的reaml 进行账号密码校验 校验失败会抛出异常
}catch (Exception e) {
    e.printStackTrace();
    System.out.println("认证失败");
    return new ModelAndView("login/login");
}
// 校验通过 subject.getPrincipal() 拿到user信息 放入session 跳转首页
User user = (User) subject.getPrincipal();
session.setAttribute("loginUser", user);
return new ModelAndView("index");

 自定义Realm方法

public class Realm extends AuthorizingRealm {
	
	@Autowired
	private UserMapper userMapper;
	
	// 认证方法
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("自定义的realm中认证方法执行的");
		UsernamePasswordToken passwordToken = (UsernamePasswordToken)token;
		//根据用户名查询数据库中的密码
		String username = passwordToken.getUsername();
		User user = userMapper.getUserByUsernmae(username);
		if(user == null) {
			//用户不存在
			return null;
		}
		// 如果用户存在 校验密码是否正确 正确renturn info 否则抛出异常 认证失败
		AuthenticationInfo info = new SimpleAuthenticationInfo(user,   user.getPassword(), this.getName());
		return info;
	}
	
	// 授权方法
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("自定义的realm中授权方法执行的");
		return null;
	}

	
	
}

继承AuthorizingRealm 实现两个抽象方法 也可以继承其它Realm类 或者实现其它Realm接口

 两部

通过Controller中传入的token,Realm中可以取到

UsernamePasswordToken passwordToken = (UsernamePasswordToken)token;

只需要通过username查询出User信息  不需要校验密码 Realm有自己校验方法

查询不到user信息抛出异常 Controller中进行拦截 (这里的异常有账号不存在,密码错误等 可以根据异常类型不同进行捕获)

查到user信息进行校验返回

三、realm方法授权

在applicationContext-shiro.xml  URL拦截规则中加入下面配置

/doGetAuthorizationInfo.do = perms["authorization"]

意思是在用户登录后的情况下 访问doGetAuthorizationInfo.do URL 调用后台的Controller会判断当前用户有没有“authorization”的权限 没有的话会被拦截到未授权页面unauthorized.do

   <!-- 未授权时要跳转的连接 -->
  <property name="unauthorizedUrl" value="unauthorized.do" />

 

在Realm中的AuthorizationInfo方法中添加“authorization” 权限即可 这里只是简单的添加 应该是从数据库遍历的

        // 授权方法
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		System.out.println("自定义的realm中授权方法执行的");
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		//为用户授权
		info.addStringPermission("authorization");
		
		//TODO 后期需要修改为根据当前登录用户查询数据库 获取实际对应的权限
		return info;
	}

还可以在controller方法开始中进行判断 以及还有页面中的标签使用 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值