Shiro使用

Apache Shiro一个开源的安全框架,本文将会对Shiro的相关知识做一个总结,先来看一个Shiro的结构图:
在这里插入图片描述
接下来介绍下Shiro框架的使用,主要介绍两种方式:

  1. 配置文件
  2. 使用配置类
1、配置文件方式
1.1配置文件元素介绍

Shiro的配置文件中包含以下元素:
[main]
配置应用程序的SecurityManager实例及其任何依赖项(如:Realms)的地方,举例如下:

[main]
sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher

myRealm = com.company.security.shiro.DatabaseRealm # 定义了一个Realm的对象实例
myRealm.connectionTimeout = 30000
myRealm.username = jsmith
myRealm.password = secret
myRealm.credentialsMatcher = $sha256Matcher # 使用$符号来进行值的引用

securityManager.sessionManager.globalSessionTimeout = 1800000

[users]
用于去指定一些静态的用户账户,这些账户的指定需要遵循如下规则:

username = password, roleName1, roleName2, ..., roleNameN

等号右边的第一个值为账号的密码,后边的为账号所分配的角色,之间用逗号(",")隔开;如下为一些例子:

[users]
admin = secret
lonestarr = vespa, goodguy, schwartz
darkhelmet = ludicrousspeed, badguy, schwartz

注意:
在指定用户的账户密码时,可以使用加密后的值来展示,但是一旦这里使用了hash后的值,就必须在[main]部分中指定自己在进行加密时所使用的算法,如在main中所指定的参数:

myRealm.credentialsMatcher = $sha256Matcher # 设定加密算法

来设置自己所用的算法;除此以外你还可以在加密的时候设置一些其他的策略,但是也是需要进行在[main]中进行配置,如:

sha256Matcher.storedCredentialsHexEncoded = false  # 用户的密码字符串是Base64编码的,而不是默认的十六进制编码

[roles]
用来将[users]部分和权限进行关联,当角色数量较少时我们可以直接使用这个静态文件来配置;创建的格式为:

rolename = permissionDefinition1, permissionDefinition2, ..., permissionDefinitionN

举一个例子来展示一下:

[roles]
# 'admin' role has all permissions, indicated by the wildcard '*'
admin = *
# The 'schwartz' role can do anything (*) with any lightsaber:
schwartz = lightsaber:*
# The 'goodguy' role is allowed to 'drive' (action) the winnebago (type) with
# license plate 'eagle5' (instance specific id)
goodguy = winnebago:drive:eagle5

[urls]
为您的应用程序中的任何匹配URL路径定义特别过滤器链,url部分的格式如下:

URL_Ant_Path_Expression = Path_Specific_Filter_Chain

举例如下:

[urls]
/index.html = anon
/user/create = anon
/user/** = authc
#/user/login/**=anon
/admin/** = authc, roles[administrator]
/rest/** = authc, rest
/remoting/rpc/** = authc, perms["remote:invoke"]

注意:

  • 在上述的urls配置中,有一第一个匹配到的规则生效的原则;
    例如:上述中的/user/login/**=anon规则永远都不会被匹配到,因为在/user/**=authc在其前边已经生效了。
  • 等号(=)右边的令牌是要为匹配该路径的请求执行的逗号分隔的筛选器列表(authc为过滤器名称),可以使用默认的过滤器,也可以自定义过滤器;自定义的过滤器必须符合以下格式:
filter1[optional_config1], filter2[optional_config2], ..., filterN[optional_configN] # filterN为在[main]部分定义的过滤器的名字,[optional_configN]为一个可选的参数,由于这是一个过滤器链,所以先后顺序很重要
    
#举例如下,自定义过滤器的使用
[main]
myFilter = com.company.web.some.FilterImplementation
myFilter.property1 = value1
...
    
[urls]
...
/some/path/** = myFilter 
  • 也可以使用一些默认的过滤器,如:
    在这里插入图片描述
  • 如果需要禁用某一个过滤器可以在[main]部分中借助于过滤器的enabled属性来设置,如下:
[main]
# configure Shiro's default 'ssl' filter to be disabled while testing:
ssl.enabled = false
...

[urls]
/some/path = ssl, authc
/another/path = ssl, roles[admin]
....
1.2、配置文件的使用

shiro.ini配置文件如下:

[users]
root = secret, admin
guest = guest, guest
presidentskroob = 12345, president
darkhelmet = ludicrousspeed, darklord, schwartz
lonestarr = vespa, goodguy, schwartz

[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5

接下来介绍下配置文件在代码中的使用:

public class App {
	private static final Logger log = LoggerFactory.getLogger(App.class);

	public static void main(String[] args) {
		log.info("My First Apache Shiro Application");
		Factory<org.apache.shiro.mgt.SecurityManager> securityManagerFactory = new IniSecurityManagerFactory(
				"classpath:shiro.ini");
		// 获取SecurityManager实例
		SecurityManager securityManager = securityManagerFactory.getInstance();
		SecurityUtils.setSecurityManager(securityManager);

		// 获取当前的用户
		Subject subject = SecurityUtils.getSubject();
		Subject currentUser = SecurityUtils.getSubject();

		// Do some stuff with a Session (no need for a web or EJB container!!!)
		Session session = currentUser.getSession();
		session.setAttribute("someKey", "aValue");
		String value = (String) session.getAttribute("someKey");
		if (value.equals("aValue")) {
			log.info("Retrieved the correct value! [" + value + "]");
		}
		if (!subject.isAuthenticated()) {
			UsernamePasswordToken token = new UsernamePasswordToken("lonestarr", "vespa");
			// 设置记住我
			token.setRememberMe(true);
			try {
				currentUser.login(token);
			} catch (UnknownAccountException uae) {
				log.info("There is no user with username of " + token.getPrincipal());
			} catch (IncorrectCredentialsException ice) {
				log.info("Password for account " + token.getPrincipal() + " was incorrect!");
			} catch (LockedAccountException lae) {
				log.info("The account for username " + token.getPrincipal() + " is locked.  "
						+ "Please contact your administrator to unlock it.");
			} catch (AuthenticationException ae) {
			}
		}
		log.info("User [" + currentUser.getPrincipal() + "] logged in successfully.");
		if (currentUser.hasRole("schwartz")) {
			log.info("May the Schwartz be with you!");
		} else {
			log.info("Hello, mere mortal.");
		}
		if (currentUser.isPermitted("lightsaber:weild")) {
            log.info("You may use a lightsaber ring.  Use it wisely.");
        } else {
            log.info("Sorry, lightsaber rings are for schwartz masters only.");
        }
		if (currentUser.isPermitted("winnebago:drive:eagle5")) {
            log.info("You are permitted to 'drive' the winnebago with license plate (id) 'eagle5'.  " +
                    "Here are the keys - have fun!");
        } else {
            log.info("Sorry, you aren't allowed to drive the 'eagle5' winnebago!");
        }
		//all done - log out!
        currentUser.logout();
	}
}
2、配置类的方式

先来构建一个Shiro的配置类,如下所示:

package com.rhine.blog.config;

import java.io.Serializable;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.mgt.RememberMeManager;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.SessionDAO;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.CookieRememberMeManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.servlet.SimpleCookie;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.rhine.blog.realm.UserRealm;

@Configuration
public class ShiroConfig {
	
	/**设置hash加密的方式**/
	@Bean("hashedCredentialsMatcher")
	public HashedCredentialsMatcher hashedCredentialsMatcher() {
		HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
		// 指定加密方式为MD5
		credentialsMatcher.setHashAlgorithmName("MD5");
		// 加密次数
		credentialsMatcher.setHashIterations(1024);
		credentialsMatcher.setStoredCredentialsHexEncoded(true);
		return credentialsMatcher;
	}

	@Bean("userRealm")
	public UserRealm userRealm(@Qualifier("hashedCredentialsMatcher") HashedCredentialsMatcher matcher) {
		UserRealm userRealm = new UserRealm();
		userRealm.setCredentialsMatcher(matcher);
		return userRealm;
	}
	@Bean
	public ShiroFilterFactoryBean shirFilter(@Qualifier("securityManager") DefaultWebSecurityManager securityManager) {
		ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
		// 设置 SecurityManager
		bean.setSecurityManager(securityManager);

		bean.setSuccessUrl("/main");
		// 设置登录跳转页面
		bean.setLoginUrl("/toLogin");
		// 设置未授权提示页面
		bean.setUnauthorizedUrl("/error/unAuth");
		/**
		 * Shiro内置过滤器,可以实现拦截器相关的拦截器
		 *    常用的过滤器:
		 *      anon:无需认证(登录)可以访问
		 *      authc:必须认证才可以访问
		 *      user:如果使用rememberMe的功能可以直接访问
		 *      perms:该资源必须得到资源权限才可以访问
		 *      role:该资源必须得到角色权限才可以访问
		 **/
		Map<String, String> filterMap = new LinkedHashMap<>();

		filterMap.put("/login", "anon");
		filterMap.put("/user/index", "authc");
		filterMap.put("/vip/index", "roles[vip]");
		filterMap.put("/druid/**", "anon");
		filterMap.put("/static/asserts/**", "anon");
		filterMap.put("/static/pages/**", "authc");

		filterMap.put("/**", "user"); 
		filterMap.put("/logout", "logout");

		bean.setFilterChainDefinitionMap(filterMap);
		return bean;
	}
	/**
	 * 注入 securityManager
	 */
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager getDefaultWebSecurityManager(HashedCredentialsMatcher hashedCredentialsMatcher) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		// 关联realm.
		securityManager.setRealm(userRealm(hashedCredentialsMatcher));
		securityManager.setRememberMeManager(getRememberMeManager()); //配置记住我的功能
		securityManager.setSessionManager(getSessionManager());
		return securityManager;
	}
	
	/**
	 * 进行记住我的相关配置
	 * 
	 */
	public SimpleCookie getCookie() {
		SimpleCookie simpleCookie=new SimpleCookie("remember"); // 配置cookie的名称为rememberMe
		simpleCookie.setMaxAge(100); // 100s
		return simpleCookie;
	}
	
	public CookieRememberMeManager getRememberMeManager() {
		CookieRememberMeManager rememberMeManager=new CookieRememberMeManager();
		rememberMeManager.setCookie(getCookie());
		rememberMeManager.setCipherKey(Base64.decode("2AvVhdsgUs0FSA3SDFAdag=="));
		return rememberMeManager;
	}
	
	/**
	 * 会话管理
	 */
	public DefaultWebSessionManager getSessionManager() {
		SimpleCookie simpleCookie=new SimpleCookie("sessionId"); 
		simpleCookie.setMaxAge(30); // 60s
		DefaultWebSessionManager sessionManager=new DefaultWebSessionManager();
		sessionManager.setSessionIdCookie(simpleCookie);
		sessionManager.setSessionIdCookieEnabled(true);// 默认为true
		return sessionManager;
	}
}

逻辑认证器UserRealm的代码如下:

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权
     **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行授权");

        Subject subject = SecurityUtils.getSubject();
        UserBean user = (UserBean)subject.getPrincipal();
        if(user != null){
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            // 角色与权限字符串集合
            Collection<String> rolesCollection = new HashSet<>();
            Collection<String> premissionCollection = new HashSet<>();

            Set<RoleBean> roles = user.getRole();
            for(RoleBean role : roles){
                rolesCollection.add(role.getName());
                Set<PermissionBean> permissions = role.getPermissions();
                for (PermissionBean permission : permissions){
                    premissionCollection.add(permission.getUrl());
                }
                info.addStringPermissions(premissionCollection);
            }
            info.addRoles(rolesCollection);
            return info;
        }
        return null;
    }

    /**
     * 认证
     **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行认证");
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        UserBean bean = userService.findByName(token.getUsername());
        if(bean == null){
            throw new UnknownAccountException();
        }
        ByteSource credentialsSalt = ByteSource.Util.bytes(bean.getName());
        return new SimpleAuthenticationInfo(bean, bean.getPassword(),
                credentialsSalt, getName());
    }
}

登入/登出接口:

@RequestMapping("/login")
	public String login(HttpServletRequest request, HttpServletResponse response) {
		response.setHeader("root", request.getContextPath());
		String userName = request.getParameter("username");
		String password = request.getParameter("password");

		if (!StringUtils.isEmpty(userName)) {
			// 1.获取Subject
			Subject subject = SecurityUtils.getSubject();
			// 2.封装用户数据
			UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
			token.setRememberMe(true);
			// 3.执行登录方法
			try {
				subject.login(token);
				return "redirect:/main";
			} catch (UnknownAccountException e) {
				System.out.println("用户名不存在!");
				request.setAttribute("msg", "用户名不存在!");
			} catch (IncorrectCredentialsException e) {
				System.out.println("密码错误!");
				request.setAttribute("msg", "密码错误!");
			}
		}

		return "login";
	}

	@RequestMapping("/logout")
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			subject.logout();
		}
		return "redirect:/main";
	}

其他博文:
Shiro原理剖析

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值