尝试获取用户时,SecurityContextHolder上的Spring mvc java.lang.NullPointerException

时间:2016-06-27 21:13:27

标签: java spring nullpointerexception

嗨,大家好我的弹簧安全模块有问题我正在使用弹簧mvc

这是我的安全配置类

@Configuration
@EnableWebSecurity
@Order(1)
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration 
                      extends WebSecurityConfigurerAdapter
{
@Autowired
DataSource dataSource;

@Autowired
@Qualifier("userDetailsService")
private UserDetailsService userDetailsService;


@Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception
{
    auth.userDetailsService(userDetailsService);
    auth.authenticationProvider(authProvider());
}

@Bean(name="userDetailsService")
public UserDetailsService userDetailsService(){
    JdbcDaoImpl jdbcImpl = new JdbcDaoImpl();
    jdbcImpl.setDataSource(dataSource);
    jdbcImpl.setUsersByUsernameQuery("SELECT email,password,enabled FROM users WHERE email=?");
    jdbcImpl.setAuthoritiesByUsernameQuery("SELECT email, role FROM users_roles WHERE email=?");
    return jdbcImpl;
}

@Bean
public DaoAuthenticationProvider authProvider() {
    DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
    authProvider.setUserDetailsService(userDetailsService);
    authProvider.setPasswordEncoder(passwordEncoder());
    return authProvider;
}


@Bean(name = "passwordEncoder")
public PasswordEncoder passwordEncoder()
{
    return new BCryptPasswordEncoder();
}




@Override
public void configure(WebSecurity web) throws Exception
{
    web.ignoring().antMatchers("/webjars/**", "/resources/**");
}


@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception
{
    return super.authenticationManagerBean();
}



@Override
protected void configure(HttpSecurity http) throws Exception
{

    http.requestMatchers()
            .antMatchers("/login", "/oauth/**").and().formLogin()
            .loginPage("/login")
            .failureUrl("/login?error")
            .usernameParameter("email").passwordParameter("password")
            .permitAll().and().authorizeRequests().anyRequest().authenticated()
            .and().csrf()
            .and().exceptionHandling().accessDeniedPage("/Access_Denied");

}
}

这是控制器代码

@RequestMapping(value = "/product/" , 
      method = RequestMethod.GET)
@ResponseBody
public String singleProduct( )
{

    Authentication auth =         SecurityContextHolder.getContext().getAuthentication();
    String name = auth.getCredentials().toString();
   return name;

}

和初始化程序

public class Initializers 
   extends AbstractDispatcherServletInitializer {


public void onStartup(ServletContext container) throws ServletException
{
    super.onStartup(container);
    DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
    filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
    container.addFilter("springSecurityFilterChain",  filter).addMappingForUrlPatterns(null, false, "/*");
}

@Override
protected WebApplicationContext createRootApplicationContext() {
    return null;
}

@Override
protected WebApplicationContext createServletApplicationContext() {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.scan(ClassUtils.getPackageName(getClass()));
    return context;
}

@Override
protected String[] getServletMappings() {
    return new String[] { "/" };
}


protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
    String filterName = Conventions.getVariableName(filter);
    FilterRegistration.Dynamic registration = servletContext.addFilter(filterName, filter);
    registration.setAsyncSupported(true);
    registration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    return registration;
}

}

和例外

    StandardWrapperValve[dispatcher]: Servlet.service() for servlet      dispatcher threw exception
java.lang.NullPointerException
    at .singleProduct(SiteController.java:105)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at  sun.reflect.NativeMethodAccessorImpl.invoke
(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke
(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke
(InvocableHandlerMethod.java:222)
    at org.springframework.web.method.support.InvocableHandlerMethod
.invokeForRequest(InvocableHandlerMethod.java:137)
    at org.springframework.web.servlet.mvc.method.annotation
.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
    at org.springframework.web.servlet.mvc.method
.annotation.RequestMappingHandlerAdapter
.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
    at org.springframework.web.servlet.mvc.method.annotation
.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
    at org.springframework.web.servlet.mvc.method
.AbstractHandlerMethodAdapter
.handle(AbstractHandlerMethodAdapter.java:85)
    at org.springframework.web.servlet
.DispatcherServlet.doDispatch(DispatcherServlet.java:959)
    at org.springframework.web.servlet
.DispatcherServlet.doService(DispatcherServlet.java:893)
    at org.springframework.web.servlet
.FrameworkServlet.processRequest(FrameworkServlet.java:969)
    at org.springframework
.web.servlet.FrameworkServlet
.doGet(FrameworkServlet.java:860)
    at javax.servlet
.http.HttpServlet.service(HttpServlet.java:687)
    at org.springframework
.web.servlet.FrameworkServlet.service(FrameworkServlet.java:845)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:344)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:121)
    at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:207)
    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:256)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:214)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:316)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:416)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:283)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:459)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:167)
    at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:206)
    at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:180)
    at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:235)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:283)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:200)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:132)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:111)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:536)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:591)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:571)
    at java.lang.Thread.run(Thread.java:745)
]]

当前的春季版本4.2.4.RELEASE

maven依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>${org.springframework-version}</version>
</dependency>




<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>${org.springframework-version}</version>
</dependency>


<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-beans</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
    <exclusions>
        <!-- Exclude Commons Logging in favor of SLF4j -->
        <exclusion>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context-support</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aop</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-jdbc</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-tx</artifactId>
    <version>${org.springframework-version}</version>

</dependency>


<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-jpa</artifactId>
    <version>1.9.4.RELEASE</version>
</dependency>
<!--throw default csr token exception-->
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-config</artifactId>
    <version>4.0.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-core</artifactId>
    <version>4.0.4.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-messaging</artifactId>
    <version>4.0.4.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-taglibs</artifactId>
    <version>4.0.4.RELEASE</version>
</dependency>


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

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-expression</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>


<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-java-dsl</artifactId>
    <version>1.1.2.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.integration</groupId>
    <artifactId>spring-integration-websocket</artifactId>
    <version>4.2.5.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.session</groupId>
    <artifactId>spring-session</artifactId>
    <version>1.1.1.RELEASE</version>
</dependency>

<dependency>
    <groupId>org.springframework.ws</groupId>
    <artifactId>spring-ws</artifactId>
    <version>2.1.4.RELEASE</version>
</dependency>

2 个答案:

答案 0 :(得分:1)

尽量避免使用 HttpServletRequest 请求,因为这是获取用户最不安全的方式。

答案 1 :(得分:0)

您可以从HttpServletRequest对象中获取用户:

@RequestMapping(value = "/product/" , 
      method = RequestMethod.GET)
@ResponseBody
public String singleProduct(HttpServletRequest request)
{
    String name = request.getUserPrincipal().getName();
   return name;

}

你也可以从Authentication类中获取它:

Authentication auth =         SecurityContextHolder.getContext().getAuthentication();
String name = auth.getName();