shrio +springmvc web项目搭建
shrio +springmvc web项目搭建
asd121213 发表于3年前
shrio +springmvc web项目搭建
  • 发表于 3年前
  • 阅读 94
  • 收藏 1
  • 点赞 0
  • 评论 0

腾讯云 技术升级10大核心产品年终让利>>>   

摘要: java web项目集成springmvc 和 shrio

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 ;

    }


共有 人打赏支持
粉丝 0
博文 9
码字总数 2245
×
asd121213
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: