spring+springMVC+shiro认证和授权

导入shiro jar包

spring+springMVC+shiro认证和授权_第1张图片

导入spring jar包

spring+springMVC+shiro认证和授权_第2张图片

导入springMVC jar包

spring-webmvc-4.2.5.RELEASE.jar

导入ehcache(缓存架包)

在这里插入图片描述

web.xml配置

 
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>UTF-8param-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>
  
    
	<context-param>
	    <param-name>contextConfigLocationparam-name>
	    <param-value>classpath:spring_shiro.xmlparam-value>
	context-param>
	<listener>
	    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
	listener>
	
	
	<servlet>
	    <servlet-name>springDispatcherServletservlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
	    <init-param>
	        <param-name>contextConfigLocationparam-name>
	        <param-value>classpath:springmvc.xmlparam-value>
	    init-param>
	    <load-on-startup>1load-on-startup>
	servlet>
	<servlet-mapping>
	    <servlet-name>springDispatcherServletservlet-name>
	    <url-pattern>/url-pattern>
	servlet-mapping>
   
    
	<filter>
	    <filter-name>shiroFilterfilter-name>
	    <filter-class>
		    org.springframework.web.filter.DelegatingFilterProxy
	    filter-class>
	    <init-param>
	        <param-name>targetFilterLifecycleparam-name>
	        <param-value>trueparam-value>
	    init-param>
	filter>
	<filter-mapping>
	    <filter-name>shiroFilterfilter-name>
	    <url-pattern>/*url-pattern>
	filter-mapping>

spring_shiro.xml配置


	<context:component-scan base-package="com.znsd.shiro">
		
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		
		<context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
	context:component-scan>
	
	
   
	
    
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	    
	    <property name="cacheManager" ref="cacheManager"/>
	    
	    <property name="realm" ref="shiroRealm"/>
		
		
	bean>
	
	<bean id="multAuthenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
		
		<property name="authenticationStrategy">
			
			
			
			<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy">bean>
		property>
	bean>
	
	
	<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
	    <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/> 
	bean>
	
	
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.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>
	
	
	<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>
	
	
	<bean id="secondRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm">
		
		<property name="credentialsMatcher">
			
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
				
				<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="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">
        
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
		
		<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;
	}
}

添加了两种验证策略(其实上面已经配置了的,只是单独拿出来,比较好看点)

 
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
	    
	    <property name="cacheManager" ref="cacheManager"/>
	    
	    <property name="realm" ref="shiroRealm"/>
		
		<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">
		
		<property name="authenticationStrategy">
			
			
			
			<bean class="org.apache.shiro.authc.pam.AllSuccessfulStrategy">bean>
		property>
	bean>
	
	
	<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>
	
	
	<bean id="secondRealm" class="com.znsd.shiro.ShiroRealm.ShiroRealm">
		
		<property name="credentialsMatcher">
			
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
				
				<property name="hashAlgorithmName" value="sha1" />
				
				<property name="hashIterations" value="10" />
			bean>
		property>
	bean>

你可能感兴趣的:(spring,springMVC,shiro)