首页 > 解决方案 > 在 Spring-security-oauth2 密码模式下,用户名和密码已被视为匿名

问题描述

我正在使用 Spring Boot 和 Spring Security OAuth2 向前端发出令牌。

Postman
当我使用 postman 进行测试时,一切正常。

使用邮递员获取access_token.

浏览器
但是当我使用 vue.js 和 axios 在浏览器上发送相同的请求时,它没有按预期工作。状态码是 401。

Gerneral:
Request URL: http://localhost:8080/oauth/token
Request Method: POST
Status Code: 401 
Remote Address: [::1]:8080
Referrer Policy: no-referrer-when-downgrade

Response Headers:
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: http://localhost:8081
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: application/json;charset=UTF-8
Date: Sun, 17 Mar 2019 02:20:54 GMT
Expires: 0
Pragma: no-cache
Transfer-Encoding: chunked
Vary: Origin, Access-Control-Request-Method, Access-Control-Request-Headers
WWW-Authenticate: Basic realm="oauth2/client"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

Request Headers:
Provisional headers are shown
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
Origin: http://localhost:8081
Referer: http://localhost:8081/login
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36
Form Data:
{"grant_type":"password","scope":"all","username":"admin","password":"888","client_id":"wellcell","client_secret":"wellcell"}: 

服务器控制台日志的差异
我并排制作了一张图片:

比较

左侧是邮递员请求的服务器控制台日志。浏览器请求的服务器控制台日志在右侧。

在“ClientCredentialsTokenEndpointFilter”之后,邮递员请求到“DaoAuthenticationProvider”进行身份验证。但是浏览器请求转到“BasicAuthencationFilter”,“用户名”和“密码”被忽略,并返回了一个匿名用户。然后,匿名用户拒绝访问。

以前有人遇到过这种问题吗?

标签: spring-bootvue.jsaxiospostmanspring-security-oauth2

解决方案


我认为有问题Content-Type: application/x-www-form-urlencoded。如果发送 json,则需要使用Content-Type: application/json. 简单使用 axios 和 post 的 json:

axios.post("http://localhost:8080/oauth/token", { 
  "grant_type": "password",
  "scope": "all",
  "username": "admin",
  "password": "888",
  "client_id": "wellcell",
  "client_secret": "wellcell"
}).then((response) => {
  console.log(response.data);
});

推荐阅读