青岛达内it培训 > 达内新闻
学习如何使用Shiro(6)
- 发布:青岛达内
- 来源:达内新闻
- 时间:2019-01-30 20:25
如果希望在WEB环境中使用Shiro必须首先在web.xml文件中配置-青岛达内负责整理
<?xml version=“1.0” encoding=“UTF-8”?>
<web-app xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xmlns=“#/xml/ns/javaee”
xsi:schemaLocation=“#/xml/ns/javaee #/xml/ns/javaee/web-app_3_0.xsd”
id=“WebApp_ID” version=“3.0”>
<display-name>Shiro_Project</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringMVC</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>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 将Shiro的配置文件交给Spring监听器初始化 -->
<param-value>classpath:spring.xml,classpath:spring-shiro-web.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLoaction</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- shiro配置 开始 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
<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>
<!-- shiro配置 结束 -->
</web-app>
熟悉Spring配置的同学可以重点看有绿字注释的部分,这里是使Shiro生效的关键。由于项目通过Spring管理,因此所有的配置原则上都是交给Spring.DelegatingFilterProxy的功能是通知Spring将所有的Filter交给ShiroFilter管理。
接着在classpath路径下配置spring-shiro-web.xml文件
<beans xmlns=“#/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:p=“#/schema/p”
xmlns:context=“#/schema/context”
xmlns:mvc=“#/schema/mvc”
xsi:schemaLocation=“#/schema/beans
#/schema/beans/spring-beans-3.1.xsd
#/schema/context
#/schema/context/spring-context-3.1.xsd
#/schema/mvc
#/schema/mvc/spring-mvc-4.0.xsd”>
<!-- 缓存管理器 使用Ehcache实现 -->
<bean id=“cacheManager” class=“org.apache.shiro.cache.ehcache.EhCacheManager”>
<property name=“cacheManagerConfigFile” value=“classpath:ehcache.xml” />
</bean>
<!-- 凭证匹配器 -->
<bean id=“credentialsMatcher” class=“utils.RetryLimitHashedCredentialsMatcher”>
<constructor-arg ref=“cacheManager” />
<property name=“hashAlgorithmName” value=“md5” />
<property name=“hashIterations” value=“2” />
<property name=“storedCredentialsHexEncoded” value=“true” />
</bean>
<!-- Realm实现 -->

<bean id=“userRealm” class=“utils.UserRealm”>
<property name=“credentialsMatcher” ref=“credentialsMatcher” />
</bean>
<!-- 安全管理器 -->
<bean id=“securityManager” class=“org.apache.shiro.web.mgt.DefaultWebSecurityManager”>
1
</bean>
<!-- Shiro的Web过滤器 -->
<bean id=“shiroFilter” class=“org.apache.shiro.spring.web.ShiroFilterFactoryBean”>
<property name=“securityManager” ref=“securityManager” />
<property name=“loginUrl” value=“/” />
<property name=“unauthorizedUrl” value=“/” />
<property name=“filterChainDefinitions”>
<value>
/authc/admin = roles[admin]
/authc/** = authc
/** = anon
</value>
</property>
</bean>
<bean id=“lifecycleBeanPostProcessor” class=“org.apache.shiro.spring.LifecycleBeanPostProcessor” />
</beans>
需要注意filterChainDefinitions过滤器中对于路径的配置是有顺序的,当找到匹配的条目之后容器不会再继续寻找。因此带有通配符的路径要放在后面。三条配置的含义是:
/authc/admin需要用户有用admin权限
/authc/**用户必须登录才能访问
/**其他所有路径任何人都可以访问
说了这么多,大家一定关心在Spring中引入Shiro之后到底如何编写登录代码呢。
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping(“login”)
public ModelAndView login(@RequestParam(“username”) String username, @RequestParam(“password”) String password) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (IncorrectCredentialsException ice) {
// 捕获密码错误异常
ModelAndView mv = new ModelAndView(“error”);
mv.addObject(“message”, “password error!”);
return mv;
} catch (UnknownAccountException uae) {
// 捕获未知用户名异常
ModelAndView mv = new ModelAndView(“error”);
mv.addObject(“message”, “username error!”);
return mv;
} catch (ExcessiveAttemptsException eae) {
// 捕获错误登录过多的异常
ModelAndView mv = new ModelAndView(“error”);
mv.addObject(“message”, “times error”);
return mv;
}
User user = userService.findByUsername(username);
subject.getSession()。setAttribute(“user”, user);
return new ModelAndView(“success”);
}
}
登录完成以后,当前用户信息被保存进Session.这个Session是通过Shiro管理的会话对象,要获取依然必须通过Shiro.传统的Session中不存在User对象。
@Controller
@RequestMapping(“authc”)
public class AuthcController {
// /authc/** = authc 任何通过表单登录的用户都可以访问
@RequestMapping(“anyuser”)
public ModelAndView anyuser() {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getSession()。getAttribute(“user”);
System.out.println(user);
return new ModelAndView(“inner”);
}
// /authc/admin = user[admin] 只有具备admin角色的用户才可以访问,否则请求将被重定向至登录界面
@RequestMapping(“admin”)
public ModelAndView admin() {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getSession()。getAttribute(“user”);
System.out.println(user);
return new ModelAndView(“inner”);
}
}
以上就是青岛达内给大家做的内容详解,更多关于UI的学习,请继续关注青岛达内
最新开班时间
- 北京
- 上海
- 广州
- 深圳
- 南京
- 成都
- 武汉
- 西安
- 青岛
- 天津
- 杭州
- 重庆
- 哈尔滨
- 济南
- 沈阳
- 合肥
- 郑州
- 长春
- 苏州
- 长沙
- 昆明
- 太原
- 无锡
- 石家庄
- 南宁
- 佛山
- 珠海
- 宁波
- 保定
- 呼和浩特
- 洛阳
- 烟台
- 运城
- 潍坊
学习如何使用Shiro(6)
- 发布:青岛达内
- 来源:达内新闻
- 时间:2019-01-30 20:25
如果希望在WEB环境中使用Shiro必须首先在web.xml文件中配置-青岛达内负责整理
<?xml version=“1.0” encoding=“UTF-8”?>
<web-app xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xmlns=“#/xml/ns/javaee”
xsi:schemaLocation=“#/xml/ns/javaee #/xml/ns/javaee/web-app_3_0.xsd”
id=“WebApp_ID” version=“3.0”>
<display-name>Shiro_Project</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>SpringMVC</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>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<!-- 将Shiro的配置文件交给Spring监听器初始化 -->
<param-value>classpath:spring.xml,classpath:spring-shiro-web.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLoaction</param-name>
<param-value>classpath:log4j.properties</param-value>
</context-param>
<!-- shiro配置 开始 -->
<filter>
<filter-name>shiroFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<async-supported>true</async-supported>
<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>
<!-- shiro配置 结束 -->
</web-app>
熟悉Spring配置的同学可以重点看有绿字注释的部分,这里是使Shiro生效的关键。由于项目通过Spring管理,因此所有的配置原则上都是交给Spring.DelegatingFilterProxy的功能是通知Spring将所有的Filter交给ShiroFilter管理。
接着在classpath路径下配置spring-shiro-web.xml文件
<beans xmlns=“#/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:p=“#/schema/p”
xmlns:context=“#/schema/context”
xmlns:mvc=“#/schema/mvc”
xsi:schemaLocation=“#/schema/beans
#/schema/beans/spring-beans-3.1.xsd
#/schema/context
#/schema/context/spring-context-3.1.xsd
#/schema/mvc
#/schema/mvc/spring-mvc-4.0.xsd”>
<!-- 缓存管理器 使用Ehcache实现 -->
<bean id=“cacheManager” class=“org.apache.shiro.cache.ehcache.EhCacheManager”>
<property name=“cacheManagerConfigFile” value=“classpath:ehcache.xml” />
</bean>
<!-- 凭证匹配器 -->
<bean id=“credentialsMatcher” class=“utils.RetryLimitHashedCredentialsMatcher”>
<constructor-arg ref=“cacheManager” />
<property name=“hashAlgorithmName” value=“md5” />
<property name=“hashIterations” value=“2” />
<property name=“storedCredentialsHexEncoded” value=“true” />
</bean>
<!-- Realm实现 -->

<bean id=“userRealm” class=“utils.UserRealm”>
<property name=“credentialsMatcher” ref=“credentialsMatcher” />
</bean>
<!-- 安全管理器 -->
<bean id=“securityManager” class=“org.apache.shiro.web.mgt.DefaultWebSecurityManager”>
1
</bean>
<!-- Shiro的Web过滤器 -->
<bean id=“shiroFilter” class=“org.apache.shiro.spring.web.ShiroFilterFactoryBean”>
<property name=“securityManager” ref=“securityManager” />
<property name=“loginUrl” value=“/” />
<property name=“unauthorizedUrl” value=“/” />
<property name=“filterChainDefinitions”>
<value>
/authc/admin = roles[admin]
/authc/** = authc
/** = anon
</value>
</property>
</bean>
<bean id=“lifecycleBeanPostProcessor” class=“org.apache.shiro.spring.LifecycleBeanPostProcessor” />
</beans>
需要注意filterChainDefinitions过滤器中对于路径的配置是有顺序的,当找到匹配的条目之后容器不会再继续寻找。因此带有通配符的路径要放在后面。三条配置的含义是:
/authc/admin需要用户有用admin权限
/authc/**用户必须登录才能访问
/**其他所有路径任何人都可以访问
说了这么多,大家一定关心在Spring中引入Shiro之后到底如何编写登录代码呢。
@Controller
public class LoginController {
@Autowired
private UserService userService;
@RequestMapping(“login”)
public ModelAndView login(@RequestParam(“username”) String username, @RequestParam(“password”) String password) {
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
Subject subject = SecurityUtils.getSubject();
try {
subject.login(token);
} catch (IncorrectCredentialsException ice) {
// 捕获密码错误异常
ModelAndView mv = new ModelAndView(“error”);
mv.addObject(“message”, “password error!”);
return mv;
} catch (UnknownAccountException uae) {
// 捕获未知用户名异常
ModelAndView mv = new ModelAndView(“error”);
mv.addObject(“message”, “username error!”);
return mv;
} catch (ExcessiveAttemptsException eae) {
// 捕获错误登录过多的异常
ModelAndView mv = new ModelAndView(“error”);
mv.addObject(“message”, “times error”);
return mv;
}
User user = userService.findByUsername(username);
subject.getSession()。setAttribute(“user”, user);
return new ModelAndView(“success”);
}
}
登录完成以后,当前用户信息被保存进Session.这个Session是通过Shiro管理的会话对象,要获取依然必须通过Shiro.传统的Session中不存在User对象。
@Controller
@RequestMapping(“authc”)
public class AuthcController {
// /authc/** = authc 任何通过表单登录的用户都可以访问
@RequestMapping(“anyuser”)
public ModelAndView anyuser() {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getSession()。getAttribute(“user”);
System.out.println(user);
return new ModelAndView(“inner”);
}
// /authc/admin = user[admin] 只有具备admin角色的用户才可以访问,否则请求将被重定向至登录界面
@RequestMapping(“admin”)
public ModelAndView admin() {
Subject subject = SecurityUtils.getSubject();
User user = (User) subject.getSession()。getAttribute(“user”);
System.out.println(user);
return new ModelAndView(“inner”);
}
}
以上就是青岛达内给大家做的内容详解,更多关于UI的学习,请继续关注青岛达内
最新开班时间
- 北京
- 上海
- 广州
- 深圳
- 南京
- 成都
- 武汉
- 西安
- 青岛
- 天津
- 杭州
- 重庆
- 厦门
- 哈尔滨
- 济南
- 福州
- 沈阳
- 合肥
- 郑州
- 长春
- 苏州
- 大连
- 长沙
- 昆明
- 温州
- 太原
- 南昌
- 无锡
- 石家庄
- 南宁
- 中山
- 兰州
- 佛山
- 珠海
- 宁波
- 贵阳
- 保定
- 呼和浩特
- 东莞
- 洛阳
- 潍坊
- 烟台
- 运城