问题
I have implemented the oauth2 server using spring boot and reactjs.
Server side working ok, in first step I want to get token using username and password here is my react login or get
export const dologin = (username, password) => {
let details = {
username: username,
password: password,
grant_type: 'password'
};
let formBody = [];
for (let property in details) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(details[property]);
formBody.push(encodedKey + "=" + encodedValue);
}
return fetch('/oauth/token', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Authorization': 'Basic '+btoa('someclientid:dTHfdd4TRDvcsaSS'),
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
body: formBody.join("&")
}).then(res => {
return res.json();
}).then((data) => {
console.log(data)
}).catch((err) => {
console.log(err);
});
}
However if I send request, I get http auth window alert on the browser even I am accepting json.
'Accept': 'application/json',
Not sure why it is happening?
回答1:
The modal popup is triggered because you are configured a basic authentication when you send this header:
'Authorization': 'Basic...'
Try to use Bearer instead Basic
oauth2 flow
The flow of the application will be the following:
- (1) Your users will start the web application.
- (2) As they were not signed in before, you web app will show them a login screen (a page provided by the authorization server).
- (3) After authenticating, the authorization server will provide your web app a code.
- (4) The web app will issue a request to a token endpoint to exchange this code for an access token and/or an id token.
- (5) After getting back these tokens, the web app can consume the endpoints of your private rest apis sending one of these tokens as header.
- (6) Your private rest apis must validate if token of the web app (header) is valid by sending it to one endpoint of the authorization server
- (7) If token is valid, your api rest is allowed to respond to the web client. For instance a json with information of user, perform an update of customer order details, etc
Here some oauth2 flows
In order to perform the steps (2), (3) and (4) you will need clientId, clientSecret and other sensitive values, so I suggest you, to perform these steps in the backend of your frontend!. I know this sounds crazy but with the next example you will understand:
If you host the build of your react.js app in a simple server like apache http or nginx, this is the backend of your frontend
The disadvantage of these servers is that they are only used to serve the static assets not to perform complex steps.
In this case you can use
- node.js with passport js module. Also check this
- php, ruby, etc
来源:https://stackoverflow.com/questions/54615902/react-js-oauth2-login-using-react-and-spring-boot-shows-auth-window