node.js无法从Spring Boot Security获取用户主体

时间:2016-06-30 23:32:00

标签: node.js spring spring-security spring-boot spring-oauth2

Spring Security正在保护两个独立的Spring Boot后端服务,这些服务在两个独立的jar文件中运行在两个独立的端口上。其中一个服务(称为resource, with full code at this link)响应来自前端Node.js服务器的GET请求,但另一个服务(称为authserver, will full code at this link.)则不响应。 如何更改Spring安全设置,以便authserver应用可以响应来自node.js服务器的请求?

这是来自node.js服务器的express.js代码,它向两个后端服务发出请求:

var url = require('url');
var request = require('request');

// expose the routes to our app with module.exports
module.exports = function(app) {

    // application --------------------------------
    app.get('/resource/**', function(req, res) {
        request.get('http://localhost:9000/resource', function (error, response, body) {
            if(error){console.log('ERROR with resource request.')}
            if (!error){// && response.statusCode == 200) {
                console.log(response.statusCode);
                console.log(body);
            };
        });
        console.log("You Hit The Resource Route ");
    });

    app.get('/user/**', function(req, res) {
        request.get('http://localhost:9999/uaa/user', function (error, response, body) {
            if(error){console.log('ERROR with user request.')}
            if (!error){// && response.statusCode == 200) {
                console.log(response.statusCode);
                console.log(body);
            };
        });
        console.log("You Hit The User Route ");
    });

};

以下是nodemon日志,显示:
1.)对authserver应用程序的/uaa/user端点的调用给出了304响应(Spring Boot authserver应用程序的日志没有显示任何接收请求的证据),以及
2.)resource应用的/resource端点返回401响应(Spring Boot resource应用日志DO显示它已收到请求):

[nodemon] starting `node server.js`
App listening on port 8080
GET /user 304 4.257 ms - -
You Hit The Resource Route 
401
{"error":"unauthorized","error_description":"Full authentication is required to access this resource"}

我确认在Web浏览器中键入http://localhost:9999/uaa/user会触发Spring Boot authserver应用程序来创建记录请求的日志,并在浏览器中提供以下xml:

<oauth>
<error_description>
Full authentication is required to access this resource
</error_description>
<error>unauthorized</error>
</oauth>

1 个答案:

答案 0 :(得分:0)

在AuthserverApplication.java中,您使用.authorizeRequests().anyRequest().authenticated()覆盖了Spring安全性。 这意味着每个请求都要求用户进行身份验证。

尝试在GET / user上更改Spring Security中的权限,以授予对未经身份验证的用户的访问权限(如果您的nodeJs服务器在调用spring服务时未发送Auth令牌/标头/ cookie)

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // @formatter:off
        http
             .formLogin().loginPage("/login").permitAll()
        .and()
            .requestMatchers().antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
        .and()
            .authorizeRequests()
            .antMatchers(HttpMethod.GET, "/user").permitAll()
            .anyRequest().authenticated();
        // @formatter:on
    }