本文主要是介绍shiro的使用入门,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
shiro是一个权限控制框架,因为项目需要自己看了看,在这里把所有学到的分享一下。shiro主要由AuthorizationInfo、AuthenticationInfo、Subject构成一个权限环境,doGetAuthenticationInfo方法是用户登录的使用调用的( subject.login(token);),doGetAuthorizationInfo方法是在用户进行权限验证的时候调用的( boolean isOk=subject.isPermitted(url);)。
下面我们来看看一个真正的项目中使用shiro需要做哪些操作。
1、配置web.xml文件
<!-- 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>
2、配置shiro.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:util="http://www.springframework.org/schema/util"
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
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">
<description>apache shiro配置</description>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"/>
<property name="loginUrl" value="/"/>
<property name="successUrl" value="/jsp/main"/>
<property name="unauthorizedUrl" value="/rest/page/401"/>
<property name="filterChainDefinitions">
<value>
<!-- 静态资源允许访问 -->
/app/** = anon
/login = anon
<!-- 登录页允许访问 -->
/rest/user/login = anon
/=anon
<!-- 其他资源需要认证 -->
/** = authc
</value>
</property>
</bean>
<!-- 缓存管理器 使用Ehcache实现 -->
<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache-shiro.xml"/>
</bean>
<!-- 会话DAO -->
<bean id="sessionDAO" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO"/>
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="sessionDAO" ref="sessionDAO"/>
</bean>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realms">
<list>
<ref bean="myRealms"/>
</list>
</property>
<!-- cacheManager,集合spring缓存工厂 -->
<!-- <property name="cacheManager" ref="shiroEhcacheManager" /> -->
<!-- <property name="sessionManager" ref="sessionManager" /> -->
</bean>
<bean id="myRealms" class="com.lintian.util.MyRealms"></bean>
<!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
3、安全管理器MyRealms.java
package com.lintian.util;
import java.util.ArrayList;
import java.util.List;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import com.lintian.entity.Permission;
import com.lintian.entity.Role;
import com.lintian.entity.User;
import com.lintian.service.UserService;
@Service
public class MyRealms extends AuthorizingRealm {
@Autowired
private UserService userService;
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
//获取当前登录的用户名
String account = (String) super.getAvailablePrincipal(principals);
List<String> roles = new ArrayList<String>();
List<String> permissions = new ArrayList<String>();
User user = userService.getByAccount(account);//获取用户
if(user != null){
if (user.getRoles() != null && user.getRoles().size() > 0) {
for (Role role : user.getRoles()) {
roles.add(role.getRoleName());
if (role.getPermissions() != null && role.getPermissions().size() > 0) {
for (Permission pmss : role.getPermissions()) {
if(!StringUtils.isEmpty(pmss.getPermission())){
permissions.add(pmss.getPermission());
}
}
}
}
}
}else{
throw new AuthorizationException();
}
//给当前用户设置角色
info.addRoles(roles);
//给当前用户设置权限
info.addStringPermissions(permissions);
return info;
}
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken authcToken) throws AuthenticationException {
// TODO Auto-generated method stub
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
User user = userService.getByAccount(token.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(user.getUserName(), user
.getUserPass(), getName());
} else {
return null;
}
}
}
4、测试控制器
package com.lintian.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.mybatis.generator.ant.GeneratorAntTask;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import com.lintian.entity.User;
import com.lintian.service.UserService;
@Controller
public class TestAction {
@Autowired
private UserService userService;
@RequestMapping("/login.do")
public String login(){
System.out.println("system is login...");
return "test";
}
@RequestMapping("/login")
public String login2(String userName,HttpServletRequest request){
System.out.println("system is login2...");
userName=request.getParameter("userName");
User user=userService.getByAccount(userName);
System.out.println(user.getUserName()+"========"+user.getUserPass());
Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token=new UsernamePasswordToken(user.getUserName(),user.getUserPass());
token.setRememberMe(true);
subject.login(token);
token.clear();
request.setAttribute("user", user);
return "main";
}
@RequestMapping(value="/user/insert")
public String insert(String userName,String userPass,HttpServletRequest request,HttpServletResponse response){
System.out.println("do insert method....");
String url=request.getContextPath();
String path=request.getServletPath();
boolean isOk=checkPermission(path, request, response);
if(isOk){
return "user/list";
}else{
return "/permissionError";
}
}
@RequestMapping(value="/logout")
public String logout(HttpServletRequest request){
Subject subject=SecurityUtils.getSubject();
subject.logout();
return "login";
}
@RequestMapping(value="/checkPerm")
public boolean checkPermission(String url,HttpServletRequest request,HttpServletResponse response){
Subject subject=SecurityUtils.getSubject();
boolean isOk=subject.isPermitted(url);
System.out.println(url+" is have premission: "+isOk);
return isOk;
}
}
以上代码是经过测试可用的。
这篇关于shiro的使用入门的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!