一、POM依赖
注意和Spring和SpringMVC的版本兼容
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-core</artifactId>
<version>1.4.0</version>
</dependency>
<dependency>
<groupId>org.apache.shiro</groupId>
<artifactId>shiro-spring</artifactId>
<version>1.4.0</version>
</dependency>
二、Spring配置文件需要添加的东西(Spring就是对所有的bean管理,而注解什么的由SpringMVC配置文件管理,所以关于Shiro的元素都需要放至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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- Spring配置文件 -->
<!--Shiro过滤器-->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<!--设置Shiro的securityManager-->
<property name="securityManager" ref="securityManager"/>
<!--登录网址-->
<property name="loginUrl" value="login.html"/>
<!--未授权网址-->
<property name="unauthorizedUrl" value="403.html"/>
<!--过滤器链 anon匿名访问的路径 authc必须验证通过才能访问的路径 配置在前面的优先生效!-->
<property name="filterChainDefinitions">
<value>
/login.html = anon
/sublogin = anon
/* = authc
</value>
</property>
</bean>
<!--配置securityManager,注意在Spring中使用的是DefaultWebSecurityManager,在非web环境下,使用DefaultSecurityManager-->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--配置数据源-->
<property name="realm" ref="realm"/>
</bean>
<!--配置数据源-->
<bean id="realm" class="org.pc.util.CustomRealm">
<!--配置加密对象-->
<property name="credentialsMatcher" ref="matcher"/>
</bean>
<!--配置加密对象-->
<bean id="matcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!--加密算法-->
<property name="hashAlgorithmName" value="md5"/>
<!--加密次数-->
<property name="hashIterations" value="1"/>
</bean>
</beans>
三、web.xml中配置shrio过滤器
<!--配置shiroFilter过滤器-->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>shiroFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
四、案例验证
@Controller
public class LoginController {
/**
* produces = "application/json;charset=utf-8":解决返回中文乱码问题
* 注意:以上解决办法仅限于SpringMVC框架返回json数据出错的问题,如果加入jackson对json处理,就不会出现乱码问题
*/
@PostMapping(value = "/sublogin", produces = "application/json;charset=utf-8")
@ResponseBody
public String login(User user){
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
try {
subject.login(token);
} catch (AuthenticationException e) {
return e.getMessage();
}
return "登陆成功";
}
}