如何为未经授权的用户配置Spring security + oAuth2

时间:2016-03-25 09:42:48

标签: java spring-security oauth-2.0

我有我的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请求到我有401(未授权)的弹簧控制器。

Ember请求代码:

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

我的Spring Controller:

@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?

1 个答案:

答案 0 :(得分:0)

我刚添加了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();
  }
 }