权限管理——shiro

1.shiro整合spring

  a.导入依赖

<properties>    
    <shiro.version>1.2.4</shiro.version>
</properties>



<!-- shiro -->
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-core</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-ehcache</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-web</artifactId>
      <version>${shiro.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.shiro</groupId>
      <artifactId>shiro-spring</artifactId>
      <version>${shiro.version}</version>
    </dependency>

  b.创建spring-shiro.xml

    注:filterChainDefinitions是过滤器

      anon为匿名访问

      authc为登陆验证了才能访问

      roles[admin]为角色为“admin”字符串才能访问

      等等。。。

<?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:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.3.xsd">

    <!-- 使用spring组件扫描@service  -->
    <context:component-scan base-package="com.wode.service"/>
    <!-- 自定义域realm -->
    <bean id="custom_Realm" class="com.wode.realm.CustomRealm">
        <property name="credentialsMatcher" >  
            <bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">  
                    <!-- md5加密密码  -->
                <property name="hashAlgorithmName" value="MD5"></property> 
                    <!-- md5加密次数  -->
                <property name="hashIterations" value="1"></property>
            </bean>  
        </property>
    </bean>
    <!-- 安全管理器  ref对象-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="custom_Realm"/>
    </bean>
    <!-- shiro filter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 安全管理器必须的 -->
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份认证失败   认证提交的地址 -->
        <property name="loginUrl" value="/"/>
        <!-- 权限认证失败    没有权限认证提交的地址 -->
        <property name="unauthorizedUrl" value="/unauthorized"/>
        <!-- Shiro连接约束配置,即过滤链的定义 -->
        <property name="filterChainDefinitions">
            <value>
                <!-- 对静态资源设置匿名访问 -->
                / = anon
                /login = anon
                /go2RegisterPage = anon
                /register = anon
                /static/** = anon
                <!-- 必须要管理员角色才能访问 -->
                /admin/** = roles[admin]
                <!-- 所有url都必须认证通过才可以访问 -->
                /** = authc
            </value>
        </property>
    </bean>
    <!-- Shiro生命周期处理器 -->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"></bean>
    <bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
        <property name="securityManager" ref="securityManager"/>
    </bean>

</beans>    

  c.创建自定义域realm类

public class CustomRealm extends AuthorizingRealm {
    
    @Resource
    private UserService userService;
    
    /**
     * 用户授权认证
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String userId = principalCollection.getPrimaryPrincipal().toString();
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setRoles(userService.queryRolesByName(userId));    //设置角色
//        simpleAuthorizationInfo.addStringPermissions(permissions);    //设置权限
        return simpleAuthorizationInfo;
    }

    /**
     * 用户登陆认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String userId = authenticationToken.getPrincipal().toString();
        User user = null;
        try {
            user = userService.queryUserByName(userId);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user!=null) {
            //第一二个参数是账号密码,第三参数是加的盐值,第四个是Realm的名称
            AuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user.getUserId(), user.getUserPwd(), ByteSource.Util.bytes(user.getUserId()), this.getName());
            return authenticationInfo;
        }
        return null;
    }

}

  d.用户的登陆Controller类

@Controller
public class UserController {
    @Resource
    private UserService userService;
    
    //登陆
    @RequestMapping("login")
    public @ResponseBody String login(User user){
        String userId = user.getUserId();
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(userId, user.getUserPwd());
        try {
            subject.login(usernamePasswordToken);

//            Session session = subject.getSession();
//            session.setAttribute("userId", userId);
//            session.setAttribute("roleName", roleName);
//            session.setAttribute("userPhoto", userPhoto);

            return "success";
        } catch (Exception e) {
            return "fail";
        }
    }
}

  c.用户登出

//登出
    @RequestMapping("logout")
    public String logout(){
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "redirect:/";
    }

  d.加密工具类(以shiro的加密方式加密,可用于注册)

public class Md5AndSaltUtil {

    public static String encrypt(String userId, String userPwd){
        //第一个参数是加密方式,第二个是加密的字符串,第三个是盐值,第四个是md5的加密次数
        return new SimpleHash("MD5", userPwd, ByteSource.Util.bytes(userId), 1).toString();
    }
}

 

posted @ 2018-01-30 14:30  晨M风  阅读(199)  评论(0编辑  收藏  举报