public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
        {
            using (AuthentificationRepository _repo = new AuthentificationRepository())
            {
                ApplicationUser user = await _repo.FindUser(context.UserName, context.Password);

                if (user == null)
                {
                    context.SetError("invalid_grant", "The user name or password is incorrect.");
                    return;
                }
            }

            var identity = new ClaimsIdentity(context.Options.AuthenticationType);

            identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
            identity.AddClaim(new Claim("sub", context.UserName));
            identity.AddClaim(new Claim("role", "user"));

            var props = new AuthenticationProperties(new Dictionary <string, string>
            {
                {
                    "as:client_id", (context.ClientId == null) ? string.Empty : context.ClientId
                },
                {
                    "userName", context.UserName
                }
            });

            var ticket = new AuthenticationTicket(identity, props);

            context.Validated(ticket);
        }
        public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId     = string.Empty;
            string clientSecret = string.Empty;
            Client client       = null;

            if (!context.TryGetBasicCredentials(out clientId, out clientSecret))
            {
                context.TryGetFormCredentials(out clientId, out clientSecret);
            }

            if (context.ClientId == null)
            {
                context.Validated();
                //context.SetError("invalid_clientId", "ClientId should be sent.");
                return(Task.FromResult <object>(null));
            }

            using (AuthentificationRepository _repo = new AuthentificationRepository())
            {
                client = _repo.FindClient(context.ClientId);
            }

            if (client == null)
            {
                context.SetError("invalid_clientId", string.Format("Client '{0}' is not registered in the system.", context.ClientId));
                return(Task.FromResult <object>(null));
            }

            if (client.ApplicationType == ApplicationTypes.NativeConfidential)
            {
                if (string.IsNullOrWhiteSpace(clientSecret))
                {
                    context.SetError("invalid_clientId", "Client secret should be sent.");
                    return(Task.FromResult <object>(null));
                }
                else
                {
                    if (client.Secret != Helper.GetHash(clientSecret))
                    {
                        context.SetError("invalid_clientId", "Client secret is invalid.");
                        return(Task.FromResult <object>(null));
                    }
                }
            }

            if (!client.Active)
            {
                context.SetError("invalid_clientId", "Client is inactive.");
                return(Task.FromResult <object>(null));
            }

            context.OwinContext.Set <string>("as:clientAllowedOrigin", client.AllowedOrigin);
            context.OwinContext.Set <string>("as:clientRefreshTokenLifeTime", client.RefreshTokenLifeTime.ToString());

            context.Validated();
            return(Task.FromResult <object>(null));
        }
        /// <summary>
        /// the method returns a new access token for the refresh token
        /// </summary>
        /// <param name="context">the current HTTP context</param>
        /// <returns></returns>
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");

            context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });

            string hashedTokenId = Helper.GetHash(context.Token);

            using (AuthentificationRepository _repo = new AuthentificationRepository())
            {
                var refreshToken = await _repo.FindRefreshToken(hashedTokenId);

                if (refreshToken != null)
                {
                    context.DeserializeTicket(refreshToken.ProtectedTicket);
                    var result = await _repo.RemoveRefreshToken(hashedTokenId);
                }
            }
        }
Exemplo n.º 4
0
        public async Task Inscription()
        {
            var dto = new DtoTGA001InpDA01UtilisateurPourInscription()
            {
                NomUtilisateur = "stephane",
                MotDePasse     = "password",
                Email          = "*****@*****.**",
                Prenom         = "Stéphane",
                NomDeFamille   = "Bressani",
                Adresse        = "16A ch. des Buclines",
                CodePostal     = "1224",
                Lieu           = "Chêne-Bougeries"
            };

            using var context = new DataContext(this.DA001TestDbContext().Options);
            // Connection au repository
            var repo = new AuthentificationRepository(context);

            context.Database.EnsureCreated();

            var userToCreate = new DA01Utilisateur
            {
                NomUtilisateur = dto.NomUtilisateur,
                EMail          = dto.Email
            };
            var clientToCreate = new DA10Client
            {
                Prenom       = dto.Prenom,
                NomDeFamille = dto.NomDeFamille,
                Adresse      = dto.Adresse,
                CodePostal   = dto.CodePostal,
                Lieu         = dto.Lieu
            };
            await repo.Inscription(userToCreate, clientToCreate, dto.MotDePasse);

            Assert.True(await repo.UtilisateurExiste(dto.NomUtilisateur));
        }
        public async Task CreateAsync(AuthenticationTokenCreateContext context)
        {
            var clientid = context.Ticket.Properties.Dictionary["as:client_id"];

            if (string.IsNullOrEmpty(clientid))
            {
                return;
            }

            var refreshTokenId = Guid.NewGuid().ToString("n");

            using (AuthentificationRepository _repo = new AuthentificationRepository())
            {
                var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");

                var token = new RefreshToken()
                {
                    Id         = Helper.GetHash(refreshTokenId),
                    ClientId   = clientid,
                    Subject    = context.Ticket.Identity.Name,
                    IssuedUtc  = DateTime.UtcNow,
                    ExpiresUtc = DateTime.UtcNow.AddMinutes(Convert.ToDouble(refreshTokenLifeTime))
                };

                context.Ticket.Properties.IssuedUtc  = token.IssuedUtc;
                context.Ticket.Properties.ExpiresUtc = token.ExpiresUtc;

                token.ProtectedTicket = context.SerializeTicket();

                var result = await _repo.AddRefreshToken(token);

                if (result)
                {
                    context.SetToken(refreshTokenId);
                }
            }
        }
 /// <summary>
 /// the constructor creates a new instance of a controller
 /// </summary>
 public AccountController()
 {
     _Repo    = new AuthentificationRepository();
     _SecRepo = new RoleRightRepository();
 }