spring security + oauth2 + reactjs + restful http客户端

Posted

技术标签:

【中文标题】spring security + oauth2 + reactjs + restful http客户端【英文标题】:spring security + oauth2 + reactjs + restful http client 【发布时间】:2017-09-17 09:58:41 【问题描述】:

我正在使用 auth2 身份验证和 reactjs 进行 spring boot 1.5+ 安全性。用于使用 restful http 客户端的 http 调用。身份验证工作正常,我成功地从资源服务器访问数据。问题是注销代码不起作用,我在控制台上收到此错误:

发布http://localhost:8080/logout403 ()

错误:“禁止” 消息:“在请求参数 '_csrf' 或标头 'X-XSRF-TOKEN' 上发现无效的 CSRF 令牌 'null'。

我也在分享我的代码。

1) ReactJs 代码

  handleLogout = (e) => 
    client(
            method: 'POST',
            path: '/logout',
            headers: 
              'Accept': 'application/json',
              'Content-Type': 'application/json'
            ).then(response => 
              console.log(response);
    );
  

2) 宁静的http客户端

'use strict';

// client is custom code that configures rest.js to include support for HAL, URI Templates,
// and other things. It also sets the default Accept request header to application/hal+json.

// get the rest client
var rest = require('rest');

// provides default values for the request object. default values can be provided for the method, path, params, headers, entity
// If the value does not exist in the request already than the default value utilized
var defaultRequest = require('rest/interceptor/defaultRequest');

// Converts request and response entities using MIME converter registry
// Converters are looked up by the Content-Type header value. Content types without a converter default to plain text.
var mime = require('rest/interceptor/mime');

// define the request URI by expanding the path as a URI template
var uriTemplateInterceptor = require('./uriTemplateInterceptor');

// Marks the response as an error based on the status code
// The errorCode interceptor will mark a request in error if the status code is equal or greater than the configured value.
var errorCode = require('rest/interceptor/errorCode');
var csrf = require('rest/interceptor/csrf');
// A registry of converters for MIME types is provided. Each time a request or response entity needs to be encoded or
// decoded, the 'Content-Type' is used to lookup a converter from the registry.
// The converter is then used to serialize/deserialize the entity across the wire.
var baseRegistry = require('rest/mime/registry');
var registry = baseRegistry.child();
registry.register('text/uri-list', require('./uriListConverter'));
registry.register('application/hal+json', require('rest/mime/type/application/hal'));

// wrap all the above interceptors in rest client
// default interceptor provide Accept header value 'application/hal+json' if there is not accept header in request
module.exports = rest
        .wrap(mime,  registry: registry )
        .wrap(uriTemplateInterceptor)
        .wrap(errorCode)
        .wrap(csrf)
        .wrap(defaultRequest,  headers:  'Accept': 'application/hal+json' );

3) 客户端应用的application.yml

debug: true

spring:
  aop:
    proxy-target-class: true


security:
  user:
    password: none
  oauth2:
    client:
      access-token-uri: http://localhost:9999/uaa/oauth/token
      user-authorization-uri: http://localhost:9999/uaa/oauth/authorize
      client-id: acme
      client-secret: acmesecret
    resource:
      user-info-uri: http://localhost:9999/uaa/user
      jwt:
        key-value: |
          -----BEGIN PUBLIC KEY-----
          MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgnBn+WU3i6KarB6gYlg40ckBiWmtVEpYkggvHxow74T19oDyO2VRqyY9oaJ/cvnlsZgTOYAUjTECjL8Ww7F7NJZpxMPFviqbx/ZeIEoOvd7DOqK3P5RBtLsV5A8tjtfqYw/Th4YEmzY/XkxjHH+KMyhmkPO+/tp3eGmcMDJgH+LwA6yhDgCI4ztLqJYY73gX0pEDTPwVmo6g1+MW8x6Ctry3AWBZyULGt+I82xv+snqEriF4uzO6CP2ixPCnMfF1k4dqnRZ/V98hnSLclfMkchEnfKYg1CWgD+oCJo+kBuCiMqmeQBFFw908OyFKxL7Yw0KEkkySxpa4Ndu978yxEwIDAQAB
          -----END PUBLIC KEY-----

zuul:
  routes:
    resource:
      path: /resource/**
      url: http://localhost:9000/resource
    user:
      path: /user/**
      url: http://localhost:9999/uaa/user

logging:
  level:
    org.springframework.security: DEBUG

4) 授权服务器中的 CorsFilter 配置

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter 

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) 

        System.out.println("*********** running doFilter method of CorsFilter of auth-server***********");
        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
        response.addHeader("Access-Control-Allow-Headers", "x-auth-token, x-requested-with");
        response.addHeader("Access-Control-Max-Age", "3600");

        if (request.getMethod()!="OPTIONS") 
            try 
                chain.doFilter(req, res);
             catch (IOException e) 
                e.printStackTrace();
             catch (ServletException e) 
                e.printStackTrace();
            
         else 
        
    

    public void init(FilterConfig filterConfig) 

    public void destroy() 


5) 认证服务器的AuthororizationServerConfigurerAdapter

@Configuration
@EnableAuthorizationServer
public class OAuth2AuthorizationConfig extends AuthorizationServerConfigurerAdapter 

    @Autowired
    private AuthenticationManager authenticationManager;

    @Bean
    public @Autowired JwtAccessTokenConverter jwtAccessTokenConverter() throws Exception 

        System.out.println("*********** running jwtAccessTokenConverter ***********");

        // Setting up a JWT token using JwtAccessTokenConverter.
        JwtAccessTokenConverter converter = new JwtAccessTokenConverter();
        // JWT token signing key
        KeyPair keyPair = new KeyStoreKeyFactory(
                new ClassPathResource("keystore.jks"), "suleman123".toCharArray())
                .getKeyPair("resourcekey");
        converter.setKeyPair(keyPair);
        return converter;
    


    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception 

        System.out.println("*********** running configure(ClientDetailsServiceConfigurer clients)  ***********");

        clients.inMemory()
                .withClient("acme") // registers a client with client Id 'acme'
                .secret("acmesecret") // registers a client with password 'acmesecret'
                .authorizedGrantTypes("authorization_code", "refresh_token",
                        "password") // We registered the client and authorized the “password“, “authorization_code” and “refresh_token” grant types
                .scopes("openid") // scope to which the client is limited
                .autoApprove(true);
    

    /**
     *  
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints)
            throws Exception 

        System.out.println("*********** running configure(AuthorizationServerEndpointsConfigurer endpoints)  ***********");

        // we choose to inject an existing authentication manager from the spring container
        // With this step we can share the authentication manager with the Basic authentication filter
        endpoints.authenticationManager(authenticationManager)
                .accessTokenConverter(jwtAccessTokenConverter());
    

    @Override
    public void configure(AuthorizationServerSecurityConfigurer oauthServer)
            throws Exception 

        System.out.println("*********** running configure(AuthorizationServerSecurityConfigurer oauthServer)  ***********");

        oauthServer.tokenKeyAccess("permitAll()").checkTokenAccess(
                "isAuthenticated()");
    

【问题讨论】:

现在我正在使用 react-cookie 库从 cookie 中获取 Csrf-Token 并在 restful http 客户端中作为 X-Csrf-Token 标头传递。上述错误已经消失,但这次我在控制台上遇到了一些不同的错误。错误是:跨域请求被阻止:同源策略不允许读取localhost:9999/uaa/oauth/… 的远程资源。 (原因:CORS 预检通道未成功)。 这是我当前的restful http客户端注销代码:client( method: 'POST', path: 'logout', headers: 'Accept': 'application/json', 'Content-Type ': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'X-Csrf-Token': Cookie.load('XSRF-TOKEN') ).then(response => console.日志(响应);); 【参考方案1】:

终于搞定了。我为使它工作所做的工作:

1) 我已经安装了“react-cookie”库

npm install react-cookie --save

2) 在我的 reactjs 代码中,我导入了 react-cookie 库,并且在使用 restful http 客户端生成注销请求的方法中,我从 cookie 中获取 Csrf-Token 并将其作为请求标头发送。

  handleLogout = (e) => 

    client(
            method: 'POST',
            path: 'logout',
            headers: 
              'Content-Type': 'application/x-www-form-urlencoded;charset=utf8',
              'X-Requested-With': 'XMLHttpRequest',
              'X-Csrf-Token': Cookie.load('XSRF-TOKEN')
            
          ).then(response => 
              this.setState(authenticated: false);
              console.log(response);
    );
  

3) 在授权服务器中,而不是使用我在问题中提到的自定义 Cors 过滤器类,现在我使用 Spring Cors 过滤器代码

@Configuration
public class CorsFilterConfig 

    @Bean
    public FilterRegistrationBean corsFilter() 
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        bean.setOrder(0);
        return bean;
    

4) 我在 Authorization Server 的 application.properties 文件中添加了这个属性,所以 CorsFilter 将在 SpringSecurityFilterChain 之前运行

security.filter-order=50

【讨论】:

以上是关于spring security + oauth2 + reactjs + restful http客户端的主要内容,如果未能解决你的问题,请参考以下文章

Spring-Security OAuth2 设置 - 无法找到 oauth2 命名空间处理程序

Spring Security OAuth2 v5:NoSuchBeanDefinitionException:'org.springframework.security.oauth2.jwt.Jwt

如何使用spring-security,oauth2调整实体的正确登录?

针对授权标头的Spring Security OAuth2 CORS问题

Spring Security---Oauth2详解

OAuth2.0学习(4-1)Spring Security OAuth2.0 - 代码分析