Shiro的基本使用

本篇主要介绍shiro的简单基本使用,我使用的是maven管理项目

1.在pom.xml中添加依赖

<dependency>
    <groupId>org.apache.shiro</groupId>
    <artifactId>shiro-core</artifactId>
    <version>1.4.0</version>
</dependency>

2.在web.xml中配置

  <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

public class ShiroRealm extends AuthorizingRealm {

	/*
	 * 登录信息和用户验证信息验证(non-Javadoc)
	 * @see org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org.apache.shiro.authc.AuthenticationToken)
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		 String username = (String)token.getPrincipal();  				//得到用户名 
	     String password = new String((char[])token.getCredentials()); 	//得到密码
	     if(null != username && null != password){
	    	 return new SimpleAuthenticationInfo(username, password, getName());
	     }else{
	    	 return null;
	     }
	}
	
	/*
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用,负责在应用程序中决定用户的访问控制的方法(non-Javadoc)
	 * @see org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache.shiro.subject.PrincipalCollection)
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection pc) {
		System.out.println("========2");
		return null;
	}

}

4.创建ApplicationContext-shiro.xml并在web.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">
	

		<!-- 項目自定义的Realm -->
	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="ShiroRealm" />
	</bean>
	    <bean id="ShiroRealm" class="com.wdkj.gerakan.interceptor.shiro.ShiroRealm" ></bean>

		<!-- Shiro Filter -->
		<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
			<property name="securityManager" ref="securityManager" />
			
			<property name="loginUrl" value="/" />
			
			<property name="successUrl" value="/main/index" />
			
			<property name="unauthorizedUrl" value="/login_toLogin" />
			
			<property name="filterChainDefinitions">
				<value>
				/testlogin/shiro                 = anon
	           	        /**			         = authc 
				</value>
			</property>
		</bean>
   
</beans>

在web.xml中配置

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>
      classpath:spring/ApplicationContext-main.xml,
      classpath:spring/ApplicationContext-dataSource.xml,
      classpath:spring/ApplicationContext-shiro.xml,
      <!--classpath:spring/ApplicationContext-quartz.xml,-->
      <!-- 	classpath:spring/ehcache.xml, -->
      classpath:spring/ApplicationContext-redis.xml
    </param-value>
  </context-param>

5.LoginController.java

@Controller
public class LoginController extends BaseController {



    /**
     * 访问登录页
     *
     * @return
     * @throws Exception
     */

    @RequestMapping(value = "testlogin/shiro", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String testShiro() {
        PageData pd = new PageData();
        pd = this.getPageData();
        if ("wss".equals(pd.get("username")) &&"123".equals( pd.get("password"))) {
            UsernamePasswordToken token = new UsernamePasswordToken(pd.get("username").toString(), pd.get("password").toString());
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);
            return JSONUtil.toJsonString(new JsonResult(1, "登录成功", null));
        } else {
            return JSONUtil.toJsonString(new JsonResult(-1, "登录失败", null));
        }
    }

    @RequestMapping(value = "testshiro/shirologin", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String loginShiro() {
        PageData pd = new PageData();
        pd = this.getPageData();
        if ("wss".equals(pd.get("user"))) {
            return JSONUtil.toJsonString(new JsonResult(1, "登录成功", null));
        } else {
            return JSONUtil.toJsonString(new JsonResult(-1, "登录失败", null));
        }
    }

    @RequestMapping(value = "testshirologout/shirologout", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String loginoutShiro() {
        SecurityUtils.getSubject().logout();
        return JSONUtil.toJsonString(new JsonResult(1, "登录成功", null));
    }  }

效果:

在没有调用testlogin/shiro正确登录的时候


调用testshiro/shirologin会被拦截,跳转到登录界面


正确调用登录


没有拦截


现在调用testshirologout/shirologout退出接口


再调用testshiro/shirologin会被拦截,跳转到登录界面,基本使用就完成了 ,下一篇会介绍手机端的登录Token验证










 



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值