public ActionResult <Model.Korisnik> Auth() { if (!Request.Headers.ContainsKey("Authorization")) { return(BadRequest(new { message = "Missing Authorization Header" })); } Model.Korisnik user = null; try { var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentialBytes = Convert.FromBase64String(authHeader.Parameter); var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':'); var username = credentials[0]; var password = credentials[1]; user = _userService.Authenticate(username, password); } catch { return(BadRequest(new { message = "Invalid Authorization Header" })); } if (user == null) { return(BadRequest(new { message = "Username or password is incorrect" })); } return(Ok(user)); }
public async Task <IActionResult> LoginWithFaceID([FromBody] TokenEndpointRequestBody model) { if (model == null) { return(BadRequest()); } byte[] img = null; try { img = Convert.FromBase64String(model.Image); } catch (Exception ex) { return(BadRequest(ex.Message)); } var korisnickiNalog = await _korisnikService.Authenticate(img); if (korisnickiNalog == null) { return(BadRequest(SharedResources.UnsuccessfulFaceIdAuthentication)); } //Secret GUID for resource owner password validator (if GUID is not valid, auth will be rejected) var secretGuid = new Guid(); FaceIDSecretsManager.Add(secretGuid); var postBody = @"client_id=" + model.ClientId + "&client_secret=" + model.ClientSecret + "&grant_type=password&username="******"{korisnickiNalog.Username}*{korisnickiNalog.Id}" + $"&password={secretGuid}" + "&scope=openid offline_access face-recognition"; var client = new HttpClient(); HttpResponseMessage response; var uri = Environment.IsDevelopment() ? $"{Request.Scheme}://{Request.Host.Value}" : Resources.ProductionUri; using (var stringContent = new StringContent(postBody, Encoding.UTF8, "application/x-www-form-urlencoded")) { response = await client.PostAsync($@"{uri}/connect/token", stringContent); } if (response.StatusCode == HttpStatusCode.OK) { var responseJson = await response.Content.ReadAsStringAsync(); return(Ok(responseJson)); } return(BadRequest(response.Content.ReadAsStringAsync())); }
protected override async Task <AuthenticateResult> HandleAuthenticateAsync() { if (!Request.Headers.ContainsKey("Authorization")) { return(AuthenticateResult.Fail("Missing Authorization Header")); } Model.Korisnik CurrentUser = null; try { var authHeader = AuthenticationHeaderValue.Parse(Request.Headers["Authorization"]); var credentialBytes = Convert.FromBase64String(authHeader.Parameter); var credentials = Encoding.UTF8.GetString(credentialBytes).Split(':'); var username = credentials[0]; var password = credentials[1]; CurrentUser = _korisnikService.Authenticate(username, password); } catch { return(AuthenticateResult.Fail("Invalid Authorization Header")); } if (CurrentUser == null) { return(AuthenticateResult.Fail("Invalid Username or Password")); } _korisnikService.SetCurrentUser(CurrentUser); var claims = new List <Claim> { new Claim(ClaimTypes.NameIdentifier, CurrentUser.KorisnickoIme), new Claim(ClaimTypes.Name, CurrentUser.Ime + " " + CurrentUser.Prezime), }; claims.Add(new Claim(ClaimTypes.Role, CurrentUser.Uloga)); var identity = new ClaimsIdentity(claims, Scheme.Name); var principal = new ClaimsPrincipal(identity); var ticket = new AuthenticationTicket(principal, Scheme.Name); return(AuthenticateResult.Success(ticket)); }
public async Task ValidateAsync(ResourceOwnerPasswordValidationContext context) { //Only for patients (mobile client) if (context.Request.ClientId == OAuthConstants.MobileClientId && context.Request.Scopes.Any(x => x.StartsWith(InMemoryConfig.FaceRecognitionScope))) { if (FaceIDSecretsManager.IsValidSecret(Guid.Parse(context.Password))) { var usernameAndId = context.UserName.Split('*'); if (usernameAndId.Length <= 1) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidTarget, "Invalid Face ID"); } var username = usernameAndId[0]; var userId = usernameAndId[1]; await BuildSuccessResultAsync(username, userId, context); } else { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidTarget, "Invalid Face ID"); } } else { var user = await _korisnikService.Authenticate(context.UserName, context.Password); if (user == null) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidTarget, "Invalid credentials"); return; } if (string.IsNullOrWhiteSpace(context.UserName) || string.IsNullOrWhiteSpace(context.Password)) { return; } if (!user.Roles.Any()) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidTarget, "Invalid credentials"); return; } //E.g. role with Id = 1 is Administrator, Id = 2 is Doktor, etc.. Here is role with the lowest value of ID (highest permissions) var leadRole = user.Roles.Min(); //1. condition -> If mobile client request access token and user doesn't have Pacijent role //2. condition -> If desktop client request access token and user doesn't have one of these roles => Administrator, Doktor or RadnikPrijem if ((context.Request.ClientId == OAuthConstants.MobileClientId && !RoleType.Pacijent.EqualInt(leadRole)) || (context.Request.ClientId == OAuthConstants.DesktopClientId && !RoleType.Administrator.EqualInt(leadRole) && !RoleType.Doktor.EqualInt(leadRole) && !RoleType.MedicinskiTehnicar.EqualInt(leadRole) && !RoleType.RadnikPrijem.EqualInt(leadRole))) { context.Result = new GrantValidationResult(TokenRequestErrors.InvalidTarget, "Invalid credentials"); return; } await BuildSuccessResultAsync(user.Username, user.Id.ToString(), context); } }