SSM集成Shiro进行权限控制:认证,授权!

1.spring-shiro.xml

spring集成shiro的相关配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--配置shiro的核心securityManager-->
    <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="cacheManager" ref="cacheManager"/>
        <property name="realm" ref="myShiroRealm"/>
    </bean>

    <!--项目自定义的Realm,从数据库获取用户安全数据-->
    <bean id="myShiroRealm" class="com.max.config.MyRealm"/>

    <!--&lt;!&ndash;配置ehcache缓存&ndash;&gt;-->
    <!--<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">-->
        <!--<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>-->
    <!--</bean>-->
    <!-- 用户授权信息Cache -->
    <bean id="cacheManager" class="org.apache.shiro.cache.MemoryConstrainedCacheManager" />

    <!--配置shiro中bean生命周期管理器-->
    <bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
    <!--AOP式方法权限检查-->
    <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>

    <!--shiro过滤器配置,与web.xml中的过滤器同名-->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">

        <property name="securityManager" ref="securityManager"/>
        <!--登录页面-->
        <property name="loginUrl" value="login.html"/>
        <!--登录成功后跳转的页面-->
        <property name="successUrl" value="index"/>
        <!--访问未授权页面跳转的页面-->
        <property name="unauthorizedUrl" value="unauthor.html"/>
        <property name="filterChainDefinitions">
            <!--静态资源需要设置为anon,否则找不到-->
            <value>
                /statics/**=anon
                /login.html=anon
                /welcom.html=authc
            </value>
        </property>

    </bean>
</beans>

2.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>/*</url-pattern>
    </filter-mapping>

3.自定义Realm

 Realm 获取安全数据(如用户、角色、权限),并进行认证,授权

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {

        String username= (String) SecurityUtils.getSubject().getPrincipal();
        Set<String> roles=new HashSet<String>();
        Set<String> menus=new HashSet<String>();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //通过用户id查询用户角色
        //通过用户id查询用户权限

        // 角色加入AuthorizationInfo认证对象
        info.setRoles(roles);
        // 权限加入AuthorizationInfo认证对象
        info.setStringPermissions(menus);
        return info;
    }

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //将token转换为usernamepasswordToken
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //获取token中的登录账户
        String username = token.getUsername();
        //查询数据库,是否存在指定的用户名和密码的用户
        User user = userService.findByUsername(username);
        if (user==null){
            throw new UnknownAccountException("账户"+username+"不存在");
        }
        //如果查询到了,封装查询结果
        String principal = user.getUsername();
        String credentials  = user.getPassword();
        String realmName = this.getName();
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(principal, credentials, realmName);
        //返回给调用login(token)方法
        return info;
    }
}

4.controller

@RequestMapping("/login")
    public String login(User user){

        //创建subject实例对象
        Subject subject = SecurityUtils.getSubject();
        if (subject.isAuthenticated()==false){
            UsernamePasswordToken token=new UsernamePasswordToken(user.getUsername(),user.getPassword());
            try{
                subject.login(token);
            }catch (AuthenticationException e){
                e.getMessage();
                e.printStackTrace();
                System.out.println("登录失败");
                return "login";
            }
        }
        return "index";

    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值