【发布时间】:2018-04-04 14:30:05
【问题描述】:
我的应用程序中有以下端点模式
- /token -- 所有人都可以访问
- /rest/securedone/** -- 需要身份验证
- /rest/securedtwo/** -- 需要身份验证
- /rest/unsecured/** -- 不需要身份验证
到目前为止,我可以访问 /token 端点。 但是 /rest/securedone/** 和 /rest/unsecured/** 在未发送令牌(JWT)时返回 401。我的意图是保护 /rest/securedone/**,这很好 /rest/unsecured/** 应该可以访问。
我的 httpSecurity 配置如下:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf().disable()
.authorizeRequests()
.antMatchers("/token").permitAll()
.antMatchers("/rest/secured/**").authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.addFilterBefore(authenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
我的 AbstractAuthenticationProcessingFilter 扩展类如下:
public class MyAuthenticationTokenFilter extends AbstractAuthenticationProcessingFilter {
private static Logger log = LoggerFactory.getLogger(MyAuthenticationTokenFilter.class);
public MyAuthenticationTokenFilter() { super("/rest/**"); }
@Override
public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, ServletException {
//authentication handling code
}
@Override
protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException, ServletException {
super.successfulAuthentication(request, response, chain, authResult);
chain.doFilter(request, response);
}
}
谁能帮我弄清楚以下问题:
-
什么时候使用 MyAuthenticationTokenFilter?将调用哪个 URL?怎么
/rest/unsecured/**也期待认证?即使我明确地说.antMatchers("/rest/secured/**").permitAll(),它也会发生。 -
我可以在
MyAuthenticationTokenFilter构造函数中的super(defaultFilterProcessingUrl)调用中指定多个url 模式吗?例如,如果我有另一个 url,例如/api/secured/**,我怎样才能让我的MyAuthenticationTokenFilter被/api/secured/**请求调用?我不需要不同的身份验证处理,所以我想重用这个过滤器。
【问题讨论】:
标签: spring rest authentication spring-boot spring-security