Ajax Spring security j_Spring_security_check调用给出404未找到错误

Ajax Spring security j_Spring_security_check调用给出404未找到错误,ajax,spring,spring-security,Ajax,Spring,Spring Security,我正在尝试使用spring security创建登录身份验证。我的登录url/knowledgeBase/j_spring\u security\u check出现404未找到错误。我已在安全xml中正确定义了自定义筛选器和url。我还在web xml文件中添加了一个安全过滤器。我通过序列化表单数据,通过ajax请求调用此url。我在另一个项目中成功地使用了这段代码,但现在我遇到了这个错误。原因可能是什么 这是security.xml文件 <?xml version="1.0" encod

我正在尝试使用spring security创建登录身份验证。我的登录url
/knowledgeBase/j_spring\u security\u check
出现404未找到错误。我已在安全xml中正确定义了自定义筛选器和url。我还在web xml文件中添加了一个安全过滤器。我通过序列化表单数据,通过ajax请求调用此url。我在另一个项目中成功地使用了这段代码,但现在我遇到了这个错误。原因可能是什么

这是security.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:beans="http://www.springframework.org/schema/beans"
             xsi:schemaLocation="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd
                        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- Disabled Security for Static Resources -->
    <global-method-security pre-post-annotations="enabled" secured-annotations="enabled"/>
    <http pattern="/static/**" security="none"/>

    <beans:bean id="shaPasswordEncoder" class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
        <beans:constructor-arg value="256"/>
    </beans:bean>

    <beans:bean id="userService" class="com.gsu.knowledgebase.service.UserService"/>

    <!-- Ajax Aware Handler -->
    <beans:bean id="authEntryPoint"
                class="com.gsu.knowledgebase.spring.AjaxAwareLoginUrlAuthenticationEntryPoint"
                scope="singleton">
        <beans:constructor-arg name="loginFormUrl" value="/knowledge-base"/>
    </beans:bean>

    <http authentication-manager-ref="authenticationManager" entry-point-ref="authEntryPoint"
          pattern="/knowledge-base/**"
          use-expressions="true" disable-url-rewriting="true">

        <custom-filter position="BASIC_AUTH_FILTER" ref="loginFilter"/>
        <logout logout-success-url="/knowledge-base" invalidate-session="true" delete-cookies="JSESSIONID"
                logout-url="/knowledgeBase/j_spring_security_logout"/>

        <intercept-url pattern="/knowledge-base/" access="permitAll"/>
        <intercept-url pattern="/knowledge-base/memory"
                       access="hasRole('ADMIN') || hasRole('MODERATOR') || hasRole('USER')"/>

        <access-denied-handler error-page="/knowledge-base/error/403"/>
        <session-management session-authentication-error-url="/knowledge-base/error/sessionExpired"/>
    </http>

    <!-- ************************** -->

    <authentication-manager id="authenticationManager">
        <authentication-provider user-service-ref="userService">
            <password-encoder ref="shaPasswordEncoder"/>
        </authentication-provider>
    </authentication-manager>

    <beans:bean id="loginFilter"
                class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
        <beans:property name="authenticationManager" ref="authenticationManager"/>
        <beans:property name="filterProcessesUrl" value="/knowledgeBase/j_spring_security_check"/>
        <beans:property name="authenticationSuccessHandler">
            <beans:bean class="com.gsu.knowledgebase.spring.AuthenticationSuccessHandler"/>
        </beans:property>
        <beans:property name="authenticationFailureHandler">
            <beans:bean class="com.gsu.knowledgebase.spring.AuthenticationFailureHandler"/>
        </beans:property>
    </beans:bean>

    <!-- ************************** -->


</beans:beans>
但我收到一个404未找到错误

更新:

解决这个问题后,我的用户服务出现了问题。它无法识别其中定义的自动关联依赖项。我尝试在变量上直接使用自动连接注释,也尝试单独在构造函数上使用
KnowledBasedao
loadUserByUsername
中为空。在启动时,该类的构造函数被调用3次。每个都创建不同的对象。第一个是使用默认的空构造函数创建的。另外两个是使用自动连接构造函数创建的,并为
knowledgebaseDao
分配正确的类。当从登录页面调用userservice时,它使用第一个userservice类,并引发空指针异常。这是我的密码:

@Component("userService")
public class UserService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private KnowledgeBaseDao knowledgeBaseDao;

    public UserService(){
        System.out.println();
    }

    @Autowired
    public UserService(KnowledgeBaseDao knowledgeBaseDao) {
        this.knowledgeBaseDao = knowledgeBaseDao;
        }

    public UserDetails loadUserByUsername(String login) throws AuthenticationException {
        logger.info("UserDetails Database Service : " + login);

        // check user exists in database
        User user = knowledgeBaseDao.findUserByEmail(login);
        if (user == null) {
            logger.warn("User({}) does not exist in system", login);
            throw new UsernameNotFoundException("There is no user with this username.");
        }

        boolean containsLoginRole = checkLoginRole(user);

        if (!containsLoginRole) {
            throw new UsernameNotFoundException("Access denied.");
        }

        if ((user.getStatus() == null || user.getStatus() == 0)) {
            throw new UsernameNotFoundException("User is not confirmed");
        }

        //boolean enabled = user.getStatus() == AccountStatus.ACTIVE;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        if (user.getLoginTryCount() != null && user.getLoginTryCount() >= 3) {
            accountNonLocked = false;
        }

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), true, accountNonExpired,
                credentialsNonExpired, accountNonLocked, this.getAuthorities(user.getRoleId()));
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roleList) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (Role role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Long roleId) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        authorities.add(new SimpleGrantedAuthority(Constants.ROLE_NAME(roleId.intValue())));

        return authorities;
    }

    private boolean checkLoginRole(User user) {
        if (user.getRoleId() == 0) {
            return false;
        }

        if (user.getRoleId() == Constants.ROLE_ADMIN
                || user.getRoleId() == Constants.ROLE_MODERATOR
                || user.getRoleId() == Constants.ROLE_USER) {
            return true;
        } else {
            return false;
        }
    }
}
@组件(“用户服务”)
公共类UserService实现UserDetailsService{
私有静态最终记录器Logger=LoggerFactory.getLogger(UserService.class);
私人知识库知识库;
公共用户服务(){
System.out.println();
}
@自动连线
公共用户服务(KnowledgeBaseDao KnowledgeBaseDao){
this.knowledgeBaseDao=knowledgeBaseDao;
}
public UserDetails loadUserByUsername(字符串登录)引发AuthenticationException{
logger.info(“UserDetails数据库服务:”+登录);
//检查数据库中是否存在用户
User User=knowledgeBaseDao.findUserByEmail(登录);
if(user==null){
警告(“用户({})在系统中不存在”,登录名);
抛出新用户名NotFoundException(“没有使用此用户名的用户”);
}
布尔containsLoginRole=checkLoginRole(用户);
如果(!containsLoginRole){
抛出新用户名NotFoundException(“拒绝访问”);
}
if((user.getStatus()==null | | user.getStatus()==0)){
抛出新用户名NotFoundException(“用户未确认”);
}
//布尔启用=user.getStatus()==AccountStatus.ACTIVE;
布尔值accountNonExpired=true;
布尔CredentialsNoExpired=true;
布尔值accountNonLocked=true;
if(user.getLoginTryCount()!=null&&user.getLoginTryCount()>=3){
accountNonLocked=false;
}
返回新的org.springframework.security.core.userdetails.User(User.getEmail(),User.getPassword(),true,accountNonExpired,
CredentialsNoExpired,AccountNoLocked,this.getAuthories(user.getRoleId());
}

public Collection你确定/knowledgeBase是根servlet上下文url吗?我认为它是知识库..因此在这种情况下,正确的url使登录请求应该是/knowledgeBase/knowledgeBase/j_spring\u security\u check尝试通过邮递员发帖子

现在我的用户服务遇到问题,它无法识别自动登录红色依赖项。我已经更新了我的问题,你能看一下吗?你已经将userdetailsservice注册为bean了吗?在安全配置中,是的。我正在从身份验证管理器引用这个bean。嗯,我认为你需要在声明中添加一个数据源,它必须被配置如果您在哪个声明中使用sql或其他东西,请将其添加到您的数据源?
<form id="login-form">
                        <div class="form-group">
                            <label>Username</label>
                            <input type="text" class="form-control" name="j_username" ng-model="username"
                                   placeholder="Your username">
                        </div>

                        <div class="form-group">
                            <label>Password</label>
                            <input type="password" name="j_password" class="form-control" ng-model="password"
                                   placeholder="Password">
                        </div>
                        <div class="form-check">
                            <!--<input type="checkbox" class="form-check-input" id="exampleCheck1">-->
                            <!--<label class="form-check-label">Check me out</label>-->
                        </div>
                        <span class="validation-message" style="display:none;">{{validationMessage}}</span>
                        <span class="success-message" style="display:none;">{{successMessage}}</span>
                        <input type="button" class="btn btn-default blue" value="Log in"
                               ng-click="login()">
                    </form>
$.ajax({
                            type: "POST",
                            url: 'knowledgeBase/j_spring_security_check',
                            data: jQuery("#login-form").serialize(), // serializes the form's elements.
                            success: function (data) {
                                window.location = "/knowledge-base/memory";
                            },
                            error: function (data, textStatus, jqXHR) {
                                if (data.status == 410) {
                                } else if (data.status == 409) {
                                } else if (data.status == 406) {
                                } else {
                                }

                                $scope.$digest();

                                printError(textStatus);
                            }
                        });
@Component("userService")
public class UserService implements UserDetailsService {
    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    private KnowledgeBaseDao knowledgeBaseDao;

    public UserService(){
        System.out.println();
    }

    @Autowired
    public UserService(KnowledgeBaseDao knowledgeBaseDao) {
        this.knowledgeBaseDao = knowledgeBaseDao;
        }

    public UserDetails loadUserByUsername(String login) throws AuthenticationException {
        logger.info("UserDetails Database Service : " + login);

        // check user exists in database
        User user = knowledgeBaseDao.findUserByEmail(login);
        if (user == null) {
            logger.warn("User({}) does not exist in system", login);
            throw new UsernameNotFoundException("There is no user with this username.");
        }

        boolean containsLoginRole = checkLoginRole(user);

        if (!containsLoginRole) {
            throw new UsernameNotFoundException("Access denied.");
        }

        if ((user.getStatus() == null || user.getStatus() == 0)) {
            throw new UsernameNotFoundException("User is not confirmed");
        }

        //boolean enabled = user.getStatus() == AccountStatus.ACTIVE;
        boolean accountNonExpired = true;
        boolean credentialsNonExpired = true;
        boolean accountNonLocked = true;

        if (user.getLoginTryCount() != null && user.getLoginTryCount() >= 3) {
            accountNonLocked = false;
        }

        return new org.springframework.security.core.userdetails.User(user.getEmail(), user.getPassword(), true, accountNonExpired,
                credentialsNonExpired, accountNonLocked, this.getAuthorities(user.getRoleId()));
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Collection<Role> roleList) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for (Role role : roleList) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }
        return authorities;
    }

    public Collection<? extends GrantedAuthority> getAuthorities(Long roleId) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        authorities.add(new SimpleGrantedAuthority(Constants.ROLE_NAME(roleId.intValue())));

        return authorities;
    }

    private boolean checkLoginRole(User user) {
        if (user.getRoleId() == 0) {
            return false;
        }

        if (user.getRoleId() == Constants.ROLE_ADMIN
                || user.getRoleId() == Constants.ROLE_MODERATOR
                || user.getRoleId() == Constants.ROLE_USER) {
            return true;
        } else {
            return false;
        }
    }
}