apache shiro学习笔记--03(与spring整合)

1.web.xml部分的配置

在web.xml文件中添加shiro过滤器
  <!-- shiro过滤器定义 -->
    <filter>  
        <filter-name>shiroFilter</filter-name>  
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>  
        <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.spring配置文件的部分的配置

在spring的配置文件中添加

<!-- 自定义Realm -->
    <bean id="myRealm" class="com.xie.myRealm.MyRealm"/>  

    <!-- 安全管理器 -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">  
      <property name="realm" ref="myRealm"/>  
    </bean>  

    <!-- Shiro过滤器 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">  
        <!-- Shiro的核心安全接口,这个属性是必须的 -->  
        <property name="securityManager" ref="securityManager"/>
        <!-- 身份认证失败,则跳转到登录页面的配置 -->  
        <property name="loginUrl" value="/index.jsp"/>
        <!-- 权限认证失败,则跳转到指定页面 -->  
        <property name="unauthorizedUrl" value="/unAuth.jsp"/>  
        <!-- Shiro连接约束配置,即过滤链的定义 -->  
        <property name="filterChainDefinitions">  
            <value>  
                 /login=anon
                /admin*=authc
                /student=roles[teacher]
                /teacher=perms["user:create"]
            </value>  
        </property>
    </bean>  

    <!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->  
    <bean id="lifecycleBeanPostProcessor class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>  

    <!-- 开启Shiro注解 -->
    <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>  

3.myrelam的代码

public class MyRealm extends AuthorizingRealm{

    @Resource
    private UserService userService;

    /**
     * 验证当前登录的用户
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String userName=(String)token.getPrincipal();
        /*Subject 认证主体包含两个信息:
        Principals:身份,可以是用户名,邮件,手机号码等等,用来标识一个登录主体身份;
        Credentials:凭证,常见有密码,数字证书等等;*/
        User user = userService.getByUserName(userName);
        if (user != null) {
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(user.getName(), user.getPassword(), "");
            return authcInfo;
        } else {
            return null;
        }
    }

    /**
     * 为当限前登录的用户授予角色和权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName=(String)principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
        //授予角色(该用户有哪些角色,从数据库中获取)
        authorizationInfo.setRoles(userService.getRoles(userName));
        //授予权限(该用户有哪些权限,从数据库中获取)
        authorizationInfo.setStringPermissions(userService.getPermissions(userName));
        return authorizationInfo;
    }

}

4.controller的代码

/**
     * 用户登录
     * @param user
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(User user,HttpServletRequest request){
        Subject subject=SecurityUtils.getSubject();
        UsernamePasswordToken token=new UsernamePasswordToken(user.getName(), user.getPassword());
        try{
            subject.login(token);//开始认证,调用realm中的方法
            Session session=subject.getSession();
            session.setAttribute("info", "session数据:sessionId"+session.getId()+" sessionHost:"+session.getHost());
            return "redirect:/success.jsp";
        }catch(Exception e){
            e.printStackTrace();
            request.setAttribute("user", user);
            request.setAttribute("errorMsg", "用户名或者密码错误");
            return "index";
        }
    }

5.jsp页面代码

<body>
${info }
<br>
欢迎你!
<shiro:hasRole name="admin">
    欢迎有admin角色的用户!
    <br>
</shiro:hasRole>

<shiro:hasRole name="teacher">
    欢迎有teacher角色的用户!
    <br>
</shiro:hasRole>

<shiro:hasPermission name="student:create">
    欢迎有student:create权限的用户!
    <br>
</shiro:hasPermission>

<shiro:hasPermission name="student:update">
    欢迎有student:update权限的用户!
    <br>
</shiro:hasPermission>
</body>

6.数据库设计

t_role(角色表):id,name;
t_user(用户表):id,name,roleId;
t_perimission(权限表):id,name,roleId

7.源码地址

http://download.csdn.net/download/wu_0916/10011174

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值