2016-07-08 39 views
0

更新如何使一个请求,从UWP我的.NET核心应用,与微软帐户验证

在网络侧的一些代码

startup.cs

 app.UseOAuthAuthentication(new OAuthOptions() 
     { 
      AuthenticationScheme = "Microsoft-AccessToken", 
      DisplayName = "MicrosoftAccount-AccessToken", 
      ClientId = {CliendID}, 
      ClientSecret = {ClientSecret}, 
      CallbackPath = new PathString("/signin-microsoft-token"), 
      AuthorizationEndpoint = MicrosoftAccountDefaults.AuthorizationEndpoint, 
      TokenEndpoint = MicrosoftAccountDefaults.TokenEndpoint, 
      UserInformationEndpoint = MicrosoftAccountDefaults.UserInformationEndpoint, 
      Scope = { "https://graph.microsoft.com/user.read" }, 
      SaveTokens = true, 
      Events = new OAuthEvents() 
      { 
       OnCreatingTicket = async context => 
       { 
        var request = new HttpRequestMessage(HttpMethod.Get, context.Options.UserInformationEndpoint); 
        request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", context.AccessToken); 
        request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

        var response = await context.Backchannel.SendAsync(request, context.HttpContext.RequestAborted); 
        response.EnsureSuccessStatusCode(); 

        var user = JObject.Parse(await response.Content.ReadAsStringAsync()); 

        var identifier = user.Value<string>("id"); 
        if (!string.IsNullOrEmpty(identifier)) 
        { 
         context.Identity.AddClaim(new Claim(
          ClaimTypes.NameIdentifier, identifier, 
          ClaimValueTypes.String, context.Options.ClaimsIssuer)); 
        } 

        var userName = user.Value<string>("displayName"); 
        if (!string.IsNullOrEmpty(userName)) 
        { 
         context.Identity.AddClaim(new Claim(
          ClaimTypes.Name, userName, 
          ClaimValueTypes.String, context.Options.ClaimsIssuer)); 
        } 

        var email = user.Value<string>("userPrincipalName"); 
        if (!string.IsNullOrEmpty(email)) 
        { 
         context.Identity.AddClaim(new Claim(
          ClaimTypes.Email, email, 
          ClaimValueTypes.Email, context.Options.ClaimsIssuer)); 
        } 
       } 
      } 
     }); 

HomeController.cs

[Authorize] 
    public string GetInfo() 
    { 
     return "Hello world!"; 
    } 

我是能够检索用户的令牌,像这样

 string MicrosoftClientID = {ClientID}; 
     string MicrosoftCallbackURL = "urn:ietf:wg:oauth:2.0:oob"; 
     string scope = WebUtility.UrlEncode("openid offline_access https://graph.microsoft.com/user.read"); 
     string MicrosoftURL = "https://login.microsoftonline.com/consumers/oauth2/v2.0/authorize?client_id=" + MicrosoftClientID + "&response_type=code&redirect_uri=" + MicrosoftCallbackURL + "&response_mode=query&scope=" + scope; 

     Uri StartUri = new Uri(MicrosoftURL); 
     Uri EndUri = new Uri(MicrosoftCallbackURL); 

     WebAuthenticationResult WebAuthenticationResult = await WebAuthenticationBroker.AuthenticateAsync(
               WebAuthenticationOptions.None, 
               StartUri, 
               EndUri); 
     if (WebAuthenticationResult.ResponseStatus == WebAuthenticationStatus.Success) 
     { 
      string code = WebAuthenticationResult.ResponseData.Replace("urn:ietf:wg:oauth:2.0:oob?code=", ""); 
      string strContent = "client_id=" + MicrosoftClientID + "&scope=" + scope + "&code=" + code + "&redirect_uri=" + MicrosoftCallbackURL + "&grant_type=authorization_code"; 

      HttpClient httpClient = new HttpClient(); 
      HttpContent httpContent = new StringContent(strContent); 
      httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); 
      HttpResponseMessage httpResponseMessage = await httpClient.PostAsync("https://login.microsoftonline.com/consumers/oauth2/v2.0/token", httpContent); 
      string stringResponse = await httpResponseMessage.Content.ReadAsStringAsync(); 
     } 

但如何使用令牌,使我的.NET核心的Web应用程序的API请求,这是在蔚蓝的托管代码?

我尝试了这些

  httpClient = new HttpClient(); 
      httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", authenticationModel.AccessToken); 
      string apicontent = await httpClient.GetStringAsync("https://{host}.azurewebsites.net/home/GetInfo"); 
      apicontent.ToString(); 

我的一切是登录页面的HTML

任何帮助吗?

+1

API(** GetInfo **)是如何要求授权的?您请求的包含Microsoft Graph相对范围的令牌意味着您可以直接调用** Microsoft Graph **。但是,如果您的API需要授权,它仍然需要进行身份验证和授权。 –

+0

@FeiXue Thx给你评论,我在这里添加了一些我的asp.net核心代码。无论如何,我可以授权在UWP? –

回答

0

此授权与普通网络应用程序相同。

如果你不想当你调用这个API认证用户,你可以删除attribure [授权]的GetInfo。如果您还拥有控制器的授权,您可以添加[AllowAnonymous]属性以指定授权期间AuthorizeAttribute跳过此操作。

您可以参考here关于认证和授权。

+0

感谢您的回复,但这似乎与我的问题无关 –

0

让我们从Web Api开始:

这里是我从Api中检索朋友列表的示例方法。 注有“路由前缀”属性 - 来表示我想检索并“授权”其资源属性调用此方法之前,要求验证:在UWP应用程序,您将调用此方法

[RoutePrefix("api/Friends")] 
public class FriendsController : ApiController 
{ 
    [Authorize] 
    [Route("GetConfirmedFriends")] 
    public IHttpActionResult GetConfirmedFriends() 
    { 
     using (DbWrapper dbContext = new DbWrapper()) 
     { 
      return Ok(dbContext.GetConfirmedFriends()); 
     } 
    } 
} 

现在如下所示:

public async Task<ObservableCollection<Friend>> GetConfirmedFriends() 
    { 
     //access token eretrieved after MS authentication: 
     if (_accessToken == null) 
      throw new NullReferenceException("Access token cannot be empty. Please authenticate first"); 
     try 
     { 
      using (HttpClient client = new HttpClient()) 
      { 
       ObservableCollection<Friend> friends = null; 
       client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _accessToken); 
       var data = await client.GetAsync(string.Concat(https://{host}.azurewebsites.net/, "api/Friends/GetConfirmedFriends")); 
       var jsonResponse = await data.Content.ReadAsStringAsync(); 
       if (jsonResponse != null) 
        friends = JsonConvert.DeserializeObject<ObservableCollection<Friend>>(jsonResponse); 
       return friends; 
      } 
     } 

     catch (WebException exception) 
     { 
      throw new WebException("An error has occurred while calling GetConfirmedFriends method: " + exception.Message); 
     } 
    } 

请检查并告诉我。

+0

感谢您的答案和代码示例,我相信我有一个类似的模式,就像您在这里所做的一样。但是在向UWP提出请求时,我无法通过身份验证。我猜测有两个原因:1。我没有从正确的微软api检索用户令牌,2.我没有在启动时设置身份验证架构。CS正确 –

+0

我会尝试测试你的代码来找到解决方案。 –

相关问题