Shiro的permission管理,用户的认证和授权

Shiro的permission管理,用户的认证和授权demo步骤:
1.web.xml中配置:

<display-name>shirodemo</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml,classpath:spring-shiro.xml</param-value>
    </context-param>

    <!-- apache shiro权限 在web.xml中添加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>*.do</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
    </filter-mapping>

2.spring-shiro.xml

<description>shiro权限管理配置</description>
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <!-- shiro通过一个filter控制权限-->
    <property name="securityManager"   ref="securityManager" />
    <property name="loginUrl" value="/login.jsp" /> 
        <!-- 登陆页 -->
     <property name="successUrl" value="/login.jsp" /> 
         <!-- 登陆成功之后跳转的页面 -->
    <property name="unauthorizedUrl" 
        value="/error/noperms.jsp" />  
        <!-- 用户在请求无权限的资源时,跳转到这个url -->
    <property name="filterChainDefinitions"> 
    <!-- 配置访问url资源需要用户拥有什么权限 配置的优先级由上至下-->
        <value>
            /login.jsp* = anon
            /login.do* = anon
            /index.jsp*= anon
            /error/noperms.jsp*= anon
            /*.jsp* = authc
            /*.do* = authc
        </value>
    </property>
    </bean>
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--设置自定义realm -->
        <property name="realm" ref="monitorRealm" />
    </bean>

    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />

    <!--自定义Realm 继承自AuthorizingRealm -->
    <bean id="monitorRealm" class="com.shiro.service.MonitorRealm"></bean>
    <!-- securityManager -->
    <bean
        class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="org.apache.shiro.SecurityUtils.setSecurityManager" />
        <property name="arguments" ref="securityManager" />
    </bean>

    <!-- Enable Shiro Annotations for Spring-configured beans. Only run after -->
    <!-- the lifecycleBeanProcessor has run: -->
    <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.spring-mvc.xml增加自动扫描

<!--# 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
 <context:component-scan 
 base-package="com.shiro.controller" />

4.applicationContext.xml增加自动扫描配置

 <!--自动扫描dao和service包(自动注入)-->
    <context:component-scan base-package="com.shiro.dao,com.shiro.service" />

5.LoginController.java

  package com.shiro.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.shiro.Utils.EncryptUtils;
import com.shiro.model.User;

@Controller
@RequestMapping(value = "login")
public class LoginController {
    /*
     * @Autowired User user;
     * 用户登录
     */
    @RequestMapping(params = "main")
    public ModelAndView login(User user,HttpSession session, HttpServletRequest request) {

        ModelAndView modelView = new ModelAndView();
        //认证:验证用户身份的过程
        //收集了实体/凭据信息之后,
        //我们可以通过SecurityUtils工具类,获取当前的用户
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsercode(), EncryptUtils.encryptMD5(user.getPassword()));
        //“记住我”的功能。
        token.setRememberMe(true);
        try {
            //然后通过调用login方法提交认证
            currentUser.login(token);
        } catch (AuthenticationException e) {
            modelView.addObject("message", "login errors");
            modelView.setViewName("/login");
            e.printStackTrace();

        }
        //使用subject.isAuthenticated()判断用户是否已验证返回true/false.
        if(currentUser.isAuthenticated()){
            user.setUserName("张三");
            session.setAttribute("userinfo", user);
            modelView.setViewName("/main");
        }else{
            modelView.addObject("message", "登陆名或密码错误!");
            modelView.setViewName("/login");
        }
        return modelView;
    }

    /**
     * 退出登录
     */
    @RequestMapping(params = "logout")
    public String logout() {
        Subject currentUser = SecurityUtils.getSubject();
        try {
            currentUser.logout();
        } catch (AuthenticationException e) {
            e.printStackTrace();
        }
        return "/login";
    }

    @RequestMapping(params = "myjsp")
    public ModelAndView login2() {

        System.out.println("sss");
        ModelAndView modelView = new ModelAndView();
        modelView.addObject("message", "登录成功!");
        modelView.setViewName("/my");
        return modelView;
    }

    @RequestMapping(params = "test")
    public ModelAndView login3() {
        System.out.println("sss");
        ModelAndView modelView = new ModelAndView();
        modelView.addObject("message", "登录成功!");
        modelView.setViewName("/test");
        return modelView;
    }
}

6.UserController.java

package com.shiro.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping(value="user")
public class UserController {
    /**
     * 跳转到myjsp页面
     */
    @RequestMapping(params = "myjsp")
    public String home() {
        Subject currentUser = SecurityUtils.getSubject();
        //对比是否有权限,permissions中有此"user.do?myjsp" 
        //则有权,无 则无权
        if(currentUser.isPermitted("user.do?myjsp")){
            return "my";
        }else{
            return "error/noperms";
        }
    }
    @RequestMapping(params = "notmyjsp")
    public String nopermission() {
        Subject currentUser = SecurityUtils.getSubject();
        if(currentUser.isPermitted("user.do?notmyjsp")){
            return "notmyjsp";
        }else{
            return "error/noperms";
        }
    }
}

7.service层下的MonitorRealm.java

package com.shiro.service;

import java.util.HashSet;
import java.util.Set;
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.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.stereotype.Service;

import com.shiro.Utils.EncryptUtils;
import com.shiro.model.User;

@Service("monitorRealm")
public class MonitorRealm extends AuthorizingRealm {
    /*
     * @Autowired UserService userService;
     * @Autowired RoleService roleService;
     * @Autowired LoginLogService loginLogService;
     */

    public MonitorRealm() {
        super();
    }

     /**
     * 授权信息
     * 用户权限源(shiro调用此方法获取用户权限,
     * 至于从何处获取权限项,由我们定义。)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(
            PrincipalCollection principals) {
        /* 这里编写授权代码 */
        Set<String> roleNames = new HashSet<String>();
        Set<String> permissions = new HashSet<String>();
        roleNames.add("111111");
        permissions.add("user.do?myjsp");
        permissions.add("login.do?main");
        permissions.add("login.do?logout");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roleNames);
        info.setStringPermissions(permissions);
      //将用户权限返回给shiro
        return info;

    }

    /**
     * 认证信息
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(
            AuthenticationToken authcToken) throws AuthenticationException {
        /* 这里编写认证代码 */
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
//        User user = securityApplication.findby(upToken.getUsername());
        User user = new User();
        user.setUsercode(token.getUsername());

        user.setUserName("admin");
        user.setPassword(EncryptUtils.encryptMD5("admin"));
//        if (user != null) {
        //比对成功则返回info,比对失败则抛出对应信息的异常AuthenticationException
        return new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(), getName());
    }

    public void clearCachedAuthorizationInfo(String principal) {
        SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
        clearCachedAuthorizationInfo(principals);
    }

}

8.MD5加密EncryptUtils.java

 package com.shiro.Utils;

import org.apache.shiro.crypto.hash.Md5Hash;

public class EncryptUtils {
    public static final String encryptMD5(String source) {
        if (source == null) {
            source = "";
        }
        Md5Hash md5 = new Md5Hash(source);
        return md5.toString();
    }
}

9.model实体类 User.java

public class User {
    private String usercode;
    private String userName;
    private String password;
}

10.eclipse结构图
这里写图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值