shrio +springmvc web项目搭建

1. pom.xml jar 引入

             < dependency>

               < groupId> org.apache.shiro </groupId >

               < artifactId> shiro-all </artifactId >

               < version> 1.2.2</ version >

           </ dependency>

2. web.xml配置filter

      <!-- Shiro配置-->

  <filter >   

    <filter-name >shiroFilter </ filter-name>

    < filter-class> org.springframework.web.filter.DelegatingFilterProxy </filter-class >

  </filter >

  <filter-mapping >   

    <filter-name >shiroFilter </ filter-name>    

    <url-pattern >/* </ url-pattern>    

  </filter-mapping >

3. 编写验证类

     package com.my.shrio.application;


import java.util.HashSet;
import java.util.List;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.my.shrio.domain.User;

@Service
public class MyShiroDbReaml extends AuthorizingRealm {

    @Autowired
    private UserAL UserAl;

    /*
     * 权限认证
     * 
     * @see
     * org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
     * .shiro.subject.PrincipalCollection)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
        // 用户名
        String loginName = (String) arg0.fromRealm(getName()).iterator().next();
        // User user = userService.getUserByLoginName(loginName);
        /* 这里编写授权代码 */
        Set<String> roleNames = new HashSet<String>();
        Set<String> permissions = new HashSet<String>();
        if ("admin".equals(loginName)) {
            roleNames.add("admin");
            permissions.add("manager:admin");
        } else {
            roleNames.add("user");
            permissions.add("manager:user");
        }

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roleNames);
        info.setStringPermissions(permissions);
        return info;
    }

    @Override
    // 获取认证信息
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        // 根据用户名去表中查询用户信息      
         User user = UserAl.selectByUserName(token.getUsername());
        // 认证用户身份
        if (user != null) {
            return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), getName());
        } else {
            throw new AuthenticationException();
        }
    }

}


4.配置spring集成信息

<? 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:aop ="http://www.springframework.org/schema/aop"

       xmlns:tx ="http://www.springframework.org/schema/tx"

       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/tx http://www.springframework.org/schema/tx/spring-tx.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" >

 

      <bean id= "myShiro" class ="com.my.shrio.application.MyShiroDbReaml" >

      </bean >

 

    <!-- 配置权限管理器 -->

    <bean id= "securityManager" class ="org.apache.shiro.web.mgt.DefaultWebSecurityManager" >

        <!-- ref 对应我们写的realm  MyShiro -->

        < property name= "realm" ref = "myShiro"/>

        <!-- 使用下面配置的缓存管理器 -->

        < property name= "cacheManager" ref ="cacheManager" />

    </bean >

    

    <!-- 配置shiro的过滤器工厂类,id- shiroFilter要和我们在web.xml中配置的过滤器一致 -->

    <bean id= "shiroFilter" class ="org.apache.shiro.spring.web.ShiroFilterFactoryBean" >

        <!-- 调用我们配置的权限管理器 -->

        < property name= "securityManager" ref ="securityManager" />

        <!-- 配置我们的登录请求地址 -->

        < property name= "loginUrl" value = "/app/tologin"/>

        <!-- 配置我们在登录页登录成功后的跳转地址,如果你访问的是非/login地址,则跳到您访问的地址

        <property name="successUrl" value="/index.jsp"/> -->

        <!-- 如果您请求的资源不再您的权限范围,则跳转到/403请求地址 -->

        < property name= "unauthorizedUrl" value ="/app/noperms" />

        <!-- 权限配置 -->

        < property name= "filterChainDefinitions" >

            < value>

                <!-- anon表示此地址不需要任何权限即可访问-->

                /*/login=anon

                / ws/**=anon

                /**/*. css=anon

                /**/*. js=anon

                /**/*. gif=anon

                /**/*. jpg=anon

                /**/*. png=anon

                <!-- roles[admin ]表示访问此连接需要用户的角色为 admin-->

                / app/page/*=roles[admin ]

                <!-- perms [manager:admin]表示访问此连接需要权限为manager:admin的用户  -->

                / app/page/*=perms [manager:admin]

                <!--所有的请求(除去配置的静态资源请求或请求地址为anon的请求)都要通过登录验证,如果未登录则跳到/login-->

                /** = authc

            </ value>

        </ property>

    </bean >

     

    <bean id= "cacheManager" class ="org.apache.shiro.cache.MemoryConstrainedCacheManager" />

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

     

</ beans>


5.controller中进行验证

     @RequestMapping(value = "/login" , method = RequestMethod.POST )

    public ModelAndView login(HttpServletRequest request) {


        // System.out.println(userService.getUserById(username).getName());


        String result = "login" ;

        // 此处默认有值

        String username = request .getParameter("username" );

        // MD5加密

        // String password =

        // CipherUtil.generatePassword(request.getParameter("password"));

        String password = request .getParameter("password" );

        UsernamePasswordToken token = new UsernamePasswordToken(username password );


        Subject currentUser = SecurityUtils.getSubject();

        try {

            // System.out.println("----------------------------");

            if (!currentUser .isAuthenticated()) {

                token.setRememberMe( true );

                currentUser .login(token );

            }

            // System.out.println("result: " + result);

            result = "index" ;

        } catch (Exception e ) {

            result = "login" ;

        }

        ModelAndView mav = new ModelAndView(result );

        mav.addObject( "account" username );

        return mav ;

    }


转载于:https://my.oschina.net/u/1412205/blog/406388

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值