【问题标题】:How to configure Spring security + oAuth2 for unauthorized users如何为未经授权的用户配置 Spring security + oAuth2
【发布时间】:2019-05-29 15:41:19
【问题描述】:

我有我的 Spring 后端配置

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

@Autowired
MongoDBAuthenticationProviderService authenticationProvider;

@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
}

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http
            .authorizeRequests()
            .antMatchers("/loadingObjectController/**").permitAll()
            .anyRequest().authenticated();

    http
            .formLogin().permitAll().loginPage("/login").usernameParameter("username").passwordParameter("password")
            .and()
            .logout().permitAll()
            .and()
            .exceptionHandling().accessDeniedPage("/403");
   }
}

@Configuration
@EnableAuthorizationServer
public class AuthenticationConfig extends AuthorizationServerConfigurerAdapter {

@Value("${oauth.client-id}")                     private String client_id;
@Value("${oauth.client-secret}")                 private String client_secret;
@Value("${oauth.authorized-grant-types}")        private String grant_types;
@Value("${oauth.access-token-validity-seconds}") private Integer validity_seconds;
@Value("${oauth.scope}")                         private String scope;

@Autowired
private AuthenticationManager auth;

@Bean
public TokenStore tokenStore() {
    return new InMemoryTokenStore();
}

@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints)throws Exception {
    endpoints
            .authenticationManager(auth).tokenStore(tokenStore())
            .allowedTokenEndpointRequestMethods(HttpMethod.POST, HttpMethod.GET, HttpMethod.OPTIONS);
}

@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
    oauthServer

            .checkTokenAccess("permitAll()")   
            .allowFormAuthenticationForClients();
 }

@Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
    clients.inMemory()
            .withClient(client_id)
            .secret(client_secret)
            .authorizedGrantTypes(grant_types.split(","))
            .accessTokenValiditySeconds(validity_seconds)
            .scopes(scope.split(",")).autoApprove(true);
}
}

我有带有登录表单和索引页面的 Ember.js 前端。 身份验证工作正常。 但后来我尝试将 GET 请求从索引页面发送到 spring 控制器我有 401(未经授权)。

Ember 请求代码:

actions: {
    sendReq() {
        $.ajax({
            url: 'http://192.168.13.108:8080/getCoordinates?bbox=%b&zoom=%z&filter=',
            success: console.log("Ok")
        });
    }
}

还有我的 Spring 控制器:

@RestController
@RequestMapping("/loadingObjectController")
public class LoadingObjectController {

@Autowired
private CoordinatesRepository coordinatesRepository;

@ResponseBody
@RequestMapping(value = "/getCoordinates", method = RequestMethod.GET)
public MappingJacksonValue getCoordinates(@RequestParam(value = "bbox") String bbox, @RequestParam(value = "callback") String callback,
                                          @RequestParam(value = "zoom") byte zoom, @RequestParam(value = "filter") String filterRequest) {

    System.out.println("bbox = " + bbox);
    System.out.println("zoom = " + zoom);
    System.out.println("filterRequest = " + filterRequest);
    Map responseObject = new HashMap<>();
    MappingJacksonValue mappingJacksonValue = new MappingJacksonValue(responseObject);
    mappingJacksonValue.setJsonpFunction(callback);

    return mappingJacksonValue;
}

如何配置向他发出请求的 Spring Security?

【问题讨论】:

    标签: java spring-security oauth-2.0


    【解决方案1】:

    我刚刚为 Resource 添加了新配置,并添加了匿名权限。

    @Configuration
    @EnableWebSecurity
    @EnableGlobalMethodSecurity(prePostEnabled = true)
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
    
    @Autowired
    MongoDBAuthenticationProviderService authenticationProvider;
    
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
    auth.authenticationProvider(authenticationProvider);
    }
    
    @Override
    protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    
    http
            .anonymous()
            .and()
            .authorizeRequests().antMatchers("/loadingObjects").permitAll()
            .and()
            .formLogin().permitAll().loginPage("/login").usernameParameter("username").passwordParameter("password")
            .and()
            .logout().permitAll()
            .and()
            .authorizeRequests().anyRequest().fullyAuthenticated()
            .and()
            .httpBasic().disable()
            .exceptionHandling().accessDeniedPage("/403")
            .and()
            .headers()
            .contentTypeOptions()
            .disable();
     }
    } 
    

    @EnableResourceServer
    @Configuration
    public class ResourseConfig extends ResourceServerConfigurerAdapter {
    
    @Override
    public void configure(HttpSecurity http) throws Exception {
    
    http
            .anonymous()   
            .and()
            .authorizeRequests().antMatchers("/loadingObjects/**").permitAll()
            .and()
            .formLogin().permitAll().loginPage("/login").usernameParameter("username").passwordParameter("password")
            .and()
            .logout().permitAll()
            .and()
            .authorizeRequests().anyRequest().fullyAuthenticated() 
            .and()
            .httpBasic().disable()
            .exceptionHandling().accessDeniedPage("/403")
            .and()
            .headers().contentTypeOptions()
            .disable();
      }
     }
    

    【讨论】:

      猜你喜欢
      • 2019-08-09
      • 2013-05-18
      • 2020-05-01
      • 2013-02-13
      • 2015-10-21
      • 1970-01-01
      • 2018-04-27
      • 2020-05-11
      • 2014-05-10
      相关资源
      最近更新 更多