spring+springMVC+shiro认证和授权

7 篇文章 0 订阅
2 篇文章 0 订阅
导入shiro jar包

在这里插入图片描述

导入spring jar包

在这里插入图片描述

导入springMVC jar包

spring-webmvc-4.2.5.RELEASE.jar

导入ehcache(缓存架包)

在这里插入图片描述

web.xml配置
 <!-- 注册spring提供的针对POST请求的中文乱码问题 -->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
  
    <!-- spring配置文件 -->
	<context-param>
	    <param-name>contextConfigLocation</param-name>
	    <param-value>classpath:spring_shiro.xml</param-value>
	</context-param>
	<listener>
	    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- SpringMVC的配置文件 -->
	<servlet>
	    <servlet-name>springDispatcherServlet</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <init-param>
	        <param-name>contextConfigLocation</param-name>
	        <param-value>classpath:springmvc.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	    <servlet-name>springDispatcherServlet</servlet-name>
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
   
    <!-- 添加shiro过滤器,用来拦截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>
spring_shiro.xml配置
<!-- 指定不扫描的包 -->
	<context:component-scan base-package="com.znsd.shiro">
		<!-- 排除@Controller注解的包 -->
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<!-- 排除@ControllerAdvice注解的包 -->
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	</context:component-scan>
	
	<!-- 3.配置实现了realm接口的bean -->
   <!--  <bean id="shiroRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm"></bean> -->
	
    <!-- 1.配置 securityManager管理器-->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	    <!-- 缓存管理器 -->
	    <property name="cacheManager" ref="cacheManager"/>
	    <!-- 配置session的管理方式 -->
	    <property name="realm" ref="shiroRealm"/>
		<!-- 添加了两种验证策略 -->
		<!-- <property name="realms">
			<list>
				<ref bean="shiroRealm"/>
				<ref bean="secondRealm"/>
			</list>
		</property> -->
	</bean>
	
	<bean id="multAuthenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
		<!-- 设置realms的验证策略 -->
		<property name="authenticationStrategy">
			<!-- 默认值,有任何一个策略生效,都可以成功 -->
			<!-- <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy" /> -->
			<!-- 必须满足所有的realms验证才可以成功 -->
			<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>
		</property>
	</bean>
	
	<!-- 2.配置缓存管理器,可以设置缓存 -->
	<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
	    <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
	</bean>
	
	<!-- 4.配置lifecycleBeanPostProcessor,可以自动调用配置在spring中的shrio对象生命周期方法。 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
	
	<!-- 5.启用IOC容器中的shiro注解,但必须在配置 lifecycleBeanPostProcessor 后才会生效。-->
	<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>
	
	<!-- 添加自定义的Relm规则 -->
	<bean id="shiroRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm">
		<property name="credentialsMatcher">
		    <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
		        <property name="hashAlgorithmName" value="MD5"></property>
	            <property name="hashIterations" value="10"></property>
		    </bean>
		</property>
	</bean>
	
	<!-- 3.配置实现了realm接口的bean -->
	<bean id="secondRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm">
		<!-- 自定义加密算法 -->
		<property name="credentialsMatcher">
			<!-- shiro通过HashedCredentialsMatcher完成各种加密算法的封装 -->
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
				<!-- 指定使用什么加密算法,md5,sha1 ... -->
				<property name="hashAlgorithmName" value="sha1" />
				<!-- 重复加密的次数 -->
				<property name="hashIterations" value="10" />
			</bean>
		</property>
	</bean>
	
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
	    <property name="securityManager" ref="securityManager"/>
	    <property name="loginUrl" value="/user/login"/>
	    <property name="successUrl" value="/admin/index"/>
	    <property name="unauthorizedUrl" value="/user/unauthorized"/>
	   <!--  <property name="filterChainDefinitions">
	        <value>
	            /user/login = anon
	            /index.jsp = anon
	            /admin/**= authc,roles[admin]
	            /user/unauthorized=roles[user]
	            /logout= logout
	            /** = authc
	        </value>
	    </property> -->
	    <!-- 通过工厂进行数据库查询权限 -->
	    <property name="filterChainDefinitionMap">
			<ref bean="filterMap"/>
		</property>
	</bean>
	<bean id="filterChainDefinitionMapFactory" class="com.znsd.shiro.ShiroRealm.FilterChainDefinitionMapFactory"></bean>
	<!-- 工厂构造器 -->
	<bean id="filterMap" factory-bean="filterChainDefinitionMapFactory" 
	factory-method="builderFilterChainDefinition"></bean>
springmvc.xml配置
<!-- 关闭默认的包扫描,限定智能扫描指定的包 -->
   <context:component-scan base-package="com.znsd.shiro" use-default-filters="false">
        <!-- 扫描@Controller注解扫描的包 -->
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		<!-- 扫描@ControllerAdvice注解扫描的包 -->
		<context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
   </context:component-scan>
	
	<!-- 拼装路径 -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/views/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>
    
    <!-- 注解驱动 -->
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<!-- 允许访问静态支援 -->
	<mvc:default-servlet-handler/>

认证

jsp页面进行登录
<form action="login" method="post">
	<table>
	   <tr>
	     <td>用户名:</td>
	     <td><input type="text" name="name"/></td>
	   </tr>
	   <tr>
	     <td>密码:</td>
	     <td><input type="password" name="password"/></td>
	   </tr>
	   <tr>
	     <td>登录</td>
	     <td><input type="submit"/></td>
	   </tr>
	</table>
</form>
验证用户
@RequestMapping(value = "/login",method = RequestMethod.POST)
	public String logins(User user) {
		Subject currentUser = SecurityUtils.getSubject();
        if (!currentUser.isAuthenticated()) {
            UsernamePasswordToken token = new UsernamePasswordToken(user.getName(),user.getPassword());
            //记住密码
            token.setRememberMe(true);
            try {
                //这里会调用认证方法
                currentUser.login(token);
                System.out.println("登录成功!");
                return "welcome";
            } catch (UnknownAccountException uae) {
            	System.out.println("用户名错误"+token.getPrincipal());
            } catch (IncorrectCredentialsException ice) {
            	System.out.println("密码错误"+token.getPrincipal());
            } catch (LockedAccountException lae) {
            	System.err.println("账号已经锁定"+token.getPrincipal());
            }
            catch (AuthenticationException ae) {
            	System.out.println("发生其他错误!");
            	throw ae;
            }
        }
        return "login";
	}
进行认证
public class ShiroRealm extends AuthenticatingRealm{
	
	//认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		 //①、把AuthenticationToken转换为UsernamePasswordToken。
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		//②、从UsernamePasswordToken中获取username
		String username = upToken.getUsername();
		//③、调用数据库的方法,从数据库中查询username对应的记录。
		UserService userService = new UserService();
		User user = userService.login(username);
		//④、若用户不存在,则可以跑出UnknownAccountException异常。
		if(user == null) {
			throw new UnknownAccountException("用户不存在");
		}
		//⑤、根据用户信息的情况,决定是否需要抛出其它AuthenticationException异常。
		if(user.isLock()) {
			throw new LockedAccountException("用户被锁定");
		}
		//盐值
		ByteSource salt = ByteSource.Util.bytes("www.znsd.com");
		//⑥、根据用户的情况,来构建AuthenticationInfo对象并返回。
		AuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
		return info;
	}
这里我只是模拟一下,真正的还是要查询数据库的
@Service
public class UserService {
	public User login(String name) {
		if("admin".equals(name)) {
		    //ture就是锁定的意思
			User user=new User("admin","5489abfd2e375f20485584c704a1a9da",false);
			return user;
		}
		if("zhangsan".equals(name)) {
			User user=new User("张三","b961a66f118748a2b9d73d72c65870b7",false);
			return user;
		}
		return null;
	}
}

授权(在认证的基础上进行添加)

在这里的授权的意思是一些页面需要授权给用户才能访问一些页面。

授权要实现AuthorizingRealm,刚好是AuthenticatingRealm认证的子类,所以有两个方法。
public class ShiroRealm extends AuthorizingRealm{
	
	//认证方法
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		 //①、把AuthenticationToken转换为UsernamePasswordToken。
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		//②、从UsernamePasswordToken中获取username
		String username = upToken.getUsername();
		//③、调用数据库的方法,从数据库中查询username对应的记录。
		UserService userService = new UserService();
		User user = userService.login(username);
		//④、若用户不存在,则可以跑出UnknownAccountException异常。
		if(user == null) {
			throw new UnknownAccountException("用户不存在");
		}
		//⑤、根据用户信息的情况,决定是否需要抛出其它AuthenticationException异常。
		if(user.isLock()) {
			throw new LockedAccountException("用户被锁定");
		}
		//盐值
		ByteSource salt = ByteSource.Util.bytes("www.znsd.com");
		//⑥、根据用户的情况,来构建AuthenticationInfo对象并返回。
		AuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
		return info;
	}
	
	//授权方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		System.out.println("执行授权的操作!");
		// 授权方法的步骤:
		// 1、从PrincipalCollection中来获取登录用户的信息。
		User user = (User)principals.getPrimaryPrincipal();
		// 2、利用登录用户的信息来验证当前用户的角色或者权限。
		Set<String> roles = new HashSet<>();
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		roles.add("user");
		if ("admin".equals(user.getName())) {
		    roles.add("admin");
		    roles.add("user:query");
			info.setStringPermissions(roles);
		}
		return info;
	}
}
添加了两种验证策略(其实上面已经配置了的,只是单独拿出来,比较好看点)
 <!-- 1.配置 securityManager管理器-->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	    <!-- 缓存管理器 -->
	    <property name="cacheManager" ref="cacheManager"/>
	    <!-- 配置session的管理方式 -->
	    <property name="realm" ref="shiroRealm"/>
		<!-- 设置多个realms的验证策略 -->
		<property name="authenticator" ref="multAuthenticator" />
		<!-- 添加了两种验证策略 -->
		<property name="realms">
			<list>
				<ref bean="shiroRealm"/>
				<ref bean="secondRealm"/>
			</list>
		</property>
	</bean>
	<bean id="multAuthenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
		<!-- 设置realms的验证策略 -->
		<property name="authenticationStrategy">
			<!-- 默认值,有任何一个策略生效,都可以成功 -->
			<!-- <bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy" /> -->
			<!-- 必须满足所有的realms验证才可以成功 -->
			<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"></bean>
		</property>
	</bean>
	
	<!-- 添加自定义的Relm规则 -->
	<bean id="shiroRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm">
		<property name="credentialsMatcher">
		    <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
		        <property name="hashAlgorithmName" value="MD5"></property>
	            <property name="hashIterations" value="10"></property>
		    </bean>
		</property>
	</bean>
	
	<!-- 3.配置实现了realm接口的bean -->
	<bean id="secondRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm">
		<!-- 自定义加密算法 -->
		<property name="credentialsMatcher">
			<!-- shiro通过HashedCredentialsMatcher完成各种加密算法的封装 -->
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
				<!-- 指定使用什么加密算法,md5,sha1 ... -->
				<property name="hashAlgorithmName" value="sha1" />
				<!-- 重复加密的次数 -->
				<property name="hashIterations" value="10" />
			</bean>
		</property>
	</bean>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值