java - org.springframework.security.authentication.InternalAuthenticationServiceException

标签 java spring maven spring-mvc spring-security

我试图将 Spring MVC 应用程序与 Spring Security 集成,但登录后出现此异常;

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>

这是我的 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    id="WebApp_ID" version="3.0">

    <!-- Spring MVC -->
    <servlet>
        <servlet-name>scc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/config/scc-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>scc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Loads Spring Security config file -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-security.xml</param-value>
    </context-param>

    <!-- Spring Security -->
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

这些是我在 pom.xml 中拥有的 spring 安全依赖项;

<!-- 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>

为了实现基于角色的登录,我使用以下 customSuccessHandler;

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;
    }

}

这是我的login.jsp页面;

<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

最后这是我的 customUserDetailsS​​ervice;

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;
    }

}

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

最佳答案

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

关于java - org.springframework.security.authentication.InternalAuthenticationServiceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39003177/

相关文章:

java - 使用 RestTemplate 解析本地 JSON 文件

java - 用于查找最常出现的列值的 Hive UDAF

java - 脚本标签内的换行符

没有阶段的 JavaFx FileChooser

java - 以交互方式向 java.lang.Process 发送命令失败

java - 如何在 Spring Data Neo4J 3.0.0(发布版)中向节点添加第二个标签?

java - Spring是否提供了一个类来衡量迭代代码的性能?

maven - Nexus 不会提供来自默认公共(public)组的快照

maven - 我需要在我的 POM.xml 中有一个 Parent 声明吗?

java - json文件的maven资源过滤