Exemple #1
0
        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));
        }