Spring Security在使用RequestParam时不断要求登录

huangapple go评论109阅读模式
英文:

Spring Security keeps asking for login when using RequestParam

问题

这是配置代码部分:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().configurationSource(corsConfigurationSource()).and().csrf()
            .disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}

这是第一个控制器:

@GetMapping(path = "/testOFWork")
public AuthBean test() {
    System.out.println("worked");
    return new AuthBean("You are authenticated already");
}

这是第二个控制器:

@GetMapping(path = "/getUserInfo")
public User getInfo(@RequestParam(value = "username") String user) {
    return dao.getByUserName(user);
}

这是完整的配置类:

@Autowired
UserDetailsService userDetailsService;

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().configurationSource(corsConfigurationSource()).and().csrf()
            .disable()
            .authorizeRequests()
            .antMatchers(HttpMethod.OPTIONS, "/**")
            .permitAll()
            .anyRequest()
            .authenticated()
            .and()
            .httpBasic();
}

CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
    List<String> allowOrigins = Arrays.asList("*");
    configuration.setAllowedOrigins(allowOrigins);
    configuration.setAllowedMethods(singletonList("*"));
    configuration.setAllowedHeaders(singletonList("*"));
    //in case authentication is enabled this flag MUST be set, otherwise CORS requests will fail
    configuration.setAllowCredentials(true);
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

@Autowired
public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
    auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
}

如果还有其他需要的翻译,请告诉我。

英文:

I'm trying to build a backend part of my app and I want to use rest controllers and secure them with spring security.
This is the config:

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource()).and().csrf().
                disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, &quot;/**&quot;)
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }

I also have two controllers:

@GetMapping(path = &quot;/testOFWork&quot;)
    public AuthBean test() {
        System.out.println(&quot;worked&quot;);
        return new AuthBean(&quot;You are authenticated already&quot;);
    }

@GetMapping(path = &quot;/getUserInfo&quot;)
    public User getInfo(@RequestParam(value = &quot;username&quot;) String user) {
        return dao.getByUserName(user);
    }

The first one is working perfectly. When I try to reach it: spring asks me to log in. I do it and it shows me a message.
But when I'm trying to get to the second one it just keeps asking me for a login. And if I try to go to the first one, which worked perfectly fine it asks me to login again.
Experimentally I've figured out that RequestParam causes this problem.
I understand that the problem may be in the configuration itself, but I can't get It.

Thanks for the response in advance!"

EDIT
Here is full config class:

@Autowired
    UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().configurationSource(corsConfigurationSource()).and().csrf().
                disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS, &quot;/**&quot;)
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .httpBasic();
    }


    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        List&lt;String&gt; allowOrigins = Arrays.asList(&quot;*&quot;);
        configuration.setAllowedOrigins(allowOrigins);
        configuration.setAllowedMethods(singletonList(&quot;*&quot;));
        configuration.setAllowedHeaders(singletonList(&quot;*&quot;));
        //in case authentication is enabled this flag MUST be set, otherwise CORS requests will fail
        configuration.setAllowCredentials(true);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration(&quot;/**&quot;, configuration);
        return source;
    }

    @Autowired
    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }

答案1

得分: 1

你正在告诉你的 Spring Security,在任何请求中检查用户是否已通过身份验证,使用以下代码段:

EDIT

你的代码应该如下所示:

http.authorizeRequests()
    .antMatchers("/securityNone").permitAll()
    .anyRequest().authenticated()
    .and()
    .httpBasic()
    .authenticationEntryPoint(authenticationEntryPoint);

http.addFilterAfter(new CustomFilter(),
    BasicAuthenticationFilter.class);

你需要将未受保护的访问与受保护的访问分开。

英文:

You are telling to your spring security to check if user is authenticated for any request in .antMatchers(HttpMethod.OPTIONS, "/**").

EDIT

Your code should look like this:

 http.authorizeRequests()
          .antMatchers(&quot;/securityNone&quot;).permitAll()
          .anyRequest().authenticated()
          .and()
          .httpBasic()
          .authenticationEntryPoint(authenticationEntryPoint);
 
        http.addFilterAfter(new CustomFilter(),
          BasicAuthenticationFilter.class);

You need to separate the not secured access from the secured one

huangapple
  • 本文由 发表于 2020年4月9日 00:49:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61105814.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定