简体   繁体   English

静默获取微软 accessToken

[英]Get Microsoft accessToken silently

I'm trying to connect to Graph API and get user access token.我正在尝试连接到 Graph API 并获取用户访问令牌。

My problem is that I don't know how to connect to Graph API with credentials silently (without browser).我的问题是我不知道如何使用凭据静默连接到 Graph API(没有浏览器)。

I currently use MSLogin() for get access token but it open a browser where you can authorize an AzureAD app to get some access to your account.我目前使用MSLogin()获取访问令牌,但它会打开一个浏览器,您可以在其中授权 AzureAD 应用程序访问您的帐户。 A library in Java is litteraly what I want in c# https://github.com/Litarvan/OpenAuth Java 中的库几乎是我想要的 c# https://github.com/Litarvan/OpenAuth

I need something like: MSGraph.ConnectAsync(email, pass).getAccessToken();我需要类似的东西: MSGraph.ConnectAsync(email, pass).getAccessToken();

Here my current code (Through a browser)这是我当前的代码(通过浏览器)

private const string ClientId = "520f6e8e-xxxxxxxxxxxxxxxxxxxx";
private string[] scopes = { "https://graph.microsoft.com/user.read" };

private static AuthenticationResult authResult;
public static IPublicClientApplication PublicClientApp;

private async Task<AuthenticationResult> MSLogin()
{
    PublicClientApp = PublicClientApplicationBuilder.Create(ClientId).WithRedirectUri("msal520f6e8e-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx://auth").Build();
    authResult = await PublicClientApp.AcquireTokenInteractive(scopes).ExecuteAsync();
    return authResult;
}

If you are using Microsoft Graph .NET Client Library you can check documentation with example how to implement username/password authentication flow .如果您使用的是Microsoft Graph .NET 客户端库,您可以查看文档,例如如何实现username/password authentication flow

string[] scopes = {"User.Read"};

var usernamePasswordCredential = new UsernamePasswordCredential("username@domain.com", "password", tenantId, clientId);

var graphClient = new GraphServiceClient(usernamePasswordCredential, scopes);

var me = await graphClient.Me.Request().GetAsync();

You can use AcquireTokenByUsernamePassword() for that, see MSDN .您可以为此使用AcquireTokenByUsernamePassword() ,请参阅MSDN

Note however that Microsoft discourages usage of this flow and depending on your AzureAD setup there might be restrictions (ie you can aquire tokens only within a certain IP range etc).但请注意,Microsoft 不鼓励使用此流程,并且根据您的 AzureAD 设置可能存在限制(即您只能在某个 IP 范围等内获取令牌)。

Well, you can get the access token silently but not at the first time, First a user must authorize your app by going through Microsoft's Login flow and for your subsequent calls to Microsoft, you can get the access token without the intervention of user.好吧,您可以静默获取访问令牌,但不是第一次,首先,用户必须通过 Microsoft 的登录流程授权您的应用程序,并且对于您随后对 Microsoft 的调用,您可以在无需用户干预的情况下获取访问令牌。

I would just give a basic idea, without focusing on a specific SDK that you might be using.我只是给出一个基本的想法,而不关注您可能正在使用的特定SDK For which, you can decide which ever method suits your needs.为此,您可以决定哪种方法适合您的需求。

  1. I assume, you already have your credentials and desired scopes with you, otherwise you need to obtain those.我假设,您已经拥有您的凭据和所需的范围,否则您需要获得这些。
  2. Formulate a proper URL using the credentials you obtained, plus you need to add an extra scope in the URL which is offline_access .使用您获得的凭据制定适当的 URL,另外您需要在离线访问的 URL 中添加额外的offline_access Then you need to redirect the user to Microsoft for the initial authorization.然后您需要将用户重定向到 Microsoft 以获得初始授权。
  3. If the user logs in successfully, Microsoft will redirect the user back to your website with an Authorization Code .如果用户成功登录,Microsoft 将使用Authorization Code将用户重定向回您的网站。
  4. Grab that Authorization Code and exchange it for an Access Token using /oauth2/{version}/token api.获取该授权码并使用/oauth2/{version}/token api 将其交换为Access Token
  5. You will receive a response from above call which will contain an Access Token along with a Refresh Token .您将收到来自上述调用的响应,其中将包含一个Access Token和一个Refresh Token You need to store the refresh token somewhere for future use.您需要将刷新令牌存储在某处以备将来使用。

Now comes the interesting part.现在是有趣的部分。

  1. Using the refresh token , you can renew the access token when it expires without user's intervention.使用refresh token ,您可以在访问令牌到期时更新访问令牌,而无需用户干预。 You can use oauth2/v2.0/token api with parameters:您可以使用oauth2/v2.0/token api 和参数:
client_id={your_client_id}&scope={your_scopes}&refresh_token={refresh_token_obtained}&grant_type=refresh_token&client_secret={your_client_secret}

The resultant response would look something like this:结果响应看起来像这样:

{
    "access_token": "new access token",
    "token_type": "Bearer",
    "expires_in": 3599,
    "scope": "your scopes",
    "refresh_token": "refresh token",
}

REF: https://docs.microsoft.com/en-us/graph/auth-v2-user#authorization-request编号: https://docs.microsoft.com/en-us/graph/auth-v2-user#authorization-request

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM