run-editor-sample-bom-cs.txt 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net.Http;
  4. using System.Security.Claims;
  5. using System.Security.Cryptography;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. using System.Web.Http;
  9. using System.Web.Http.ModelBinding;
  10. using Microsoft.AspNet.Identity;
  11. using Microsoft.AspNet.Identity.EntityFramework;
  12. using Microsoft.AspNet.Identity.Owin;
  13. using Microsoft.Owin.Security;
  14. using Microsoft.Owin.Security.Cookies;
  15. using Microsoft.Owin.Security.OAuth;
  16. using WebApplication.Models;
  17. using WebApplication.Providers;
  18. using WebApplication.Results;
  19. namespace WebApplication.Controllers
  20. {
  21. [Authorize]
  22. [RoutePrefix("api/Account")]
  23. public class AccountController : ApiController
  24. {
  25. private const string LocalLoginProvider = "Local";
  26. private ApplicationUserManager _userManager;
  27. public AccountController()
  28. {
  29. }
  30. public AccountController(ApplicationUserManager userManager,
  31. ISecureDataFormat<AuthenticationTicket> accessTokenFormat)
  32. {
  33. UserManager = userManager;
  34. AccessTokenFormat = accessTokenFormat;
  35. }
  36. public ApplicationUserManager UserManager
  37. {
  38. get
  39. {
  40. return _userManager ?? Request.GetOwinContext().GetUserManager<ApplicationUserManager>();
  41. }
  42. private set
  43. {
  44. _userManager = value;
  45. }
  46. }
  47. public ISecureDataFormat<AuthenticationTicket> AccessTokenFormat { get; private set; }
  48. // GET api/Account/UserInfo
  49. [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
  50. [Route("UserInfo")]
  51. public UserInfoViewModel GetUserInfo()
  52. {
  53. ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
  54. return new UserInfoViewModel
  55. {
  56. Email = User.Identity.GetUserName(),
  57. HasRegistered = externalLogin == null,
  58. LoginProvider = externalLogin != null ? externalLogin.LoginProvider : null
  59. };
  60. }
  61. // POST api/Account/Logout
  62. [Route("Logout")]
  63. public IHttpActionResult Logout()
  64. {
  65. Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
  66. return Ok();
  67. }
  68. // GET api/Account/ManageInfo?returnUrl=%2F&generateState=true
  69. [Route("ManageInfo")]
  70. public async Task<ManageInfoViewModel> GetManageInfo(string returnUrl, bool generateState = false)
  71. {
  72. IdentityUser user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
  73. if (user == null)
  74. {
  75. return null;
  76. }
  77. List<UserLoginInfoViewModel> logins = new List<UserLoginInfoViewModel>();
  78. foreach (IdentityUserLogin linkedAccount in user.Logins)
  79. {
  80. logins.Add(new UserLoginInfoViewModel
  81. {
  82. LoginProvider = linkedAccount.LoginProvider,
  83. ProviderKey = linkedAccount.ProviderKey
  84. });
  85. }
  86. if (user.PasswordHash != null)
  87. {
  88. logins.Add(new UserLoginInfoViewModel
  89. {
  90. LoginProvider = LocalLoginProvider,
  91. ProviderKey = user.UserName,
  92. });
  93. }
  94. return new ManageInfoViewModel
  95. {
  96. LocalLoginProvider = LocalLoginProvider,
  97. Email = user.UserName,
  98. Logins = logins,
  99. ExternalLoginProviders = GetExternalLogins(returnUrl, generateState)
  100. };
  101. }
  102. // POST api/Account/ChangePassword
  103. [Route("ChangePassword")]
  104. public async Task<IHttpActionResult> ChangePassword(ChangePasswordBindingModel model)
  105. {
  106. if (!ModelState.IsValid)
  107. {
  108. return BadRequest(ModelState);
  109. }
  110. IdentityResult result = await UserManager.ChangePasswordAsync(User.Identity.GetUserId(), model.OldPassword,
  111. model.NewPassword);
  112. if (!result.Succeeded)
  113. {
  114. return GetErrorResult(result);
  115. }
  116. return Ok();
  117. }
  118. // POST api/Account/SetPassword
  119. [Route("SetPassword")]
  120. public async Task<IHttpActionResult> SetPassword(SetPasswordBindingModel model)
  121. {
  122. if (!ModelState.IsValid)
  123. {
  124. return BadRequest(ModelState);
  125. }
  126. IdentityResult result = await UserManager.AddPasswordAsync(User.Identity.GetUserId(), model.NewPassword);
  127. if (!result.Succeeded)
  128. {
  129. return GetErrorResult(result);
  130. }
  131. return Ok();
  132. }
  133. // POST api/Account/AddExternalLogin
  134. [Route("AddExternalLogin")]
  135. public async Task<IHttpActionResult> AddExternalLogin(AddExternalLoginBindingModel model)
  136. {
  137. if (!ModelState.IsValid)
  138. {
  139. return BadRequest(ModelState);
  140. }
  141. Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  142. AuthenticationTicket ticket = AccessTokenFormat.Unprotect(model.ExternalAccessToken);
  143. if (ticket == null || ticket.Identity == null || (ticket.Properties != null
  144. && ticket.Properties.ExpiresUtc.HasValue
  145. && ticket.Properties.ExpiresUtc.Value < DateTimeOffset.UtcNow))
  146. {
  147. return BadRequest("External login failure.");
  148. }
  149. ExternalLoginData externalData = ExternalLoginData.FromIdentity(ticket.Identity);
  150. if (externalData == null)
  151. {
  152. return BadRequest("The external login is already associated with an account.");
  153. }
  154. IdentityResult result = await UserManager.AddLoginAsync(User.Identity.GetUserId(),
  155. new UserLoginInfo(externalData.LoginProvider, externalData.ProviderKey));
  156. if (!result.Succeeded)
  157. {
  158. return GetErrorResult(result);
  159. }
  160. return Ok();
  161. }
  162. // POST api/Account/RemoveLogin
  163. [Route("RemoveLogin")]
  164. public async Task<IHttpActionResult> RemoveLogin(RemoveLoginBindingModel model)
  165. {
  166. if (!ModelState.IsValid)
  167. {
  168. return BadRequest(ModelState);
  169. }
  170. IdentityResult result;
  171. if (model.LoginProvider == LocalLoginProvider)
  172. {
  173. result = await UserManager.RemovePasswordAsync(User.Identity.GetUserId());
  174. }
  175. else
  176. {
  177. result = await UserManager.RemoveLoginAsync(User.Identity.GetUserId(),
  178. new UserLoginInfo(model.LoginProvider, model.ProviderKey));
  179. }
  180. if (!result.Succeeded)
  181. {
  182. return GetErrorResult(result);
  183. }
  184. return Ok();
  185. }
  186. // GET api/Account/ExternalLogin
  187. [OverrideAuthentication]
  188. [HostAuthentication(DefaultAuthenticationTypes.ExternalCookie)]
  189. [AllowAnonymous]
  190. [Route("ExternalLogin", Name = "ExternalLogin")]
  191. public async Task<IHttpActionResult> GetExternalLogin(string provider, string error = null)
  192. {
  193. if (error != null)
  194. {
  195. return Redirect(Url.Content("~/") + "#error=" + Uri.EscapeDataString(error));
  196. }
  197. if (!User.Identity.IsAuthenticated)
  198. {
  199. return new ChallengeResult(provider, this);
  200. }
  201. ExternalLoginData externalLogin = ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
  202. if (externalLogin == null)
  203. {
  204. return InternalServerError();
  205. }
  206. if (externalLogin.LoginProvider != provider)
  207. {
  208. Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  209. return new ChallengeResult(provider, this);
  210. }
  211. ApplicationUser user = await UserManager.FindAsync(new UserLoginInfo(externalLogin.LoginProvider,
  212. externalLogin.ProviderKey));
  213. bool hasRegistered = user != null;
  214. if (hasRegistered)
  215. {
  216. Authentication.SignOut(DefaultAuthenticationTypes.ExternalCookie);
  217. ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(UserManager,
  218. OAuthDefaults.AuthenticationType);
  219. ClaimsIdentity cookieIdentity = await user.GenerateUserIdentityAsync(UserManager,
  220. CookieAuthenticationDefaults.AuthenticationType);
  221. AuthenticationProperties properties = ApplicationOAuthProvider.CreateProperties(user.UserName);
  222. Authentication.SignIn(properties, oAuthIdentity, cookieIdentity);
  223. }
  224. else
  225. {
  226. IEnumerable<Claim> claims = externalLogin.GetClaims();
  227. ClaimsIdentity identity = new ClaimsIdentity(claims, OAuthDefaults.AuthenticationType);
  228. Authentication.SignIn(identity);
  229. }
  230. return Ok();
  231. }
  232. // GET api/Account/ExternalLogins?returnUrl=%2F&generateState=true
  233. [AllowAnonymous]
  234. [Route("ExternalLogins")]
  235. public IEnumerable<ExternalLoginViewModel> GetExternalLogins(string returnUrl, bool generateState = false)
  236. {
  237. IEnumerable<AuthenticationDescription> descriptions = Authentication.GetExternalAuthenticationTypes();
  238. List<ExternalLoginViewModel> logins = new List<ExternalLoginViewModel>();
  239. string state;
  240. if (generateState)
  241. {
  242. const int strengthInBits = 256;
  243. state = RandomOAuthStateGenerator.Generate(strengthInBits);
  244. }
  245. else
  246. {
  247. state = null;
  248. }
  249. foreach (AuthenticationDescription description in descriptions)
  250. {
  251. ExternalLoginViewModel login = new ExternalLoginViewModel
  252. {
  253. Name = description.Caption,
  254. Url = Url.Route("ExternalLogin", new
  255. {
  256. provider = description.AuthenticationType,
  257. response_type = "token",
  258. client_id = Startup.PublicClientId,
  259. redirect_uri = new Uri(Request.RequestUri, returnUrl).AbsoluteUri,
  260. state = state
  261. }),
  262. State = state
  263. };
  264. logins.Add(login);
  265. }
  266. return logins;
  267. }
  268. // POST api/Account/Register
  269. [AllowAnonymous]
  270. [Route("Register")]
  271. public async Task<IHttpActionResult> Register(RegisterBindingModel model)
  272. {
  273. if (!ModelState.IsValid)
  274. {
  275. return BadRequest(ModelState);
  276. }
  277. var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
  278. IdentityResult result = await UserManager.CreateAsync(user, model.Password);
  279. if (!result.Succeeded)
  280. {
  281. return GetErrorResult(result);
  282. }
  283. return Ok();
  284. }
  285. // POST api/Account/RegisterExternal
  286. [OverrideAuthentication]
  287. [HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
  288. [Route("RegisterExternal")]
  289. public async Task<IHttpActionResult> RegisterExternal(RegisterExternalBindingModel model)
  290. {
  291. if (!ModelState.IsValid)
  292. {
  293. return BadRequest(ModelState);
  294. }
  295. var info = await Authentication.GetExternalLoginInfoAsync();
  296. if (info == null)
  297. {
  298. return InternalServerError();
  299. }
  300. var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
  301. IdentityResult result = await UserManager.CreateAsync(user);
  302. if (!result.Succeeded)
  303. {
  304. return GetErrorResult(result);
  305. }
  306. result = await UserManager.AddLoginAsync(user.Id, info.Login);
  307. if (!result.Succeeded)
  308. {
  309. return GetErrorResult(result);
  310. }
  311. return Ok();
  312. }
  313. protected override void Dispose(bool disposing)
  314. {
  315. if (disposing)
  316. {
  317. UserManager.Dispose();
  318. }
  319. base.Dispose(disposing);
  320. }
  321. #region Helpers
  322. private IAuthenticationManager Authentication
  323. {
  324. get { return Request.GetOwinContext().Authentication; }
  325. }
  326. private IHttpActionResult GetErrorResult(IdentityResult result)
  327. {
  328. if (result == null)
  329. {
  330. return InternalServerError();
  331. }
  332. if (!result.Succeeded)
  333. {
  334. if (result.Errors != null)
  335. {
  336. foreach (string error in result.Errors)
  337. {
  338. ModelState.AddModelError("", error);
  339. }
  340. }
  341. if (ModelState.IsValid)
  342. {
  343. // No ModelState errors are available to send, so just return an empty BadRequest.
  344. return BadRequest();
  345. }
  346. return BadRequest(ModelState);
  347. }
  348. return null;
  349. }
  350. private class ExternalLoginData
  351. {
  352. public string LoginProvider { get; set; }
  353. public string ProviderKey { get; set; }
  354. public string UserName { get; set; }
  355. public IList<Claim> GetClaims()
  356. {
  357. IList<Claim> claims = new List<Claim>();
  358. claims.Add(new Claim(ClaimTypes.NameIdentifier, ProviderKey, null, LoginProvider));
  359. if (UserName != null)
  360. {
  361. claims.Add(new Claim(ClaimTypes.Name, UserName, null, LoginProvider));
  362. }
  363. return claims;
  364. }
  365. public static ExternalLoginData FromIdentity(ClaimsIdentity identity)
  366. {
  367. if (identity == null)
  368. {
  369. return null;
  370. }
  371. Claim providerKeyClaim = identity.FindFirst(ClaimTypes.NameIdentifier);
  372. if (providerKeyClaim == null || String.IsNullOrEmpty(providerKeyClaim.Issuer)
  373. || String.IsNullOrEmpty(providerKeyClaim.Value))
  374. {
  375. return null;
  376. }
  377. if (providerKeyClaim.Issuer == ClaimsIdentity.DefaultIssuer)
  378. {
  379. return null;
  380. }
  381. return new ExternalLoginData
  382. {
  383. LoginProvider = providerKeyClaim.Issuer,
  384. ProviderKey = providerKeyClaim.Value,
  385. UserName = identity.FindFirstValue(ClaimTypes.Name)
  386. };
  387. }
  388. }
  389. private static class RandomOAuthStateGenerator
  390. {
  391. private static RandomNumberGenerator _random = new RNGCryptoServiceProvider();
  392. public static string Generate(int strengthInBits)
  393. {
  394. const int bitsPerByte = 8;
  395. if (strengthInBits % bitsPerByte != 0)
  396. {
  397. throw new ArgumentException("strengthInBits must be evenly divisible by 8.", "strengthInBits");
  398. }
  399. int strengthInBytes = strengthInBits / bitsPerByte;
  400. byte[] data = new byte[strengthInBytes];
  401. _random.GetBytes(data);
  402. return HttpServerUtility.UrlTokenEncode(data);
  403. }
  404. }
  405. #endregion
  406. }
  407. }