我正在编写一个应用程序,在其中尝试配置不同端点的可见性。
我编写了以下代码:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.cors().and().csrf().disable().authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.antMatchers(HttpMethod.POST, "/login").permitAll()
.antMatchers(HttpMethod.GET, "/login").permitAll()
.antMatchers(HttpMethod.GET, "/").authenticated()
.antMatchers(HttpMethod.GET, UPVOTE_URL).authenticated()
.antMatchers(HttpMethod.GET, DOWNVOTE_URL).authenticated()
.antMatchers(HttpMethod.POST, LOG_OUT_URL).authenticated()
.antMatchers(HttpMethod.DELETE, DELETE_URL).authenticated()
.antMatchers(HttpMethod.POST, ADD_URL).authenticated()
.anyRequest().authenticated()
.and()
.addFilter(new JWTAuthenticationFilter(authenticationManager()))
.addFilter(new JWTAuthorizationFilter(authenticationManager()))
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.logout()
.and()
.exceptionHandling()
.authenticationEntryPoint(new Http401AuthenticationEntryPoint("No authorization"));
我的程序的行为很奇怪,因为当我尝试到达“/login”或“/”端点时,程序有时会返回 401(如果用户尚未签名,那么应该重定向到登录页面)中)。
之后我重新启动它,也许在其他地方进行了一些看似完全无关的细微更改,然后我的网站再次运行了。
大家有遇到过这样的问题吗?其原因何在?我在配置中做错了什么吗?
最佳答案
这里突出的三件事
您有一个自定义入口点,并且感觉该入口点发送 401,而不是重定向到/login
您没有
formLogin()
,因此处理登录页面的过滤器未运行我们不知道您的过滤器的用途和时间
说到配置,我们先开始
http
.cors()
.and()
.csrf()
.disable()
.authorizeRequests()
.antMatchers(HttpMethod.POST, SIGN_UP_URL).permitAll()
.antMatchers("/login").permitAll()
.antMatchers(HttpMethod.GET, "/").authenticated()
.antMatchers(HttpMethod.GET, UPVOTE_URL).authenticated()
.antMatchers(HttpMethod.GET, DOWNVOTE_URL).authenticated()
.antMatchers(HttpMethod.POST, LOG_OUT_URL).authenticated()
.antMatchers(HttpMethod.DELETE, DELETE_URL).authenticated()
.antMatchers(HttpMethod.POST, ADD_URL).authenticated()
.anyRequest().authenticated()
.and()
.addFilterBefore(new JWTAuthenticationFilter(authenticationManager()), HeaderWriterFilter.class)
.addFilterAfter(new JWTAuthorizationFilter(authenticationManager()), JWTAuthenticationFilter.class)
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.formLogin()
.and()
.logout()
;
那么我们改变了什么,
删除身份验证入口点并将 JWT 过滤器移到前面。 如果这些过滤器触发(并且它们不应该为非 REST 端点触发,因此您必须编写该逻辑),那么系统要么经过身份验证,要么过滤器本身返回 401 并且不会抛出异常。也许您可以让我们知道这些过滤器是否确实起到了正确的作用?
如果 JWT 过滤器不执行任何操作,则其他所有内容都会发挥作用。所以我们在 formLogin() 中添加了所有默认配置。如果由于请求在应该进行身份验证时未经过身份验证而调用身份验证入口点,则会重定向到/login
关于java - 不同的端点看似随机地获得授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54245786/