Shiro框架的配置和简单使用

1.配置shiro框架

1.1 导入shiro需要依赖的jar包

我是使用maven项目直接加载的。
在pom.xml文件中加入如下依赖:

	<dependency>
            <groupId>org.apache.shiro</groupId>
            <artifactId>shiro-core</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-web</artifactId>
             <version>1.3.2</version>
        </dependency>
1.2配置shiro的xml文件(applicationContext-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"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">


<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
    <property name="securityManager" ref="securityManager"/>
    <!-- override these for application-specific URLs if you like:
    <property name="loginUrl" value="/login.jsp"/>
    <property name="successUrl" value="/home.jsp"/>
    <property name="unauthorizedUrl" value="/unauthorized.jsp"/> -->
    <!-- The 'filters' property is not necessary since any declared javax.servlet.Filter bean  -->
    <!-- defined will be automatically acquired and available via its beanName in chain        -->
    <!-- definitions, but you can perform instance overrides or name aliases here if you like: -->
    <!-- <property name="filters">
        <util:map>
            <entry key="anAlias" value-ref="someFilter"/>
        </util:map>
    </property> -->
    <property name="filterChainDefinitions">
        <value>
        //anon是可以匿名访问
        //authc是必须经过验证以后才能访问
            # some example chain definitions:
            /admin/** = authc, roles[admin]
            /docs/** = authc, perms[document:read]
            
             /**/*.do=anon
            /** = authc
            # more URL-to-FilterChain definitions here
        </value>
    </property>
</bean>




<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
    <!-- Single realm app.  If you have multiple realms, use the 'realms' property instead. -->
    <property name="realm" ref="myRealm"/>
    <!-- By default the servlet container sessions will be used.  Uncomment this line
         to use shiro's native sessions (see the JavaDoc for more): -->
    <!-- <property name="sessionMode" value="native"/> -->
</bean>
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>



<bean id="myRealm" class="com.gy.shiro.MyRealm">
   
</bean>
</beans>

在最后需要改一下,还有中间的配置。

1.3需要在web.xml中加载shiro的配置文件

<context-param>  
    <param-name>contextConfigLocation</param-name>  
    <param-value>classpath:applicationContext.xml,
    classpath:applicationContext-transaction.xml,
    classpath:applicationContext-shiro.xml,
    classpath:applicationContext-mybatis.xml,
    </param-value>  
</context-param>  
<listener>  
     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
 </listener>  
1.4配置好xml后需要在添加class文件
package com.gy.shiro;

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.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.gy.service.LoginService;

public class MyRealm extends AuthorizingRealm {

	@Autowired
	private LoginService service;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

		UsernamePasswordToken token2 = (UsernamePasswordToken) token;
		boolean flag = service.findUserByUserNameAndPassword(token2.getUsername(), new String(token2.getPassword()));
		if (flag) {
			AuthenticationInfo info = new SimpleAuthenticationInfo(token2.getUsername(), token2.getPassword(),
					getName());
			return info;
		} else {
			throw new AuthenticationException();
		}
	}

}

2 shiro的简单使用

2.1 使用ssm框架操作shiro框架

这里以登录为例:

@RequestMapping("/login.do")
	public String login(String userName,String password) {
		Subject currentUser = SecurityUtils.getSubject();
        //登录逻辑
        if (!currentUser.isAuthenticated()) {
        	//是否被登录过
        	//UsernamePasswordToken用于存放当前的账号和密码
            UsernamePasswordToken token = new UsernamePasswordToken(userName,password );
            token.setRememberMe(true);
            try {
            	//执行登录逻辑
                currentUser.login(token);
            } 
            // ... catch more exceptions here (maybe custom ones specific to your application?
            catch (AuthenticationException ae) {
                //unexpected condition?  error?
            	return "fail";
            }
            return "success";
        }
        return "fail";
	}
当调用 currentUser.login()方法的时候,程序最终会去调用MyRealm中的protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException方法。所以操作数据的方法需要写在这个方法里面
2.2 其他的都是正常的SSM框架的使用,这里就不一一赘述了。

值得一说的是:在shiro的配置文件中,我们需要对访问的路径进行验证或者设置可以匿名登录,达到对shiro框架的一个简单使用。

SpringMVC整合ShiroShiro是一个强大易用的Java安全框架,提供了认证、授权、加密和会话管理等功能。 配置applicationContext-shiro.xml 1. 配置authorizingRealm <bean id="authorizingRealm" class="com.mjm.core.interceptor.ShiroRealm"> <property name="authorizationCacheName" value="authorization" /> </bean> 2.Shiro Filter 设置拦截的内容和登录页面和成功、失败页面 3.配置securityManager <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager"> <!-- 单realm应用。如果有多个realm,使用‘realms’属性代替 --> <property name="realm" ref="authorizingRealm" /> <property name="cacheManager" ref="shiroCacheManager" /> </bean> 服务器 web.xml中配置 <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> maven 的pom.xml 配置 <!-- shiro简单配置 --> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-core</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-web</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-ehcache</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>org.apache.shiro</groupId> <artifactId>shiro-spring</artifactId> <version>1.2.0</version> </dependency> <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.5.3</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-jdk14</artifactId> <version>1.6.4</version> </dependency> <!-- end-->
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值