开发者社区> 问答> 正文

Shiro认证(加密出错)的问题,请高手解决,在线等,急!?报错

shiror认证报错如下:

[qtp1235633724-15] DEBUG c.c.s.s.CaptchaFormAuthenticationFilter - 登录失败:Authentication failed for token submission [com.chinagdn.ssc.security.CaptchaUsernamePasswordToken - admin, rememberMe=false (0:0:0:0:0:0:0:1)].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).

org.apache.shiro.authc.AuthenticationException: Authentication failed for token submission [com.chinagdn.ssc.security.CaptchaUsernamePasswordToken - admin, rememberMe=false (0:0:0:0:0:0:0:1)].  Possible unexpected error? (Typical or expected login exceptions should extend from AuthenticationException).
at org.apache.shiro.authc.AbstractAuthenticator.authenticate(AbstractAuthenticator.java:214)
at org.apache.shiro.mgt.AuthenticatingSecurityManager.authenticate(AuthenticatingSecurityManager.java:106)
at org.apache.shiro.mgt.DefaultSecurityManager.login(DefaultSecurityManager.java:270)
at org.apache.shiro.subject.support.DelegatingSubject.login(DelegatingSubject.java:256)
at com.chinagdn.ssc.security.CaptchaFormAuthenticationFilter.executeLogin(CaptchaFormAuthenticationFilter.java:73)
at org.apache.shiro.web.filter.authc.FormAuthenticationFilter.onAccessDenied(FormAuthenticationFilter.java:154)
at org.apache.shiro.web.filter.AccessControlFilter.onAccessDenied(AccessControlFilter.java:133)
at org.apache.shiro.web.filter.AccessControlFilter.onPreHandle(AccessControlFilter.java:162)
at org.apache.shiro.web.filter.PathMatchingFilter.isFilterChainContinued(PathMatchingFilter.java:203)
at org.apache.shiro.web.filter.PathMatchingFilter.preHandle(PathMatchingFilter.java:178)
at org.apache.shiro.web.servlet.AdviceFilter.doFilterInternal(AdviceFilter.java:131)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.apache.shiro.web.servlet.ProxiedFilterChain.doFilter(ProxiedFilterChain.java:66)
at org.apache.shiro.web.servlet.AbstractShiroFilter.executeChain(AbstractShiroFilter.java:449)
at org.apache.shiro.web.servlet.AbstractShiroFilter$1.call(AbstractShiroFilter.java:365)
at org.apache.shiro.subject.support.SubjectCallable.doCall(SubjectCallable.java:90)
at org.apache.shiro.subject.support.SubjectCallable.call(SubjectCallable.java:83)
at org.apache.shiro.subject.support.DelegatingSubject.execute(DelegatingSubject.java:383)
at org.apache.shiro.web.servlet.AbstractShiroFilter.doFilterInternal(AbstractShiroFilter.java:362)
at org.apache.shiro.web.servlet.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:125)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1650)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:583)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1125)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1059)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:110)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:497)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:248)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:540)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:610)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:539)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.chinagdn.ssc.entity.sys.User.roles, could not initialize proxy - no Session
at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:572)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:212)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:551)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:140)
at org.hibernate.collection.internal.PersistentSet.hashCode(PersistentSet.java:447)
at java.util.WeakHashMap.hash(WeakHashMap.java:365)
at java.util.WeakHashMap.getEntry(WeakHashMap.java:494)
at java.util.WeakHashMap.containsKey(WeakHashMap.java:485)
at org.apache.commons.lang3.builder.ToStringStyle.isRegistered(ToStringStyle.java:164)
at org.apache.commons.lang3.builder.ToStringStyle.appendInternal(ToStringStyle.java:462)
at org.apache.commons.lang3.builder.ToStringStyle.append(ToStringStyle.java:436)
at org.apache.commons.lang3.builder.ToStringBuilder.append(ToStringBuilder.java:848)
at org.apache.commons.lang3.builder.ReflectionToStringBuilder.appendFieldsIn(ReflectionToStringBuilder.java:522)
at org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(ReflectionToStringBuilder.java:683)
at org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(ReflectionToStringBuilder.java:282)
at org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(ReflectionToStringBuilder.java:113)
at org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(ToStringBuilder.java:152)
at com.chinagdn.ssc.entity.sys.User.toString(User.java:174)
at java.lang.String.valueOf(String.java:2847)
at java.lang.StringBuilder.append(StringBuilder.java:128)
at com.chinagdn.ssc.security.SystemAuthorizingRealm.doGetAuthenticationInfo(SystemAuthorizingRealm.java:88)
at org.apache.shiro.realm.AuthenticatingRealm.getAuthenticationInfo(AuthenticatingRealm.java:568)
at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doSingleRealmAuthentication(ModularRealmAuthenticator.java:180)
at org.apache.shiro.authc.pam.ModularRealmAuthenticator.doAuthenticate(ModularRealmAuthenticator.java:267)
at org.apache.shiro.authc.AbstractAuthenticator.authenticate(AbstractAuthenticator.java:198)
... 44 more

配置如下:

spring-content-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:aop="http://www.springframework.org/schema/aop"
	xmlns:c="http://www.springframework.org/schema/c" xmlns:cache="http://www.springframework.org/schema/cache"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:lang="http://www.springframework.org/schema/lang" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd 
		http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-4.0.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">


	<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
		<property name="realm" ref="systemAuthorizingRealm" />
		<property name="cacheManager" ref="shiroEhcacheManager" />
	</bean>
	
	<!-- 凭证匹配器
    <bean id="credentialsMatcher" class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
        <property name="hashAlgorithmName" value="md5"/>
        <property name="hashIterations" value="2"/>
        <property name="storedCredentialsHexEncoded" value="true"/>
    </bean> -->

	<!-- 項目自定义的Realm, 所有accountService依赖的dao都需要用depends-on声明 -->
	<bean id="systemAuthorizingRealm" class="com.chinagdn.ssc.security.SystemAuthorizingRealm">
		 <property name="userService" ref="userService"/>
	</bean>
	
	
	<!-- Shiro Filter -->
	<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
		<property name="securityManager" ref="securityManager" />
		<property name="loginUrl" value="/login" />
		<property name="successUrl" value="/index" />
		<!-- 没有权限的跳转路径 
		<property name="unauthorizedUrl" value="/error"/> -->
		<property name="filters">
			<util:map>
				 <entry key="authc" value-ref="captchaFormAuthenticationFilter"/>
			</util:map>
        </property>
		<property name="filterChainDefinitions">
			<value>
				/login = authc
				/logout = logout
				/static/** = anon
				/images/** = anon
				/sys/user/save = anon
				/** = user
			</value>
		</property>
	</bean>

	<!-- 用户授权信息Cache, 采用EhCache -->
	<bean id="shiroEhcacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
		<property name="cacheManagerConfigFile" value="classpath:ehcache/ehcache-shiro.xml" />
	</bean>

	<!-- 保证实现了Shiro内部lifecycle函数的bean执行 -->
	<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
	
	
	<!-- AOP式方法级权限检查  -->
	<bean class="org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator" depends-on="lifecycleBeanPostProcessor">
		<property name="proxyTargetClass" value="true" />
	</bean>
	<bean class="org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor">
    	<property name="securityManager" ref="securityManager"/>
	</bean> 
	
	<bean id="captchaFormAuthenticationFilter" class="com.chinagdn.ssc.security.CaptchaFormAuthenticationFilter"/>
</beans>



SystemAuthorizingRealm.java

package com.chinagdn.ssc.security;

import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
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.credential.HashedCredentialsMatcher;
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.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.chinagdn.ssc.common.Constants;
import com.chinagdn.ssc.common.utils.Encodes;
import com.chinagdn.ssc.entity.sys.Resource;
import com.chinagdn.ssc.entity.sys.Role;
import com.chinagdn.ssc.entity.sys.User;
import com.chinagdn.ssc.service.sys.UserService;

/**
 * 扩展AuthorizingRealm
 * 
 * @author Edward
 * 
 */
public class SystemAuthorizingRealm extends AuthorizingRealm {

	public static Logger logger = LoggerFactory.getLogger(SystemAuthorizingRealm.class);

	private UserService userService;

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	/**
	 * 鉴权的时候调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		String username = (String) principals.fromRealm(getName()).iterator().next();
		logger.debug("AuthorizationInfo[username]:" + username);
		if (StringUtils.isNotEmpty(username)) {
			User user = userService.getByUsername(username);
			logger.debug("AuthorizationInfo[user]:" + user);
			if (null != user) {
				SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
				Set<Role> roles = user.getRoles();
				logger.debug("user[roles]:" + username + "[" + roles + "]");
				for (Role role : roles) {
					Set<Resource> resources = role.getResources();
					logger.debug("role[resources]:" + role + "[" + resources + "]");
					for (Resource resource : resources) {
						authorizationInfo.addStringPermission(resource.getPermission());
					}
				}
				return authorizationInfo;
			}
		}
		return null;

	}

	/**
	 * 登录验证数据正确性
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
		CaptchaUsernamePasswordToken token = (CaptchaUsernamePasswordToken) authcToken;
		// 通过表单接收的用户名
		String username = token.getUsername();
		logger.debug("AuthenticationInfo[username]:" + username);
		if (StringUtils.isNotEmpty(username)) {
			User user = userService.getByUsername(username);
			logger.debug("AuthenticationInfo[user]:" + user);
			if (null != user) {
				SecurityUtils.getSubject().getSession().setAttribute(Constants.CURRENT_USER, user);
				byte[] salt = Encodes.decodeHex(user.getSalt());
				return new SimpleAuthenticationInfo(user.getUsername(), user.getPassword(), ByteSource.Util.bytes(salt), getName());
			}
		}
		return null;
	}

	/**
	 * 设定Password校验的Hash算法与迭代次数.
	 */
	@PostConstruct
	public void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserService.HASH_ALGORITHM);
		matcher.setHashIterations(UserService.HASH_INTERATIONS);

		setCredentialsMatcher(matcher);
	}

}



userservice.java
package com.chinagdn.ssc.service.sys;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.chinagdn.ssc.common.utils.Digests;
import com.chinagdn.ssc.common.utils.Encodes;
import com.chinagdn.ssc.dao.sys.UserDao;
import com.chinagdn.ssc.entity.sys.User;
import com.chinagdn.ssc.service.BaseService;

@Service
public class UserService extends BaseService {
	
	public static final String HASH_ALGORITHM = "SHA-1";
	public static final int HASH_INTERATIONS = 1024;
	private static final int SALT_SIZE = 8;

	@Autowired
	private UserDao userDao;

	public void save(User user) {
		entryptPassword(user);
		userDao.save(user);
	}

	public User get(Integer id) {
		return userDao.get(id);
	}
	

	public User getByUsername(String username){
		return userDao.getByUsername(username);
	}
	
	/**
	 * 设定安全的密码,生成随机的salt并经过1024次 sha-1 hash
	 */
	private void entryptPassword(User user) {
		byte[] salt = Digests.generateSalt(SALT_SIZE);
		user.setSalt(Encodes.encodeHex(salt));

		byte[] hashPassword = Digests.sha1(user.getPassword().getBytes(), salt, HASH_INTERATIONS);
		user.setPassword(Encodes.encodeHex(hashPassword));
	}
	
}



请各位指导一下,谢谢!在线等,急!!!


展开
收起
爱吃鱼的程序员 2020-06-14 18:39:25 734 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB

    如果不使用加密,使用明文的就可以认证通过!在线等高手指导!<spanstyle="font-size:13.3333330154419px;">你好,请问你的问题解决了吗?可以请教吗同样问题求解答CaptchaUsernamePasswordToken 这个类你怎么写的?

    2020-06-14 18:39:41
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
基于可信计算与加密计算 打造云上原生计算安全 立即下载
视频服务特色解决方案——直播连麦与点播加密 立即下载
量子加密通信技术 立即下载