SpringMvc+maven+shiro使用,说明及不走授权注解问题

说明:关于SpringMvc+maven参考之前的播客,这里直接配置

1.首先在pom.xml文件中配置依赖包

<!--shiro start-->
<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-core</artifactId>
  <version>1.3.2</version>
</dependency>

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-web</artifactId>
  <version>1.3.2</version>
</dependency>

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-spring</artifactId>
  <version>1.3.2</version>
</dependency>

<dependency>
  <groupId>org.apache.shiro</groupId>
  <artifactId>shiro-ehcache</artifactId>
  <version>1.3.2</version>
</dependency>
<!--shiro end-->

2.配置web.xml文件

  a.加载shiro.xml文件

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

   b.配置shiro拦截器

<!-- shiroFilter -->
<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>
3.配置shiro.xml文件

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <description>Spring 整合Shiro</description>
    <context:component-scan base-package="com.controller" />
    <!-- shiroFilter工厂 -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <!-- 构建securityManager环境 -->
        <property name="securityManager" ref="securityManager" />
        <!-- 用户没有认证通过返回的地址 -->
        <property name="loginUrl" value="/user/toLogin" />
        <!-- 拦截成功地址 -->
        <property name="successUrl" value="/" />
        <!-- 没有权限返回的地址 (拒绝访问路径)-->
        <property name="unauthorizedUrl" value="/403.html" />
        <property name="filterChainDefinitions">
            <value>
                / = anon
                /resources/**=anon
                /core/** = anon
                /user/toLogin=anon
                /user/login=anon
                /** = authc
            </value>
        </property>
    </bean>
    <!-- securityManager -->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <!--调用自定义realm -->
        <property name="realm" ref="myRealm" />
    </bean>
    <bean id="myRealm" class="com.core.MyRealm"></bean>
</beans>

4.MyRealm.java文件

package com.core;
import com.domain.back.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * Created by 李庆伟 on 2018/4/28.
 */
public class MyRealm extends AuthorizingRealm {
    /**
     * 授权
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.print("授权开始了");
        return null;
    }

    /**
     * 认证
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("shiro进来了");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        String userName = token.getUsername();
        String passWord = String.valueOf(token.getPassword());
        //下面可以写业务判断,此次模拟假数据
        User user = new User();
        user.setId(userName);
        user.setUserName(passWord);
        if("0".equals(userName)&&"admin".equals(passWord)){
            AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(userName, passWord, getName());
            setSession("user", user);
            return authcInfo;
        }
        return null;
    }

    //将登录用户放到session中
    private void setSession(Object key, Object value){
        Subject currentUser = SecurityUtils.getSubject();
        if(null != currentUser){
            Session session = currentUser.getSession();
            System.out.println("Session默认超时时间为[" + session.getTimeout() + "]毫秒");
            if(null != session){
                session.setAttribute(key, value);
            }
        }
    }
}

5.到了这里shiro的认证就配置好了,但是不走shiro的授权及扫描注解。解决方法需要在spring-mvc.xml中加入扫描shiro注解代理。

<!--shiro 授权 start  解决不走shiro授权方法及shiro注解问题-->
<!-- 开启aop,对类代理 -->
<aop:config proxy-target-class="true"></aop:config>
<!-- 开启shiro注解支持 -->
<import resource="shiro.xml"/>
<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    <property name="securityManager" ref="securityManager" />
</bean>
<!--shiro 授权 end-->

6.案例

  a.认证案例

/**
 * 登录
 * @return
 */
@RequestMapping("login")
public String login(HttpServletRequest request){
    String id = request.getParameter("id");
    String userName = request.getParameter("userName");
    UsernamePasswordToken token = new UsernamePasswordToken(id,userName);
    Subject currentUser = SecurityUtils.getSubject();
    try {
        currentUser.login(token);
        boolean flag = currentUser.isAuthenticated();
        if(flag){
            HttpSession session = request.getSession();
            User user = (User)session.getAttribute("user");
            if(user!=null){
                System.out.println("userId="+user.getId());
                System.out.println("userName="+user.getUserName());
            }
            return "sucess";
        }else {
            return "login";
        }
    }catch (UnknownAccountException e){
        System.out.println("登录异常");
        return "login";
    }
}

  b.授权案例

/**
 * 添加User
 * @param userForm
 * @return
 */
@RequiresPermissions(value = "user:addUser")
@RequestMapping("addUser")
@ResponseBody
public void addUser(UserForm userForm){
    userService.addUser(userForm);
}

业务的需要自己写,到此shiro的登录授权就完成了。








猜你喜欢

转载自blog.csdn.net/liqingwei168/article/details/80222438