public async Task <IHttpActionResult> Post([FromBody] UserLoginModel model) { IUserRepository userRepository = _uow.GetRepository <IUserRepository>(); string hash = Md5Tool.CreateUtf8Hash(model.Password); dynamic user = await userRepository.GetQueryable().AsNoTracking().Include(x => x.UserRoles.Select(y => y.Role)).Where(x => x.UserName == model.UserName && x.Password == hash).Select(x => new { x.UserName, Roles = x.UserRoles.Select(y => y.Role.Name) }).FirstOrDefaultAsync(); if (user != null) { string secretKey = ConfigurationManager.AppSettings["SecretKey"]; double tokenExpiration = double.Parse(ConfigurationManager.AppSettings["TokenExpirationMinutes"]); string token = new CustomJwtAuthorizationProvider().GenerateToken(secretKey, user.UserName, user.Roles, tokenExpiration); return(Ok(new { access_token = token, token_type = "bearer", expires_in = TimeSpan.FromMinutes(tokenExpiration).TotalSeconds })); } return(Unauthorized()); }
public override void OnAuthorization(HttpActionContext actionContext) { AuthenticationHeaderValue authRequest = actionContext.Request.Headers.Authorization; if (authRequest != null && authRequest.Scheme.Equals("bearer", StringComparison.OrdinalIgnoreCase)) { string token = authRequest.Parameter; if (!string.IsNullOrEmpty(token)) { string secretKey = ConfigurationManager.AppSettings["SecretKey"]; ClaimsPrincipal principal = null; try { principal = new CustomJwtAuthorizationProvider().GetPrincipal(secretKey, token); } catch (Exception ex) { Logger.Error(ex.Message); } if (principal != null) { ClaimsIdentity identity = (ClaimsIdentity)principal.Identity; Claim nameClaim = identity.FindFirst(ClaimTypes.Name); Claim nameIdentifierClaim = identity.FindFirst(ClaimTypes.NameIdentifier); IList <Claim> claims = new List <Claim> { nameClaim, nameIdentifierClaim }; IList <Claim> roleClaims = identity.FindAll(ClaimTypes.Role).ToList(); if (roleClaims.Any()) { foreach (Claim roleClaim in roleClaims) { claims.Add(roleClaim); } } actionContext.RequestContext.Principal = new ClaimsPrincipal(new ClaimsIdentity(claims, "bearer")); } //else //{ // actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, "Unauthorized."); //} } } base.OnAuthorization(actionContext); }