通过外部网页处理请求

Handling requests through an external web Page

我正在使用 MVC .NET6 构建 Web 应用程序。登录(到我的应用程序)后,我需要调用 rest api 但是这个 rest api 使用 Oauth2 所以基本上我的程序调用某个网页属于制作 [=17= 的公司] 我是否需要输入我的身份验证用户名和密码才能获取令牌和 refreshToken。问题是我不知道如何处理该页面上的请求。公司提供了一个使用 axios 和 javascript 工作的示例,但我想使用 .net6 来做,如果有人能告诉我如何使用 c# 来做吗?

非常感谢

通过这个 javascript 使用 axios 服务器的代码,我可以获得令牌并访问其余的 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,
    };

};

您提供的代码只是一个片段。通常OAuth2.0是在.Net Core中实现的,我们会使用identityserver4或者okta来实现。

这部分比较复杂,不能在回答中告诉你具体内容,我给你找了个不错的博客。

IdentityServer4, ASP.NET Core API and a client with username/password