如何在Spring Boot中更改OAuth2的过滤器级别?

时间:2018-05-23 22:13:57

标签: java spring spring-boot spring-security oauth-2.0

我设置了一个使用OAuth2的应用,但现在它会过滤每个请求,例如

$ curl  http://localhost:8080/robots.txt
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

不仅仅是我想要的。如何为某些路径指定安全筛选?我按了this guide阅读了this guide too

我尝试过以下操作,其中似乎适用于非OAuth2路径,但它会导致OAuth2路径出错!

@Configuration
class WebSecurityConfiguration {

    @Autowired
    UserMapper userMapper;

    @Bean
    PasswordEncoder passwordEncoder() {
//      return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Bean
    UserDetailsService userDetailsService() {
        return new UserDetailsService() {
            @Override
            public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
                User myU = userMapper.getUser(username);
                if (myU == null) throw new UsernameNotFoundException("Could not find the user '"+username+"'");
                UserDetails springU = org.springframework.security.core.userdetails.User
                        .withUsername(myU.name)
                        .password(myU.password)
                        .authorities("USER", "write")
                        .build();
                return springU;
                // Java 8
//              return (username) -> accountRepository
//                      .findByUsername(username)
//                      .map(a -> User.builder()
//                          .username(a.getUsername())
//                          .password(a.getPassword())
//                          .authorities("USER", "write")
//                          .build())
//                      .orElseThrow(
//                          () -> new UsernameNotFoundException("could not find the user '"
//                              + username + "'"));         
            }
        };
    }

    @Bean
    WebSecurityConfigurerAdapter webSecurityConfigurerAdapter() {
        return new WebSecurityConfigurerAdapter() {
            @Override
            public void configure(HttpSecurity http) throws Exception {
//              http.antMatcher("/flights/**").authorizeRequests().anyRequest().authenticated();
//              http.antMatcher("/robots.txt").anonymous();
                http
                    .authorizeRequests()
                    .antMatchers("/robots.txt", "/error", "/login", "/doLogut", "/home", "/pageNotFound", 
                            "/errorNonSamsung", "/snsandroidgear", "/snstheme", "/errorDesktop", "/*", "/getUrls",
                            "/css/**", "/js/**", "/fonts/**", "/img/**", 
                            "/dologin", "/form", "/addImage", "/addThemeImage", "/exportUniqueToexcel", "/exporttoexcel",
                            "/delete", "/activateDeactivate").permitAll().and()
//                  .authorizeRequests().antMatchers("/login", "/robots.txt").permitAll().and()
                    // default protection for all resources (including /oauth/authorize)
                    .authorizeRequests()
                    .anyRequest().hasRole("USER")
//                  .authorizeRequests()
////                    .anyRequest().permitAll()
//                  .antMatchers("/isTagAvailable").authenticated()
////                    .antMatchers("/robots.txt", "/error", "/login", "/doLogut", "/home", "/pageNotFound", 
////                            "/errorNonSamsung", "/snsandroidgear", "/snstheme", "/errorDesktop", "/*", "/getUrls",
////                            "/css/**", "/js/**", "/fonts/**", "/img/**", 
////                            "/dologin", "/form", "/addImage", "/addThemeImage", "/exportUniqueToexcel", "/exporttoexcel",
////                            "/delete", "/activateDeactivate").permitAll()
////                    .anyRequest().authenticated()
////                    .and().formLogin()
                    .and().httpBasic().disable();
            }           
        };

    }


}

访问令牌和允许的路径有效,但受OAuth2保护的路径无效。虽然它没有@Bean WebSecurityConfigurerAdapter

$ curl  http://localhost:8080/robots.txt
User-agent: *
Disallow: /

$ curl -u xxxxxxx:xxxxxxx http://localhost:8080/oauth/token -d grant_type=password -d username=xxxxx -d password=xxxx -d client_id=xxxxxxx -d client_secret=xxxxxxx -d scope=write
{"access_token":"f90b4bdf-a380-40d6-a6a7-5be28bd3ce99","token_type":"bearer","refresh_token":"cf507647-9f74-4ed7-a23e-92acac9ec257","expires_in":43199,"scope":"write"}

$ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer f90b4bdf-a380-40d6-a6a7-5be28bd3ce99" -d '{"apiKey": "xxxxxxxx", "tag": "xxx"}' localhost:8080/isTagAvailable
This is not a valid request

对整个@Bean发表评论,然后 工作。 WTF?!

$ curl -X POST -H "Content-Type: application/json" -H "Authorization: Bearer 7cf2bf7a-249f-45c2-95d9-a36d508b743a" -d '{"apiKey": "samsung", "tag": "cnn"}' localhost:8080/isTagAvailable
{"message":"CustomTag is not available","tagAvailable":false}

1 个答案:

答案 0 :(得分:0)

我扔掉了@EnableWebSecurityWebSecurityConfigurerAdapter,这完全打破了应用。我以为他们需要访问我认为我需要的HttpSecurity。我发现这个简单的新类将解决问题。您只需将不想要OAuth2的路径放在数组中,然后就可以保护其他所有路径。

@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    String[] ignoredPaths = new String[]{...};

    @Override
    public void configure(HttpSecurity http) throws Exception{

        http.authorizeRequests()
            .antMatchers(ignoredPaths).permitAll()
            .anyRequest().authenticated()
        .and()
            .httpBasic();   
    }