【发布时间】:2017-04-26 10:35:21
【问题描述】:
我正在尝试在 Spring Boot 应用程序上配置 Spring Security,如下所示:
@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
}
}
我的未授权处理程序是:
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");
}
}
最后,/subscribers 的 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";
}
}
我使用邮递员测试端点,当我对“localhost:8080/subscribers”进行 POST 时,我得到:
我希望在没有任何安全控制或凭据检查的情况下打开端点(/订阅者)、用于登录和登录的端点以及用于经过身份验证的用户的安全端点。
谢谢! :)
【问题讨论】:
-
如果我这样做,它允许我访问 /subscribers,但也允许我访问安全的 REST 端点。 @索比克
-
这就是您通过覆盖
requiresAuthentication自己编写的内容。它现在总是会返回这个。你为什么要自己实现 JWT 支持? Spring Security 已经有一个扩展。 -
我正在学习 Spring Security,我对 Spring Security 的了解很差。如何使用 Spring Security 默认的 JWT 支持? @M.Deinum
-
非常感谢@dur 的帮助!日志可以找到here。我只做了 bootRun 和之后,对 /subscribers 的 POST 请求。
-
@dur 非常感谢!!!!!!!现在它正在工作。 Spring没有进行配置,因为配置包不在
@ComponentScan(basePackages="...")
标签: java spring spring-boot spring-security postman