Advertisement
Guest User

Untitled

a guest
Jun 30th, 2017
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. using System;
  2. using System.IdentityModel.Tokens;
  3. using System.Linq;
  4. using System.Security.Claims;
  5. using System.Web.Http;
  6. using Backend.Models;
  7. using Microsoft.Azure.Mobile.Server.Login;
  8. using Newtonsoft.Json;
  9.  
  10. namespace Backend.Controllers
  11. {
  12. [Route(".auth/login/custom")]
  13. public class CustomAuthController : ApiController
  14. {
  15. private MobileServiceContext db;
  16. private string signingKey, audience, issuer;
  17.  
  18. public CustomAuthController()
  19. {
  20. db = new MobileServiceContext();
  21. signingKey = Environment.GetEnvironmentVariable("WEBSITE_AUTH_SIGNING_KEY");
  22. var website = Environment.GetEnvironmentVariable("WEBSITE_HOSTNAME");
  23. audience = $"https://{website}/";
  24. issuer = $"https://{website}/";
  25. }
  26.  
  27. [HttpPost]
  28. public IHttpActionResult Post([FromBody] User body)
  29. {
  30. if (body == null || body.Username == null || body.Password == null ||
  31. body.Username.Length == 0 || body.Password.Length == 0)
  32. {
  33. return BadRequest(); ;
  34. }
  35.  
  36. if (!IsValidUser(body))
  37. {
  38. return Unauthorized();
  39. }
  40.  
  41. var claims = new Claim[]
  42. {
  43. new Claim(JwtRegisteredClaimNames.Sub, body.Username)
  44. };
  45.  
  46. JwtSecurityToken token = AppServiceLoginHandler.CreateToken(
  47. claims, signingKey, audience, issuer, TimeSpan.FromDays(30));
  48. return Ok(new LoginResult()
  49. {
  50. AuthenticationToken = token.RawData,
  51. User = new LoginResultUser { UserId = body.Username }
  52. });
  53. }
  54.  
  55. protected override void Dispose(bool disposing)
  56. {
  57. if (disposing)
  58. {
  59. db.Dispose();
  60. }
  61. base.Dispose(disposing);
  62. }
  63.  
  64. private bool IsValidUser(User user)
  65. {
  66. return db.Users.Count(u => u.Username.Equals(user.Username) && u.Password.Equals(user.Password)) > 0;
  67. }
  68. }
  69.  
  70. public class LoginResult
  71. {
  72. [JsonProperty(PropertyName = "authenticationToken")]
  73. public string AuthenticationToken { get; set; }
  74.  
  75. [JsonProperty(PropertyName = "user")]
  76. public LoginResultUser User { get; set; }
  77. }
  78.  
  79. public class LoginResultUser
  80. {
  81. [JsonProperty(PropertyName = "userId")]
  82. public string UserId { get; set; }
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement