2017-01-18 12 views
5

я получаю ошибку ниже, когда я пытаюсь отправить JSON полезной информации Почтальона плагина хромового браузера контроллер разоблачен как URL REST - http://localhost:8080/services/acc/createAuthenticationCredentialsNotFoundException: Объект проверки подлинности не был найден в контексте безопасности

SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/services] threw exception [Request processing failed; nested exception is org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext] with root cause 
org.springframework.security.authentication.AuthenticationCredentialsNotFoundException: An Authentication object was not found in the SecurityContext 
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.credentialsNotFound(AbstractSecurityInterceptor.java:339) 
    at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:198) 
    at org.springframework.security.access.intercept.aopalliance.MethodSecurityInterceptor.invoke(MethodSecurityInterceptor.java:60) 
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) 
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) 
    at com.webadvisors.controller.HotelRestController$$EnhancerBySpringCGLIB$$e9f80d9.createHotel(<generated>) 
    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:498) 
    at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) 
    at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) 
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:114) 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) 
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) 
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) 
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) 
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) 
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) 
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:650) 
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) 
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:731) 

Я выбрал BasicAuth в качестве типа авторизации и введите имя пользователя и пароль при отправке полезной нагрузки JSON на URL REST в POSTMAN.

1) Контроллер класса

@RestController 
public class AccountRestController { 

    @Autowired 
    private AccountService accountService; 

    @PreAuthorize("hasAnyRole('ADMINISTRATOR')") 
    @RequestMapping(value= "/acc/create", method=RequestMethod.POST) 
    public HotelDTO createHotel(@RequestBody AccountDTO accDTO) throws Exception{ 
     return accountService.create(accDTO); 
    } 
} 

2) Класс настройки безопасности

@Configuration 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
@EnableWebSecurity 
@ComponentScan(basePackages = "com.freelance", scopedProxy = ScopedProxyMode.INTERFACES) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

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

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

    @Override 
    protected void configure(AuthenticationManagerBuilder auth) throws Exception { 
     auth.userDetailsService(userDetailsService); 
     auth.authenticationProvider(authenticationProvider()); 
    } 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
       .authorizeRequests() 
       .antMatchers("/user/**").permitAll() 
       .anyRequest().fullyAuthenticated(); 
     http.httpBasic(); 
     http.csrf().disable(); 
    } 

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

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

3) зависимостей Spring безопасности

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

Я посылаю учетные данные аутентификации в POSTMAN. Но почему я получаю исключение выше.

ответ

4

Вы создали springSecurityFilterChain с WebSecurityConfigurerAdapter, см Spring Security Reference:

Первый шаг заключается в создании нашей Spring Security Конфигурация Java. Конфигурация создает сервлет-фильтр, известный как springSecurityFilterChain, который отвечает за всю безопасность (защищая URL-адреса приложений, проверяя отправленное имя пользователя и пароли, перенаправляя форму регистрации и т. Д.) В рамках вашего приложения.

, но вы не использовали его (это не в вашей трассировке стека).

Необходимо зарегистрироваться springSecurityFilterChain. Если у вас есть окружение сервлетов 3.0+ см Spring Security Reference:

AbstractSecurityWebApplicationInitializer с Spring MVC

Если бы мы использовали Spring в другом месте в нашем приложении мы, вероятно, уже был WebApplicationInitializer, с загрузкой нашей конфигурации Spring. Если мы используем предыдущую конфигурацию, мы получим ошибку. Вместо этого мы должны зарегистрировать Spring Security с существующим ApplicationContext. Например, если бы мы использовали Spring MVC наш SecurityWebApplicationInitializer будет выглядеть примерно так:

import org.springframework.security.web.context.*; 

public class SecurityWebApplicationInitializer 
    extends AbstractSecurityWebApplicationInitializer { 

} 

Это просто только зарегистрировать springSecurityFilterChain фильтр для каждого URL в вашем приложении. После этого мы обеспечили бы загрузку WebSecurityConfig в наш существующий ApplicationInitializer. Например, если бы мы использовали Spring MVC он будет добавлен в getRootConfigClasses()

public class MvcWebApplicationInitializer extends 
     AbstractAnnotationConfigDispatcherServletInitializer { 

    @Override 
    protected Class<?>[] getRootConfigClasses() { 
     return new Class[] { WebSecurityConfig.class }; 
    } 

    // ... other overrides ... 
}