簡體   English   中英

如何為未經授權的用戶配置Spring Security + oAuth2

[英]How to configure Spring security + oAuth2 for unauthorized users

我有我的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(未授權)的spring控制器。

灰燼請求代碼:

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?

我剛剛為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();
  }
 }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM