我正在使用 MVC .NET6 構建一個 Web 應用程式。登錄(到我的應用程式)后,我需要呼叫一個休息 api,但這個休息 api 使用的是 Oauth2,所以基本上我的程式呼叫某個網頁屬于制作 api 的公司,如果我需要輸入我的身份驗證用戶名和密碼能夠獲取token和refreshToken。問題是我不知道如何處理該頁面上的請求。該公司提供了一個使用 axios 和 javascript 作業的示例,但如果有人能告訴我如何使用 c# 來做,我想使用 .net6 來做?
非常感謝您
通過使用 axios 服務器的這個 javascript 代碼,我可以獲得令牌并訪問其余的 api,但我需要使用 c#/.net6 來完成,所以請幫忙
const server = http.createServer(handleRequest);
server.listen(config.port, () => {
console.log('Server listening on: ``http://localhost``:%s', config.port);
});
const handleRequest = async (request, response) => {
const requestUrl = url.parse(request.url);
if (requestUrl.pathname !== '/oauth') {
response.end();
return;
}
const queryParameter = querystring.parse(requestUrl.query);
const authorizationCode = queryParameter.code;
const receivedState = queryParameter.state;
if (receivedState !== sessionState) {
console.log('State in the callback does not match the state in the original request.');
response.end();
return;
}
// Get access token
console.log('Getting tokens...');
const tokens = await retrieveTokens(authorizationCode);
console.log('Received new tokens: \n', tokens);
// Get user information
console.log('Getting user information...');
const userInformation = await userInfo(tokens.accessToken);
console.log(userInformation);
// Refresh tokens
console.log('Refreshing tokens...');
const refreshedTokens = await refreshTokens(tokens.refreshToken);
console.log('Received new tokens: \n', tokens);
// Get user information using the refreshed accessToken
console.log('Getting user information...');
const userInformationWithRefreshedToken = await userInfo(refreshedTokens.accessToken);
console.log(userInformationWithRefreshedToken);
response.end();
};
const retrieveTokens = async authorizationCode => {
const requestBody = {
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: config.redirectUri,
code: authorizationCode,
grant_type: 'authorization_code',
};
const response = await axios.post(config.tokenUrl, querystring.stringify(requestBody), {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
});
return {
accessToken: response.data.access_token,
refreshToken: response.data.refresh_token,
};
};
uj5u.com熱心網友回復:
您提供的代碼只是一個片段。通常OAuth2.0在.Net Core中實作,我們會使用identityserver4或者okta來實作。
這部分很復雜,我們無法在答案中告訴你具體內容,我為你找到了一個不錯的博客。
IdentityServer4、ASP.NET Core API 和帶有用戶名/密碼的客戶端
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/452683.html
