好了, 如此简单的代码。一个最基本的Rest API /api/hello已经开发完成,并被Spring Security通过Basic Auth进行保护。
1 2 3 4 5
➜ ~ curl http://localhost:8080/api/hello {"timestamp":1489887539548,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/api/hello"}
➜ ~ curl http://user:6a3810c9-1ad7-4694-a617-0411fec20c60@localhost:8080/api/hello Hello World
用户名密码在服务的启动Log中找。
1 2 3 4 5 6 7 8
2017-03-19 09:30:31.492 INFO 76011 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-03-19 09:30:31.571 INFO 76011 --- [ restartedMain] o.s.w.s.handler.SimpleUrlHandlerMapping : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler] 2017-03-19 09:30:31.959 INFO 76011 --- [ restartedMain] b.a.s.AuthenticationManagerConfiguration :
Using default security password: 6a3810c9-1ad7-4694-a617-0411fec20c60
2017-03-19 09:30:32.047 INFO 76011 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: OrRequestMatcher [requestMatchers=[Ant [pattern='/css/**'], Ant [pattern='/js/**'], Ant [pattern='/images/**'], Ant [pattern='/webjars/**'], Ant [pattern='/**/favicon.ico'], Ant [pattern='/error']]], [] 2017-03-19 09:30:32.234 INFO 76011 --- [ restartedMain] o.s.s.web.DefaultSecurityFilterChain : Creating filter chain: Ant [pattern='/h2-console/**'], [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter@e89b69d, org.springframework.security.web.context.SecurityContextPersistenceFilter@1932f51e, org.springframework.security.web.header.HeaderWriterFilter@65c2ab9f, org.springframework.security.web.authentication.logout.LogoutFilter@3d247454, org.springframework.security.web.authentication.www.BasicAuthenticationFilter@1e897c55, org.springframework.security.web.savedrequest.RequestCacheAwareFilter@75a44063, org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter@31201444, org.springframework.security.web.authentication.AnonymousAuthenticationFilter@160c32f9, org.springframework.security.web.session.SessionManagementFilter@507dd201, org.springframework.security.web.access.ExceptionTranslationFilter@21062771, org.springframework.security.web.access.intercept.FilterSecurityInterceptor@1f8069f6]