Guest User

Untitled

a guest
Nov 2nd, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.44 KB | None | 0 0
  1. //using System;
  2. //using System.Collections.Generic;
  3. //using System.Net;
  4. //using System.Net.Http;
  5. //string token = GetToken("https://localhost:<port>/", userName, password);
  6.  
  7. static string GetToken(string url, string userName, string password) {
  8. var pairs = new List<KeyValuePair<string, string>>
  9. {
  10. new KeyValuePair<string, string>( "grant_type", "password" ),
  11. new KeyValuePair<string, string>( "username", userName ),
  12. new KeyValuePair<string, string> ( "Password", password )
  13. };
  14. var content = new FormUrlEncodedContent(pairs);
  15. ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
  16. using (var client = new HttpClient()) {
  17. var response = client.PostAsync(url + "Token", content).Result;
  18. return response.Content.ReadAsStringAsync().Result;
  19. }
  20. }
  21.  
  22. //using System;
  23. //using System.Collections.Generic;
  24. //using System.Net;
  25. //using System.Net.Http;
  26. //var result = CallApi("https://localhost:<port>/something", token);
  27.  
  28. static string CallApi(string url, string token) {
  29. ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
  30. using (var client = new HttpClient()) {
  31. if (!string.IsNullOrWhiteSpace(token)) {
  32. var t = JsonConvert.DeserializeObject<Token>(token);
  33.  
  34. client.DefaultRequestHeaders.Clear();
  35. client.DefaultRequestHeaders.Add("Authorization", "Bearer " + t.access_token);
  36. }
  37. var response = client.GetAsync(url).Result;
  38. return response.Content.ReadAsStringAsync().Result;
  39. }
  40. }
  41.  
  42. //using Newtonsoft.Json;
  43.  
  44. class Token
  45. {
  46. public string access_token { get; set; }
  47. public string token_type { get; set; }
  48. public int expires_in { get; set; }
  49. public string userName { get; set; }
  50. [JsonProperty(".issued")]
  51. public string issued { get; set; }
  52. [JsonProperty(".expires")]
  53. public string expires { get; set; }
  54. }
  55.  
  56. var oAuthOptions = new OAuthAuthorizationServerOptions
  57. {
  58. TokenEndpointPath = new PathString("/Token"),
  59. Provider = new ApplicationOAuthProvider("self"),
  60. AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
  61. // https
  62. AllowInsecureHttp = false
  63. };
  64. // Enable the application to use bearer tokens to authenticate users
  65. app.UseOAuthBearerTokens(oAuthOptions);
  66.  
  67. //using Microsoft.AspNet.Identity.Owin;
  68. //using Microsoft.Owin.Security;
  69. //using Microsoft.Owin.Security.OAuth;
  70. //using System;
  71. //using System.Collections.Generic;
  72. //using System.Security.Claims;
  73. //using System.Threading.Tasks;
  74.  
  75. public class ApplicationOAuthProvider : OAuthAuthorizationServerProvider
  76. {
  77. private readonly string _publicClientId;
  78.  
  79. public ApplicationOAuthProvider(string publicClientId)
  80. {
  81. if (publicClientId == null)
  82. throw new ArgumentNullException("publicClientId");
  83.  
  84. _publicClientId = publicClientId;
  85. }
  86.  
  87. public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
  88. {
  89. var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>();
  90.  
  91. var user = await userManager.FindAsync(context.UserName, context.Password);
  92. if (user == null)
  93. {
  94. context.SetError("invalid_grant", "The user name or password is incorrect.");
  95. return;
  96. }
  97.  
  98. ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager);
  99. var propertyDictionary = new Dictionary<string, string> { { "userName", user.UserName } };
  100. var properties = new AuthenticationProperties(propertyDictionary);
  101.  
  102. AuthenticationTicket ticket = new AuthenticationTicket(oAuthIdentity, properties);
  103. // Token is validated.
  104. context.Validated(ticket);
  105. }
  106.  
  107. public override Task TokenEndpoint(OAuthTokenEndpointContext context)
  108. {
  109. foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
  110. {
  111. context.AdditionalResponseParameters.Add(property.Key, property.Value);
  112. }
  113. return Task.FromResult<object>(null);
  114. }
  115.  
  116. public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
  117. {
  118. // Resource owner password credentials does not provide a client ID.
  119. if (context.ClientId == null)
  120. context.Validated();
  121.  
  122. return Task.FromResult<object>(null);
  123. }
  124.  
  125. public override Task ValidateClientRedirectUri(OAuthValidateClientRedirectUriContext context)
  126. {
  127. if (context.ClientId == _publicClientId)
  128. {
  129. var expectedRootUri = new Uri(context.Request.Uri, "/");
  130.  
  131. if (expectedRootUri.AbsoluteUri == context.RedirectUri)
  132. context.Validated();
  133. }
  134. return Task.FromResult<object>(null);
  135. }
  136.  
  137. }
  138.  
  139. OAuthOptions = new OAuthAuthorizationServerOptions
  140. {
  141. TokenEndpointPath = new PathString("/Token"),
  142. Provider = new ApplicationOAuthProvider(PublicClientId),
  143. AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
  144. AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
  145. // In production mode set AllowInsecureHttp = false
  146. AllowInsecureHttp = true
  147. };
  148.  
  149. /Token/userName=johndoe%40example.com&password=1234&grant_type=password
Add Comment
Please, Sign In to add comment