Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java org.springframework.security.authentication.InternalAuthenticationServiceException_Java_Spring_Maven_Spring Mvc_Spring Security - Fatal编程技术网

Java org.springframework.security.authentication.InternalAuthenticationServiceException

Java org.springframework.security.authentication.InternalAuthenticationServiceException,java,spring,maven,spring-mvc,spring-security,Java,Spring,Maven,Spring Mvc,Spring Security,我试图将SpringMVC应用程序与SpringSecurity集成,但在登录之后,我遇到了这个异常 org.springframework.security.authentication.InternalAuthenticationServiceException 这是我的spring-security.xml <beans:beans xmlns="http://www.springframework.org/schema/security" xmlns:beans="htt

我试图将SpringMVC应用程序与SpringSecurity集成,但在登录之后,我遇到了这个异常

org.springframework.security.authentication.InternalAuthenticationServiceException
这是我的spring-security.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:beans="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-4.1.xsd
    http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-4.0.xsd">

    <http auto-config="true">
        <intercept-url pattern="/" access="hasRole('USER')"/>
        <intercept-url pattern="/student/**" access="hasRole('ADMIN')"/>
        <intercept-url pattern="/subject/**" access="hasRole('ADMIN')"/>
        <form-login  login-page="/login"
                     username-parameter="username"
                     password-parameter="password"
                     authentication-success-handler-ref="customSuccessHandler"
                     authentication-failure-url="/accessdenied"/>
        <csrf disabled="true"/>
    </http>

    <authentication-manager>
        <authentication-provider user-service-ref="customUserDetailsService"/>
    </authentication-manager>

    <beans:bean id="customUserDetailsService" class="com.scc.security.service.CustomUserDetailsService"/>
    <beans:bean id="customSuccessHandler" class="com.scc.security.service.CustomSuccessHandler"/>

</beans:beans>
最后这是我的CustomUserDetails服务

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.scc.model.RoleModel;
import com.scc.model.UserModel;
import com.scc.model.UserRoleModel;
import com.scc.security.model.SpringSecurityUser;
import com.scc.service.UserService;

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Transactional(readOnly=true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
       UserModel userModel = userService.loadUserByUsername(username);
        System.out.println("User : " + userModel);
        if( userModel == null ) {
            System.out.println("User not found");
            throw new UsernameNotFoundException("Username not found");
        }
        return new SpringSecurityUser(userModel.getUserId(), userModel.getUsername(), userModel.getPassword(), null, null, null, 
                getGrantedAuthorities(userModel));
    }

    private List<GrantedAuthority> getGrantedAuthorities(UserModel user) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        UserRoleModel userRoleModel = user.getUserRoleModel();
        RoleModel roleModel = userRoleModel.getRoleModel();

        authorities.add(new SimpleGrantedAuthority("ROLE_" + roleModel.getRoleCode()));

        System.out.print("authorities :" + authorities);
        return authorities;
    }

}
import java.util.ArrayList;
导入java.util.List;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.security.core.GrantedAuthority;
导入org.springframework.security.core.authority.SimpleGrantedAuthority;
导入org.springframework.security.core.userdetails.userdetails;
导入org.springframework.security.core.userdetails.userdetails服务;
导入org.springframework.security.core.userdetails.UsernameNotFoundException;
导入org.springframework.stereotype.Service;
导入org.springframework.transaction.annotation.Transactional;
导入com.scc.model.RoleModel;
导入com.scc.model.UserModel;
导入com.scc.model.UserRoleModel;
导入com.scc.security.model.SpringSecurityUser;
导入com.scc.service.UserService;
@服务(“customUserDetailsService”)
公共类CustomUserDetailsService实现UserDetailsService{
@自动连线
私人用户服务;
@事务(只读=真)
公共用户详细信息loadUserByUsername(字符串用户名)
抛出UsernameNotFoundException{
UserModel UserModel=userService.loadUserByUsername(用户名);
System.out.println(“用户:”+userModel);
if(userModel==null){
System.out.println(“未找到用户”);
抛出新的UsernameNotFoundException(“找不到用户名”);
}
返回新的SpringSecurityUser(userModel.getUserId(),userModel.getUsername(),userModel.getPassword(),null,null,
GetGrantedAuthories(userModel));
}
私有列表GetGrantedAuthories(UserModel用户){
列表权限=新建ArrayList();
UserRoleModel UserRoleModel=user.getUserRoleModel();
RoleModel RoleModel=userRoleModel.getRoleModel();
添加(新的SimpleGrantedAuthority(“ROLE_”+roleModel.getRoleCode());
系统输出打印(“权限:”+权限);
返回当局;
}
}

对我来说,一切看起来都很好,但显然不是,有人能告诉我上面的代码有什么问题吗。

嗨,我在运行spring boot应用程序后遇到了同样的异常。 你要做一件简单的事。 只需检查是否创建了临时数据库管理表。向管理表添加新值,如凭据。确保在工作台中测试一次。
然后重新运行application.happy解决方案。

customuserdetails服务:30
正在提供NPE,但是在您提供的代码中,
if(userModel==null){
是第30行,无法生成NPE。请检查异常跟踪和您提供的代码是否在同一版本中。此外,它是一个简单的“NullPointerException”,您可能可以轻松调试它。它甚至不进入userService。loadUserByUsername(username)方法,这是我在服务层中使用的。
位于com.scc.security.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:30)
,这一行打印在日志中。这是由于版本不匹配还是其他原因造成的
<!-- Spring Security -->

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-core</artifactId>
            <version>4.0.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>4.0.1.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>4.0.1.RELEASE</version>
        </dependency>
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

@Component
public class CustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler{

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    @Override
    protected void handle(HttpServletRequest request, 
      HttpServletResponse response, Authentication authentication) throws IOException {
        String targetUrl = determineTargetUrl(authentication);

        if (response.isCommitted()) {
            System.out.println("Can't redirect");
            return;
        }

        redirectStrategy.sendRedirect(request, response, targetUrl);
    }

    protected String determineTargetUrl(Authentication authentication) {
        String url="";

        Collection<? extends GrantedAuthority> authorities =  authentication.getAuthorities();

        List<String> roles = new ArrayList<String>();

        for (GrantedAuthority a : authorities) {
            roles.add(a.getAuthority());
        }

        if (isAdmin(roles)) {
            url = "/student";
        } else {
            url="/accessDenied";
        }

        return url;
    }

    public void setRedirectStrategy(RedirectStrategy redirectStrategy) {
        this.redirectStrategy = redirectStrategy;
    }
    protected RedirectStrategy getRedirectStrategy() {
        return redirectStrategy;
    }

    private boolean isAdmin(List<String> roles) {
        if (roles.contains("ROLE_ADMIN")) {
            return true;
        }
        return false;
    }

}
<c:url var="loginUrl" value="/login"></c:url>
        <form:form commandName="userForm" action="${loginUrl}" method="post" accept-charset="utf-8" autocomplete="off">

                <div class="form-group">

                    <form:input path="username" id="username" class="form-control" type="text" placeholder="Enter Username" name="username" autocomplete="off"/>
                    <form:errors path="username" cssStyle="color: #ff0000;"/>
                </div>

                <div class="form-group">

                    <form:input path="password" id="password" class="form-control" type="password" placeholder="Enter Password" name="password" autocomplete="off"/>
                    <form:errors path="password" cssStyle="color: #ff0000;"/>
                </div>

                <a class="forgetPassword" href="#">Forgot Password ?</a>

                <div class="form-group mt-md">

                    <input class="btn btn-block btn-primary" type="submit" value="SIGN IN" name="submit">

                </div>

        </form:form>
org.springframework.security.authentication.InternalAuthenticationServiceException
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
    at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
    at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
    at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:262)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at com.scc.security.service.CustomUserDetailsService.loadUserByUsername(CustomUserDetailsService.java:30)
    at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
    ... 36 more
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.scc.model.RoleModel;
import com.scc.model.UserModel;
import com.scc.model.UserRoleModel;
import com.scc.security.model.SpringSecurityUser;
import com.scc.service.UserService;

@Service("customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Transactional(readOnly=true)
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
       UserModel userModel = userService.loadUserByUsername(username);
        System.out.println("User : " + userModel);
        if( userModel == null ) {
            System.out.println("User not found");
            throw new UsernameNotFoundException("Username not found");
        }
        return new SpringSecurityUser(userModel.getUserId(), userModel.getUsername(), userModel.getPassword(), null, null, null, 
                getGrantedAuthorities(userModel));
    }

    private List<GrantedAuthority> getGrantedAuthorities(UserModel user) {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();

        UserRoleModel userRoleModel = user.getUserRoleModel();
        RoleModel roleModel = userRoleModel.getRoleModel();

        authorities.add(new SimpleGrantedAuthority("ROLE_" + roleModel.getRoleCode()));

        System.out.print("authorities :" + authorities);
        return authorities;
    }

}