我想在春季啓動應用程序配置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 /用戶」,我得到:
我想有開端點(/用戶)沒有任何安全控制或憑證檢查,對singup和登錄和驗證的用戶安全端點端點。
謝謝! :)
如果我這樣做,它允許我訪問/訂戶,但也允許我訪問安全的REST端點。 @Sobik –
這就是你通過重寫'requireAuthentication'來編寫自己的程序。它現在總是會返回這個。你爲什麼要自己實施JWT支持? Spring Security已經有了一個擴展。 –
我在學習春季安全,我對春季安全的知識很差。如何使用Spring Security默認的JWT支持? @ M.Deinum –