代码之家  ›  专栏  ›  技术社区  ›  Chloe

如何在春季引导中更改OAuth2的过滤级别?

  •  0
  • Chloe  · 技术社区  · 6 年前

    我设置了一个应用程序来使用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
    

    与整体 @豆 评论过,然后呢 工作。世界跆拳道联盟?!

    $ 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 回复  |  直到 6 年前
        1
  •  0
  •   Chloe    6 年前

    我扔掉了 @EnableWebSecurity WebSecurityConfigurerAdapter 这完全破坏了应用程序。我以为他们需要进入 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();   
        }