springmvc + shiro 使用

maven依赖:

<properties>
		<spring.version>4.0.0.RELEASE</spring.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>cglib</groupId>
			<artifactId>cglib</artifactId>
			<version>2.2</version>
		</dependency>


		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.9.6</version>
		</dependency>

		<dependency>
			<groupId>commons-logging</groupId>
			<artifactId>commons-logging</artifactId>
			<version>1.1.3</version>
		</dependency>


		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.6.8</version>
		</dependency>

		<dependency>
			<groupId>aopalliance</groupId>
			<artifactId>aopalliance</artifactId>
			<version>1.0</version>
		</dependency>


		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aspects</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-beans</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context-support</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-expression</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>

		<dependency>
			<groupId>org.apache.shiro</groupId>
			<artifactId>shiro-all</artifactId>
			<version>1.3.2</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>1.6.1</version>
		</dependency>

		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.6.1</version>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache-core</artifactId>
			<version>2.4.3</version>
		</dependency>

		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>4.0.1</version>
			<scope>provided</scope>
		</dependency>

	</dependencies>

spring视图配置:

<?xml version="1.0" encoding="UTF-8"?>
<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"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

	<context:component-scan base-package="com.xxx.shiro"></context:component-scan>

	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/"></property>
		<property name="suffix" value=".jsp"></property>
	</bean>

	<mvc:annotation-driven></mvc:annotation-driven>
	<mvc:default-servlet-handler />


</beans>

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" id="iplat4j-core" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	metadata-complete="true">

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>spring</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>spring</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>


	<!-- shiro 安全过滤器 -->
	<filter>
		 <!--spring调用shiro代理-->
		<filter-name>shiroFilter</filter-name>
		<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
		<init-param>
			<!--是否开启Filter的生命周期,主要涉及init和destory-->
			<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>


</web-app>

applicationContext-shiro配置:

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


	<!-- 1. 配置securityManager,也就是shiro的核心。 -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="authenticator" ref="authenticator" />
		<!-- 缓存管理器 -->
		<property name="cacheManager" ref="cacheManager" />

		<property name="realms">
			<list>
				<ref bean="myRealm" />
				<ref bean="secondRealm" />
			</list>
		</property>
	</bean>

	<!-- 2. 配置cacheManager(缓存管理) -->
	<!-- 2.1.1需要加入ehcache的jar包及配置文件 -->
	<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<!-- <property name="cacheManagerConfigFile" value="classpath:ehcache.xml"></property> -->
	</bean>

	<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
		<!-- 认证策略 全部成功才能通过 -->
		<property name="authenticationStrategy">
			<bean class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"></bean>
		</property>
	</bean>

	<!-- 3. 配置Realm,自己定义的shiroRealm,必须实现org.apache.shiro.realm.Realm这个接口 -->
	<bean id="myRealm" class="com.atguigu.shiro.realms.ShiroRealm">
		<!-- 配置密码的加密方式 -->
		<property name="credentialsMatcher">
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
				<property name="hashAlgorithmName" value="MD5"></property>
				<!-- 密码加密次数 -->
				<property name="hashIterations" value="1024"></property>
			</bean>
		</property>
	</bean>

	<!-- 多realm配置方式 -->
	<bean id="secondRealm" class="com.atguigu.shiro.realms.SecondRealm">
		<!-- 配置密码的加密方式 -->
		<property name="credentialsMatcher">
			<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
				<property name="hashAlgorithmName" value="SHA1"></property>
				<!-- 密码加密次数 -->
				<property name="hashIterations" value="1024"></property>
			</bean>
		</property>
	</bean>

	<!-- 4.配置lifecycleBeanPostProcessor, 可以自动的来调用配置在spring IOC 容器中shiro bean的生命周期方法 -->
	<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>

	<!-- 6. 配置shiroFilter 6.1 id必须和web.xml 文件中配置的DelegatingFilterProxy的filter-name一致 -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<property name="loginUrl" value="/login.jsp" />
		<property name="successUrl" value="/list.jsp" />
		<property name="unauthorizedUrl" value="/unauthorized.jsp" />
		
		<property name="filterChainDefinitions" ref="filterChainDefinitionMap" />
		
		<!-- 配置哪些页面需要受保护 以及访问这些页面需要的权限 anon可以被匿名访问,或者说游客可以访问 authc 必须认证之后才能访问,即登录后才能访问的页面 -->
<!-- 		<property name="filterChainDefinitions">
			<value>
				/login.jsp = anon
				/shiro/login = anon
				/shiro/shiro/logout = logout
				
				/shiro/shiro/user = roles[user]
				/shiro/shiro/admin= roles[admin]
				
				/** = authc
			</value>
		</property> -->

	</bean>
	
	<!-- 配置一个bean,该bean 实际上是一个map,通过实例工厂方法的方式-->
	<bean id="filterChainDefinitionMap" 
		factory-bean="filterChainDefinitionMapBuilder" factory-method="buildFilterChainDefinitionMap">
	</bean>

	<bean id="filterChainDefinitionMapBuilder" class="com.atguigu.shiro.factory.FilterChainDefinitionMapBuilder">
	</bean>

	<bean id="shiroService" class="com.atguigu.shiro.services.ShiroService">
	</bean>


</beans>

ShiroHandler 类:

@Controller
@RequestMapping("/shiro")
public class ShiroHandler {

	@Autowired
	private ShiroService shiroService;
	
	@RequestMapping("/shiro/testShiroAnnotation")
	public String testShiroAnnotation(HttpSession session){
		session.setAttribute("key", "value12345");
		
		shiroService.testMethod();
		return "redirect:/list.jsp";
	}
	
	@RequestMapping("/login")
	public String login(@RequestParam("username") String username, @RequestParam("password") String password) {
		Subject currentUser = SecurityUtils.getSubject();

		if (!currentUser.isAuthenticated()) {
			// 把用户名和密码封装成UsernamePasswordToken 对象
			UsernamePasswordToken token = new UsernamePasswordToken(username, password);
			// rememberMe
			token.setRememberMe(true);
			try {
				// 执行登录
				currentUser.login(token);
			} catch (AuthenticationException ae) {
				System.out.println("登录失败:" + ae.getMessage());
			}
		}

		return "list";
	}

	@RequestMapping("/shiro/admin")
	public String admin() {
		return "admin";
	}

	@RequestMapping("/shiro/user")
	public String user() {
		return "user";
	}
}

ShiroService:

public class ShiroService {

	//权限注解
	@RequiresRoles({"admin"})
	public void testMethod() {
		System.out.println("testMethod,time: " + new Date());
		
		//通过shiro 获取ShiroHandler.testShiroAnnotation 设置的session里面的值
		Session session = SecurityUtils.getSubject().getSession();
		Object val = session.getAttribute("key");
		
		System.out.println("SessionVal: " + val);
	}
}

ShiroRealm:

public class ShiroRealm extends AuthorizingRealm {

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("[FirstRealm] doGetAuthenticationInfo");
		
		//1.把AuthenticationToken 转换为UsernamePasswordToken对象
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		
		//2.从UsernamePasswordToken 中获取username
		String username = upToken.getUsername();
		
		//3.调用数据库的方法,从数据库中查询username对应的用户记录
		System.out.println("从数据库中获取username: " + username + " 所对应的信息");
		
		//4.若用户不存在,则可以抛出 UnknownAccountException 异常
		if("unknown".equals(username))
			throw new UnknownAccountException("用户不存在");
		
		//5.根据用户信息的情况,决定是否需要抛出其他的AuthenticationException异常
		if("monster".equals(username))
			throw new LockedAccountException("用户被锁定");
		
		//6.根据用户的情况,来构建  AuthenticationInfo 对象并返回 ,通常使用的对象为 SimpleAuthenticationInfo
		//以下信息是从数据库中获取的
		//1.principal: 认证的实体信息,可以是username,也可也是数据库查询出的实体信息
		Object principal = username;
		//2.credentials:密码
		Object credentials = null; //"fc1709d0a95a6be30bc5926fdb7f22f4";
		if("admin".equals(username)){
			credentials = "038bdaf98f2037b31f1e75b5b4c9b26e";
		}else if("user".equals(username)){
			credentials = "098d2c478e9c11555ce2823231e02ec1";
		}
			
		
		//3.realmName:当前realm 对象的name,调用父类的getName方法获取
		String realmName = getName();
		//4.盐值
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		
		SimpleAuthenticationInfo info = null;
		info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
		
		return info;
	}
	
	public static void main(String[] args) {
		String algorithmName = "MD5";
		Object source = "123456";
		Object salt = ByteSource.Util.bytes("user");
		int hashIterations = 1024;
		Object result = new SimpleHash(algorithmName, source, salt, hashIterations);
		System.out.println(result);
	}

	//授权会被shiro回调的方法
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		//1.从 PrincipalCollection 中获取登录用户的信息
		Object principal = principals.getPrimaryPrincipal();
		
		//2.利用登录的用户信息来进当前用户的角色权限设置
		Set<String> roles = new HashSet<>();
		roles.add("user");
		if("admin".equals(principal)){
			roles.add("admin");
		}
		
		//3.创建 SimpleAuthorizationInfo,并设置 reles 属性
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		
		//4.返回 SimpleAuthorizationInfo 对象
		return info;
	}

}

SecondRealm:

public class SecondRealm extends AuthenticatingRealm {

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("[SecondRealm] doGetAuthenticationInfo");
		
		//1.把AuthenticationToken 转换为UsernamePasswordToken对象
		UsernamePasswordToken upToken = (UsernamePasswordToken) token;
		
		//2.从UsernamePasswordToken 中获取username
		String username = upToken.getUsername();
		
		//3.调用数据库的方法,从数据库中查询username对应的用户记录
		System.out.println("从数据库中获取username: " + username + " 所对应的信息");
		
		//4.若用户不存在,则可以抛出 UnknownAccountException 异常
		if("unknown".equals(username))
			throw new UnknownAccountException("用户不存在");
		
		//5.根据用户信息的情况,决定是否需要抛出其他的AuthenticationException异常
		if("monster".equals(username))
			throw new LockedAccountException("用户被锁定");
		
		//6.根据用户的情况,来构建  AuthenticationInfo 对象并返回 ,通常使用的对象为 SimpleAuthenticationInfo
		//以下信息是从数据库中获取的
		//1.principal: 认证的实体信息,可以是username,也可也是数据库查询出的实体信息
		Object principal = username;
		//2.credentials:密码
		Object credentials = null; //"fc1709d0a95a6be30bc5926fdb7f22f4";
		if("admin".equals(username)){
			credentials = "ce2f6417c7e1d32c1d81a797ee0b499f87c5de06";
		}else if("user".equals(username)){
			credentials = "073d4c3ae812935f23cb3f2a71943f49e082a718";
		}
			
		
		//3.realmName:当前realm 对象的name,调用父类的getName方法获取
		String realmName = getName();
		//4.盐值
		ByteSource credentialsSalt = ByteSource.Util.bytes(username);
		
		SimpleAuthenticationInfo info = null;
		info = new SimpleAuthenticationInfo(principal, credentials, credentialsSalt, realmName);
		
		return info;
	}
	
	public static void main(String[] args) {
		String algorithmName = "SHA1";
		Object source = "123456";
		Object salt = ByteSource.Util.bytes("admin");
		int hashIterations = 1024;
		Object result = new SimpleHash(algorithmName, source, salt, hashIterations);
		System.out.println(result);
	}

}

FilterChainDefinitionMapBuilder:

public class FilterChainDefinitionMapBuilder {

	public LinkedHashMap<String, String> buildFilterChainDefinitionMap() {
		LinkedHashMap<String, String> map = new LinkedHashMap<>();

		map.put("/login.jsp", "anon");
		// /shiro/login = anon
		map.put("/shiro/login", "anon");
		
		
		map.put("/**", "authc");
		
		
		return map;
	}
}

login.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>Login Page</h4>
	
	<form action="shiro/login" method="POST">
		username: <input type="text" name="username"/>
		<br><br>
		
		password: <input type="password" name="password"/>
		
		<input type="submit" value="submit"/>
	</form>
	
</body>
</html>

 

list.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>    
    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>List Page</h4>
	
	Welcome: <shiro:principal></shiro:principal>
	
	<shiro:hasRole name="admin">
	<br><br>
	<a href="shiro/admin">Admin Jsp</a>
	</shiro:hasRole>
	
	<shiro:hasRole name="user">
	<br><br>
	<a href="shiro/user">User Jsp</a>
	</shiro:hasRole>
	
	<br><br>
	<a href="shiro/testShiroAnnotation">Test ShiroAnnotation</a>
	
	
	<br><br>
	<a href="shiro/logout">Logout</a>
</body>
</html>

admin.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>Admin Page</h4>
</body>
</html>

user.jsp:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
	<h4>User Page</h4>
</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值