本站公告: 敢于浪费哪怕一个钟头时间的人,说明他还不懂得珍惜生命的全部价值。

Spring Boot集成Shiro权限框架

框架积累 Mignon 18304浏览 3评论

spring-boot maven配置:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.2.7.RELEASE</version>
    <relativePath />
<!-- lookup parent from repository -->
</parent>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-tomcat</artifactId>
    <scope>provided</scope>
</dependency>

shiro maven配置:

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

spring-boot shiro @Configuration配置

@Configuration
public class ShiroConfig {
	
	private static Map<String, String> filterChainDefinitionMap = new LinkedHashMap<String, String>();

	@Bean(name = "cacheShiroManager")
	public CacheManager getCacheManage() {
		return new EhCacheManager();
	}

	@Bean(name = "lifecycleBeanPostProcessor")
	public LifecycleBeanPostProcessor getLifecycleBeanPostProcessor() {
		return new LifecycleBeanPostProcessor();
	}

	@Bean(name = "sessionValidationScheduler")
	public ExecutorServiceSessionValidationScheduler getExecutorServiceSessionValidationScheduler() {
		ExecutorServiceSessionValidationScheduler scheduler = new ExecutorServiceSessionValidationScheduler();
		scheduler.setInterval(900000);
		return scheduler;
	}

	@Bean(name = "hashedCredentialsMatcher")
	public HashedCredentialsMatcher getHashedCredentialsMatcher() {
		HashedCredentialsMatcher credentialsMatcher = new HashedCredentialsMatcher();
		credentialsMatcher.setHashAlgorithmName("MD5");
		credentialsMatcher.setHashIterations(1);
		credentialsMatcher.setStoredCredentialsHexEncoded(true);
		return credentialsMatcher;
	}

	@Bean(name = "sessionIdCookie")
	public SimpleCookie getSessionIdCookie() {
		SimpleCookie cookie = new SimpleCookie("sid");
		cookie.setHttpOnly(true);
		cookie.setMaxAge(-1);
		return cookie;
	}

	@Bean(name = "rememberMeCookie")
	public SimpleCookie getRememberMeCookie() {
		SimpleCookie simpleCookie = new SimpleCookie("rememberMe");
		simpleCookie.setHttpOnly(true);
		simpleCookie.setMaxAge(2592000);
		return simpleCookie;
	}
	
	@Bean
	public CookieRememberMeManager getRememberManager(){
		CookieRememberMeManager meManager = new CookieRememberMeManager();
		meManager.setCipherKey(Base64.decode("4AvVhmFLUs0KTA3Kprsdag=="));
		meManager.setCookie(getRememberMeCookie());
		return meManager;
	}
	
	@Bean(name = "sessionManager")
	public DefaultWebSessionManager getSessionManage() {
		DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
		sessionManager.setGlobalSessionTimeout(1800000);
		sessionManager.setSessionValidationScheduler(getExecutorServiceSessionValidationScheduler());
		sessionManager.setSessionValidationSchedulerEnabled(true);
		sessionManager.setDeleteInvalidSessions(true);
		sessionManager.setSessionIdCookieEnabled(true);
		sessionManager.setSessionIdCookie(getSessionIdCookie());
		EnterpriseCacheSessionDAO cacheSessionDAO = new EnterpriseCacheSessionDAO();
		cacheSessionDAO.setCacheManager(getCacheManage());
		sessionManager.setSessionDAO(cacheSessionDAO);
		// -----可以添加session 创建、删除的监听器
		
		return sessionManager;
	}
	
	@Bean(name = "myRealm")
	public AuthorizingRealm getShiroRealm() {
		AuthorizingRealm realm = new ShiroRealm(getCacheManage(), getHashedCredentialsMatcher());
		realm.setName("shiro_auth_cache");
		realm.setAuthenticationCache(getCacheManage().getCache(realm.getName()));
		realm.setAuthenticationTokenClass(UserAuthenticationToken.class);
		return realm;
	}
	
	@Bean(name = "securityManager")
	public DefaultWebSecurityManager getSecurityManager() {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		securityManager.setCacheManager(getCacheManage());
		securityManager.setSessionManager(getSessionManage());
		securityManager.setRememberMeManager(getRememberManager());
		securityManager.setRealm(getShiroRealm());
		return securityManager;
	}
	
	@Bean
	public MethodInvokingFactoryBean getMethodInvokingFactoryBean(){
		MethodInvokingFactoryBean factoryBean = new MethodInvokingFactoryBean();
		factoryBean.setStaticMethod("org.apache.shiro.SecurityUtils.setSecurityManager");
		factoryBean.setArguments(new Object[]{getSecurityManager()});
		return factoryBean;
	}
	
	@Bean
	@DependsOn("lifecycleBeanPostProcessor")
	public DefaultAdvisorAutoProxyCreator getAutoProxyCreator(){
		DefaultAdvisorAutoProxyCreator creator = new DefaultAdvisorAutoProxyCreator();
		creator.setProxyTargetClass(true);
		return creator;
	}
	
	@Bean
	public AuthorizationAttributeSourceAdvisor getAuthorizationAttributeSourceAdvisor(){
		AuthorizationAttributeSourceAdvisor advisor = new AuthorizationAttributeSourceAdvisor();
		advisor.setSecurityManager(getSecurityManager());
		return advisor;
	}
	
	@Bean(name = "shiroFilter")
	public ShiroFilterFactoryBean getShiroFilterFactoryBean(){
		ShiroFilterFactoryBean factoryBean = new ShiroFilterFactoryBean();
		factoryBean.setSecurityManager(getSecurityManager());
		factoryBean.setLoginUrl("/toLogin");
		filterChainDefinitionMap.put("/resources/**", "anon");
		filterChainDefinitionMap.put("/login**", "anon");
		filterChainDefinitionMap.put("/**", "user");
		factoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);
		return factoryBean;
	}
}

Shiro AuthorizingRealm:

public class ShiroRealm extends AuthorizingRealm {
	
	public ShiroRealm(CacheManager cacheManager, CredentialsMatcher matcher) {
		super(cacheManager, matcher);
	}

	@Autowired
	private ManageUserService userService;

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection paramPrincipalCollection) {
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		LoginUser user = (LoginUser) SecurityUtils.getSubject().getSession().getAttribute(AuthAppConfig.LOGIN_USER);
		if (user != null) {
			// 当前用户角色编码集合
			List<String> roleIds = new ArrayList<>();

			for (LoginUserRole role : userService.findLoginUserRoles(user)) {
				roleIds.add(String.valueOf(role.getId()));
			}
			authorizationInfo.addRoles(roleIds);

			//TODO add permits
			//authorizationInfo.addStringPermissions(null);

		}
		return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)  throws AuthenticationException {
		UserAuthenticationToken token = (UserAuthenticationToken) authenticationToken;
		if (StringUtils.isEmpty(token.getUsername())) {
			throw new IncorrectCredentialsException("username is null!");
		} else if (StringUtils.isEmpty(token.getCredentials())) {
			throw new IncorrectCredentialsException("password is null!");
		}
		LoginUser user = userService.findByUsername(token.getUsername());
		if (user == null) { // 用户不存在
			throw new UnknownAccountException("The user does not exist");
		}
		String userPassword = userService.getUserPassword(user.getId());
		return new SimpleAuthenticationInfo(token.getUsername(), userPassword, getName());
	}
}

自定义UserAuthenticationToken:

public class UserAuthenticationToken implements AuthenticationToken, RememberMeAuthenticationToken {
	private static final long serialVersionUID = 1L;
	private String username;
	private String password;
	private boolean rememberMe;

	public UserAuthenticationToken(String username, String password, boolean rememberMe) {
		super();
		this.username = username;
		this.password = password;
		this.rememberMe = rememberMe;
	}

	/**
	 * 是否记住密码
	 */
	@Override
	public boolean isRememberMe() {
		return rememberMe;
	}

	/**
	 * 获取用户密码
	 */
	@Override
	public Object getCredentials() {
		return this.password.toCharArray();
	}

	/**
	 * 获取用户登录名
	 */
	@Override
	public String getPrincipal() {
		return username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getUsername() {
		return username;
	}
}

这个就是spring-boot 集成 shiro权限框架。

转载请注明:码农博客 » Spring Boot集成Shiro权限框架

游客
发表我的评论 换个身份
取消评论

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
  • 验证码 (必填)点击刷新验证码

网友最新评论 (3)

  1. 访客
    我想问下,我在springmvc里面还要在web.xml里面配置过滤器,怎么才能不写啊?
    景行 1年前 (2017-02-14)回复
    • 访客
      在spring mvc里面肯定是需要加过滤器的,不加过滤器你的请求就不能进入权限框架里面去,晕看成怎么加过滤器了。
      Mignon 1年前 (2017-02-21)回复
    • 访客
      如果你是使用spring boot就不用写web.xml,spring boot的过滤器有2中注册方式:
      1、使用FilterRegistrationBean进行过滤器注册
      2、直接将实现了javax.servlet.Filter类注册为spring bean
      两者的差别是,第一种可以设置过滤器的UrlPatterns和InitParameter等参数
      Mignon 1年前 (2017-02-21)回复

分享:

支付宝

微信