2016-12-11 75 views
4

我想在春季啓動應用程序配置Spring Security如下未經授權:春季安全401未固定端點

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true) 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Autowired 
private RestAuthenticationEntryPoint unauthorizedHandler; 

@Bean 
public JwtAuthenticationFilter authenticationTokenFilterBean() throws Exception { 
    JwtAuthenticationFilter authenticationTokenFilter = new JwtAuthenticationFilter(); 
    authenticationTokenFilter.setAuthenticationManager(authenticationManagerBean()); 
    return authenticationTokenFilter; 
} 

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

    //@formatter:off 
    httpSecurity 
     .csrf() 
     .disable() 
     .exceptionHandling() 
     .authenticationEntryPoint(this.unauthorizedHandler) 
     .and() 
     .sessionManagement() 
     .sessionCreationPolicy(SessionCreationPolicy.STATELESS) 
     .and() 
     .authorizeRequests() 
     .antMatchers(HttpMethod.OPTIONS, "/**").permitAll() 
     .antMatchers("/login", "/singup", "/subscribers").permitAll() 
     .anyRequest().authenticated(); 

     // Custom JWT based security filter 
    httpSecurity    
     .addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class); 

    //@formatter:on 

} 
} 

我unauthorizedHandler是:

public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint { 

private static final Logger LOGGER = LoggerFactory.getLogger(RestAuthenticationEntryPoint.class); 

@Override 
public void commence(HttpServletRequest request, HttpServletResponse response, 
     AuthenticationException authException) throws IOException, ServletException { 
    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized"); 
} 

} 

最後,REST控制器對於/訂戶是:

@RestController 
public class SubscriberRestController { 

@Autowired 
ISubscribersService subscribersService; 

@RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.GET) 
@ResponseBody 
public Number subscriberCount() { 

    return subscribersService.subscribersCount(); 
} 

@RequestMapping(value = RequestMappingConstants.SUBSCRIBERS, method = RequestMethod.POST) 
public String subscriberPost(@RequestBody SubscriberDocument subscriberDocument) { 

    return subscribersService.subscribersInsert(subscriberDocument); 
} 

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

    return "This is a test"; 
} 

} 

我使用郵遞員來測試端點,當我做POST「本地主機:8080 /用戶」,我得到:

Postman result

我想有開端點(/用戶)沒有任何安全控制或憑證檢查,對singup和登錄和驗證的用戶安全端點端點。

謝謝! :)

+0

如果我這樣做,它允許我訪問/訂戶,但也允許我訪問安全的REST端點。 @Sobik –

+1

這就是你通過重寫'requireAuthentication'來編寫自己的程序。它現在總是會返回這個。你爲什麼要自己實施JWT支持? Spring Security已經有了一個擴展。 –

+0

我在學習春季安全,我對春季安全的知識很差。如何使用Spring Security默認的JWT支持? @ M.Deinum –

回答

0

春天啓動不應用配置,因爲找不到它。 Application.java配置包不包含在@ComponentScan內容中。

+0

默認情況下,Spring應用程序註釋@Configuration應該創建配置bean。 – dikkini

-1

一些經過研究,這裏是解決方案:

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class }) 
@ComponentScan(basePackages = { PackageConstants.PACKAGE_CONTROLLERS_REST, PackageConstants.PACKAGE_SERVICES, 
     PackageConstants.PACKAGE_SERVICES_IMPL, PackageConstants.PACKAGE_MONGO_REPOSITORIES, 
     PackageConstants.PACKAGE_MONGO_REPOSITORIES_IMPL, PackageConstants.PACKAGE_UTILS }) 
public class Application { 

    // Clase principal que se ejecuta en el bootrun 

    public static void main(String[] args) { 

     SpringApplication.run(Application.class, args); 
    } 
} 

主線@SpringBootApplication(exclude = {SecurityAutoConfiguration.class })它告訴不使用Spring啓動安全自動配置的配置。這不是完整的答案,因爲現在你必須告訴Spring用戶你的Spring Security配置類。另外我建議你用init Root Config Classes,ApplicationConfiguration創建Initializer類,並拒絕使用SpringBoot應用程序。事情是這樣的:

ApplicationConfig:

@Configuration 
@EnableWebMvc 
@ComponentScan("com.trueport.*") 
@PropertySource("classpath:app.properties") 
public class ApplicationConfig extends WebMvcConfigurerAdapter { 
    .... 
} 

ApplicationSecurityConfig:

@Configuration 
@EnableWebSecurity 
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true) 
public class ApplicationSecurityConfig extends WebSecurityConfigurerAdapter { 
    .... 
} 

初始化程序:

public class Initializer implements WebApplicationInitializer { 

    private static final String DISPATCHER_SERVLET_NAME = "dispatcher"; 

    @Override 
    public void onStartup(ServletContext servletContext) throws ServletException { 
     AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext(); 
     .... 
     DispatcherServlet dispatcherServlet = new DispatcherServlet(ctx); 
     dispatcherServlet.setThrowExceptionIfNoHandlerFound(true); 
     ctx.register(ApplicationConfig.class); 
     ServletRegistration.Dynamic servlet =  servletContext.addServlet(DISPATCHER_SERVLET_NAME, 
      dispatcherServlet); 
     servlet.addMapping("/"); 
     servlet.setLoadOnStartup(1); 
     servlet.setAsyncSupported(true); 
    } 
} 
+0

Hi @dikkini!這對我不起作用,我不明白我的錯誤在哪裏。 –

+0

我有'.antMatchers(「/ login/**」,「/ signup/**」,「/ subscribers」)。匿名()'和我得到401未經授權的郵遞員對http:// localhost:8080 /訂戶@dikkini –

+0

它也不工作。也許一些自動Spring引導配置使它失敗? –