我正在编写一个应用程序,我试图在其中配置不同端点的可见性。我写了以下代码:@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(如果用户没有登录,afaik 应该重定向到登录页面)。之后我重新启动它,也许在其他地方做了一些小的改动,这似乎完全无关紧要,我的网站又可以工作了。你们中有人遇到过这类问题吗?它的原因是什么?我在配置中做错了吗?
1 回答
![?](http://img1.sycdn.imooc.com/533e4c5600017c5b02010200-100-100.jpg)
ABOUTYOU
TA贡献1812条经验 获得超5个赞
这里突出的三件事
您有一个自定义入口点,并且感知是入口点发送 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
添加回答
举报
0/150
提交
取消