Shiro整合Spring maven

1、jar引入

<dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-core</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-web</artifactId>  
            <version>1.2.4</version>  
        </dependency>  
 
        <dependency>  
            <groupId>org.apache.shiro</groupId>  
            <artifactId>shiro-spring</artifactId>  
            <version>1.2.4</version>
         </dependency>

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、spring-shiro.xml

<?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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans   
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd  
http://www.springframework.org/schema/context   
http://www.springframework.org/schema/context/spring-context-3.1.xsd  
http://www.springframework.org/schema/aop   
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd  
http://www.springframework.org/schema/tx   
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">


<bean id="securityManager"
        class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
        <property name="realm" ref="shiroDbRealm" />
    </bean>


     <!-- 項目自定义的Realm -->
    <bean id="shiroDbRealm" class="com.xxxxx.web.common.ShiroDbRealm" ></bean>
    
    <!-- Shiro Filter -->
    <bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
        <property name="securityManager" ref="securityManager" />
        <property name="successUrl" value="/success" /><!--成功页面-->
        <property name="loginUrl" value="/show/login" />  <!--登录页面-->
        <property name="unauthorizedUrl" value="/noPower" /><!--没有权限跳转页面-->
        <property name="filterChainDefinitions">
            <value>

<!--anno 不拦截   authc 需要身份验证    roles[admin]角色为admin时才可以访问-->
            /show/*= anon
            /front/** = authc
            /unit/** = roles[admin]
            </value>
        </property>
    </bean>


  <!-- 开启Shiro注解的Spring配置方式的beans。在lifecycleBeanPostProcessor之后运行 -->
    <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>
    
    <bean id="lifecycleBeanPostProcessor"  class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
 <!-- shiro为集成spring -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="org.apache.shiro.authz.UnauthorizedException">/login</prop>
            </props>
        </property>
    </bean>
</beans>

4、application.xml配置  引入spring-shiro.xml

<import resource="spring-shiro.xml"/>

5、自定义Realm

package com.xxxx.web.common;

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 com.gwkj.entity.User;
import com.gwkj.entity.UserRole;
import com.gwkj.service.IUserRoleService;
import com.gwkj.service.IUserSrevice;


public class ShiroDbRealm extends AuthorizingRealm{

@Autowired
private IUserSrevice userService;

@Autowired
private IUserRoleService roleService;



//授权方法
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
if (null == principals) {
throw new AuthenticationException("principals can not be null");
}
// 获取当前登录的用户名
String userName = (String) super.getAvailablePrincipal(principals);
User user=userService.selectByUserName(userName);
if(user.getRoleId()!=null){
// 给当前用户设置角色
Long roleId=user.getRoleId();
UserRole rol=roleService.selectByPrimaryKey(roleId);
String roleName=rol.getRoleName();
info.addRole(roleName);
}
// 给当前用户设置权限
// info.addStringPermissions(permissions);
return info;
}




//验证方法
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
 
String userName = (String) token.getPrincipal();
User user=userService.selectByUserName(userName);
if(user!=null){
SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(),this.getName());
return info;
}else{
return null;
}
 
}
}

6、登录Controller

@RequestMapping(value="/login",method=RequestMethod.POST)
public ModelAndView login(HttpSession session,ModelAndView view,User user){

Subject subject = SecurityUtils.getSubject();
UsernamePasswordToken token = new UsernamePasswordToken(user.getUserName(),user.getPassword());
//        token.setRememberMe(true);//记住我功能
       try {
        subject.login(token);
        view.addObject("result", "登陆成功");
            view.setViewName("/success");
       }catch(Exception e){
        e.printStackTrace();
        view.addObject("result", "用户名或密码错误!!");
        view.setViewName("/login");
       }
       
       return view;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值