错误:“禁止”消息:“在请求参数'_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);
});
}
'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' }});
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
@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() {}
}
@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()");
}
}
终于成功了。我为使它发挥作用所做的工作:
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);
});
}
@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;
}
}
security.filter-order=50
但是当我运行我的应用程序“http://localhost/client-sample/product/1”时,它会显示“http://localhost/client-sample/spring_security_login”。但是我希望用户应该重定向到oaut2服务器页面。
我有一个安全的微服务正在调用另一个安全的微服务。这两个服务在KeyCloak中都有服务帐户。我如何配置第一个服务在调用第二个服务时自动从keycloak获得访问令牌?这是一个简单的服务到服务通信。Quarkus Rest客户机是否有API来执行此操作?如果没有,我如何使用Vert.x rest客户端来实现这一点?
我很难找到使用Spring实现OAuth2客户机的示例。 我使用Spring实现了OAuth2授权和资源服务器。我想从授权服务器获取访问令牌。我需要一个示例,如何从我的OAuth2服务器只使用客户端凭据获取访问令牌。不涉及用户,只是我的客户端应用程序使用客户端凭据获取访问令牌,然后使用它访问客户端资源。 我只找到了使用Java库示例,但我假设Spring的OAuth2框架中支持Java库。 如果可
顺便说一句,这些微服务只会通过中间件层互相交谈,我的意思是不需要用户凭据来允许授权(用户登录过程如Facebook)。 我在Internet上寻找了一些示例,展示了如何创建一个授权和资源服务器来管理这种通信。然而,我只是找到了一些例子,解释了如何使用用户凭据(三条腿)来实现它。 有没有人有在Spring Boot和Oauth2中如何做的样例?如果有可能提供更多关于所用范围的详细信息,令牌交换将不胜
我正在使用Spring构建Web应用程序。我有多个Spring客户端应用程序和一个OAuth2授权和资源服务器。最终用户首先在客户端应用内进行身份验证,然后客户端应用从资源服务器请求一些资源(从授权服务器获得访问令牌后),处理数据并将其返回给用户。用户也可以更改资源服务器上的数据,但只能通过客户端应用。对于仅使用客户端凭证的资源获取,在这种情况下资源所有者是可信客户端。 在资源服务器上,仅存储客户
我有一个单页应用程序,前端部分使用ReactJS和MobX构建,后端部分使用ruby-on-rails构建。我有一个图像放置区域容器,我希望用户能够上载图像,但所有上载实现都要在前端完成,后端只会收到上载图像的URL。有没有可能在根本不涉及服务器的情况下使用ReactJS实现这一点?