Ejemplo n.º 1
0
 protected virtual void AnalyzeOperationContext(RequestDetails details)
 {
     // determine if this is a WCF call
     if (OperationContext.Current != null)
     {
         details.IsActive = true;
         Tracing.Information("Active request");
     }
     else
     {
         Tracing.Information("Passive request");
     }
 }
Ejemplo n.º 2
0
        public SamlTokenServiceConfiguration(string issuerName)
        {
            Tracing.Information("Configuring token service");
            Container.Current.SatisfyImportsOnce(this);

            SecurityTokenService = typeof(SamlTokenService);
            DefaultTokenLifetime = TimeSpan.FromHours(ConfigurationRepository.Global.DefaultTokenLifetime);
            MaximumTokenLifetime = TimeSpan.FromDays(ConfigurationRepository.Global.MaximumTokenLifetime);
            DefaultTokenType     = ConfigurationRepository.Global.DefaultWSTokenType;

            TokenIssuerName    = issuerName;
            SigningCredentials = new X509SigningCredentials(ConfigurationRepository.Keys.SigningCertificate);
        }
Ejemplo n.º 3
0
 protected virtual void AnalyzeTokenType(RequestSecurityToken rst, RequestDetails details)
 {
     if (string.IsNullOrWhiteSpace(rst.TokenType))
     {
         details.TokenType = _configuration.Global.DefaultWSTokenType;
         Tracing.Information("Token Type: not specified, falling back to default token type");
     }
     else
     {
         Tracing.Information("Token Type: " + rst.TokenType);
         details.TokenType = rst.TokenType;
     }
 }
Ejemplo n.º 4
0
        private HttpResponseMessage ProcessRefreshTokenRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing refresh token request");

            var tokenService = new OidcTokenService(
                ServerConfiguration.Global.IssuerUri,
                ServerConfiguration.Keys.SigningCertificate);

            var response = tokenService.CreateTokenResponse(validatedRequest.Grant, validatedRequest.Client.AccessTokenLifetime);

            response.RefreshToken = validatedRequest.Grant.GrantId;
            return(Request.CreateTokenResponse(response));
        }
Ejemplo n.º 5
0
        public virtual void SignIn(User user, bool isPersistant = false)
        {
            Tracing.Information(String.Format("[ClaimsBasedAuthenticationService.Signin] called: {0}", user.Username));

            if (String.IsNullOrWhiteSpace(user.Username))
            {
                throw new ArgumentException("username");
            }

            // gather claims
            var claims = new List <Claim>();

            foreach (UserClaim uc in user.Claims)
            {
                claims.Add(new Claim(uc.Type, uc.Value));
            }

            if (!String.IsNullOrWhiteSpace(user.Email))
            {
                claims.Insert(0, new Claim(ClaimTypes.Email, user.Email));
            }
            claims.Insert(0, new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.Password));
            claims.Insert(0, new Claim(ClaimTypes.AuthenticationInstant, DateTime.UtcNow.ToString("s")));
            claims.Insert(0, new Claim(ClaimTypes.Name, user.Username));
            claims.Insert(0, new Claim(ClaimTypes.NameIdentifier, user.Username));

            // create principal/identity
            var id = new ClaimsIdentity(claims, "Forms");
            var cp = new ClaimsPrincipal(id);

            // claims transform
            cp = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate(String.Empty, cp);

            // issue cookie
            var sam = FederatedAuthentication.SessionAuthenticationModule;

            if (sam == null)
            {
                throw new Exception("SessionAuthenticationModule is not configured and it needs to be.");
            }

            var token = new SessionSecurityToken(cp, isPersistant ?  FormsAuthentication.Timeout : TimeSpan.FromMinutes(SessionHelpers.GetSessionTimeoutInMinutes))
            {
                IsPersistent = isPersistant
            };

            sam.WriteSessionTokenToCookie(token);

            Tracing.Verbose(String.Format("[ClaimsBasedAuthenticationService.Signin] cookie issued: {0}", claims.GetValue(ClaimTypes.NameIdentifier)));
        }
Ejemplo n.º 6
0
        protected override RequestSecurityTokenResponse GetResponse(RequestSecurityToken request,
                                                                    SecurityTokenDescriptor tokenDescriptor)
        {
            var response = base.GetResponse(request, tokenDescriptor);

            if (ConfigurationRepository.Diagnostics.EnableFederationMessageTracing)
            {
                Tracing.Information(SerializeRequest(request));
                Tracing.Information(SerializeResponse(response));
                Tracing.Information(SerializeToken(tokenDescriptor));
            }

            return(response);
        }
Ejemplo n.º 7
0
        public HttpResponseMessage Post(TokenRequest tokenRequest)
        {
            Tracing.Information("OAuth2 endpoint called.");

            Client client = null;

            if (!ValidateClient(out client))
            {
                Tracing.Error("Invalid client: " + ClaimsPrincipal.Current.Identity.Name);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidClient));
            }

            Tracing.Information("Client: " + client.Name);

            var tokenType = ConfigurationRepository.Global.DefaultHttpTokenType;

            // validate scope
            EndpointReference appliesTo;

            try
            {
                appliesTo = new EndpointReference(tokenRequest.Scope);
                Tracing.Information("OAuth2 endpoint called for scope: " + tokenRequest.Scope);
            }
            catch
            {
                Tracing.Error("Malformed scope: " + tokenRequest.Scope);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidScope));
            }

            // check grant type
            if (string.Equals(tokenRequest.Grant_Type, OAuth2Constants.GrantTypes.Password, System.StringComparison.Ordinal))
            {
                if (ConfigurationRepository.OAuth2.EnableResourceOwnerFlow)
                {
                    if (client.AllowResourceOwnerFlow)
                    {
                        return(ProcessResourceOwnerCredentialRequest(tokenRequest.UserName, tokenRequest.Password, appliesTo, tokenType, client));
                    }
                    else
                    {
                        Tracing.Error("Client is not allowed to use the resource owner password flow:" + client.Name);
                    }
                }
            }

            Tracing.Error("invalid grant type: " + tokenRequest.Grant_Type);
            return(OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType));
        }
Ejemplo n.º 8
0
        public ActionResult Issue(string realm, string tokenType)
        {
            Tracing.Verbose("JSNotify endpoint called.");

            if (!ConfigurationRepository.Endpoints.JSNotify)
            {
                Tracing.Warning("JSNotify endpoint called, but disabled in configuration");
                return(new HttpNotFoundResult());
            }

            Tracing.Information("JSNotify endpoint called for realm: " + realm);

            if (tokenType == null)
            {
                tokenType = SimpleWebToken.OasisTokenProfile;
            }

            Tracing.Information("Token type: " + tokenType);

            Uri uri;

            if (!Uri.TryCreate(realm, UriKind.Absolute, out uri))
            {
                Tracing.Error("Realm parameter is malformed.");
                return(new HttpStatusCodeResult(400));
            }

            var endpoint = new EndpointAddress(uri);
            var auth     = new AuthenticationHelper();

            TokenResponse response;

            if (auth.TryIssueToken(endpoint, Thread.CurrentPrincipal as IClaimsPrincipal, tokenType, out response))
            {
                var jsresponse = new AccessTokenResponse
                {
                    AccessToken = response.TokenString,
                    TokenType   = response.TokenType,
                    ExpiresIn   = ConfigurationRepository.Configuration.DefaultTokenLifetime * 60
                };

                Tracing.Information("JSNotify issue successful for user: " + User.Identity.Name);
                return(new JSNotifyResult(jsresponse));
            }
            else
            {
                return(new HttpStatusCodeResult(400));
            }
        }
Ejemplo n.º 9
0
        public virtual void SignOut()
        {
            Tracing.Information(String.Format("[ClaimsBasedAuthenticationService.SignOut] called: {0}", ClaimsPrincipal.Current.Claims.GetValue(ClaimTypes.NameIdentifier)));

            // clear cookie
            var sam = FederatedAuthentication.SessionAuthenticationModule;

            if (sam == null)
            {
                Tracing.Verbose("[ClaimsBasedAuthenticationService.Signout] SessionAuthenticationModule is not configured");
                throw new Exception("SessionAuthenticationModule is not configured and it needs to be.");
            }

            sam.SignOut();
        }
Ejemplo n.º 10
0
        protected virtual void AnalyzeEncryption(RequestDetails details)
        {
            if (details.EncryptingCertificate == null)
            {
                X509Certificate2 requestCertificate;
                if (TryGetEncryptionCertificateFromRequest(details.Realm, out requestCertificate))
                {
                    details.EncryptingCertificate = requestCertificate;
                    Tracing.Information("Encrypting certificate set from RST");
                }
            }

            details.UsesEncryption = (details.EncryptingCertificate != null);
            Tracing.Information("Token encryption: " + details.UsesEncryption);
        }
        public ActionResult HandleRequest(AuthorizeRequest request)
        {
            Tracing.Information("OAuth2 HandleRequest endpoint invoked");

            // check client
            Client client;
            var    error = CheckRequest(request, out client);

            if (error != null)
            {
                return(error);
            }

            RelyingParty rp;

            if (!RPRepository.TryGet(request.scope, out rp))
            {
                Tracing.Error("RP not found for scope : " + request.scope);
                return(ClientError(client.RedirectUri, OAuth2Constants.Errors.InvalidScope, request.response_type, request.state));
            }

            if (Configuration.OAuth2.EnableConsent)
            {
                // show resource name, uri and client name
                // client is trying to access resource on your behalf
                var vm = new OAuth2ConsentViewModel
                {
                    ResourceUri         = rp.Realm.AbsoluteUri,
                    ResourceName        = rp.Name,
                    ClientName          = client.ClientId,
                    RefreshTokenEnabled = client.AllowRefreshToken
                };

                return(View("ShowConsent", vm));
            }
            else
            {
                var grantResult = PerformGrant(request, client);
                if (grantResult != null)
                {
                    return(grantResult);
                }
            }

            // we don't know exactly why, so use ServerError
            Tracing.Error("Authorization Endpoint failed");
            return(ClientError(client.RedirectUri, OAuth2Constants.Errors.ServerError, request.response_type, request.state));
        }
Ejemplo n.º 12
0
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            Tracing.Information("Simple HTTP endpoint called.");

            var query = request.GetQueryNameValuePairs();
            var auth  = new AuthenticationHelper();

            var realm     = query.FirstOrDefault(p => p.Key.Equals("realm", System.StringComparison.OrdinalIgnoreCase)).Value;
            var tokenType = query.FirstOrDefault(p => p.Key.Equals("tokenType", System.StringComparison.OrdinalIgnoreCase)).Value;

            if (string.IsNullOrWhiteSpace(realm))
            {
                return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "realm parameter is missing."));
            }

            EndpointReference appliesTo;

            try
            {
                appliesTo = new EndpointReference(realm);
                Tracing.Information("Simple HTTP endpoint called for realm: " + realm);
            }
            catch
            {
                Tracing.Error("Malformed realm: " + realm);
                return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "malformed realm name."));
            }

            if (string.IsNullOrWhiteSpace(tokenType))
            {
                tokenType = ConfigurationRepository.Global.DefaultHttpTokenType;
            }

            Tracing.Verbose("Token type: " + tokenType);

            TokenResponse tokenResponse;
            var           sts = new STS();

            if (sts.TryIssueToken(appliesTo, ClaimsPrincipal.Current, tokenType, out tokenResponse))
            {
                var resp = request.CreateResponse <TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return(resp);
            }
            else
            {
                return(request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid request."));
            }
        }
Ejemplo n.º 13
0
        private bool IsMacValid()
        {
            byte[] data = this.normalizedRequest.ToBytes();
            // data, at this point has the hash coming in over the wire and hence mac computed is
            // based on the hash over the wire and not over the computed hash

            bool isMacValid = this.hasher.IsValidMac(data, credential.Key, artifacts.Mac);

            if (!isMacValid)
            {
                Tracing.Information(
                    String.Format("Invalid Mac {0} for data {1}", artifacts.Mac.ToBase64String(),
                                  Encoding.UTF8.GetString(data)));
            }
            return(isMacValid);
        }
Ejemplo n.º 14
0
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(string userName, string password, EndpointReference appliesTo, string tokenType, Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            var             auth = new AuthenticationHelper();
            ClaimsPrincipal principal;

            if (UserRepository.ValidateUser(userName, password))
            {
                principal = auth.CreatePrincipal(userName, "OAuth2",
                                                 new Claim[]
                {
                    new Claim(Constants.Claims.Client, client.Name),
                    new Claim(Constants.Claims.Scope, appliesTo.Uri.AbsoluteUri)
                });

                if (!ClaimsAuthorization.CheckAccess(principal, Constants.Actions.Issue, Constants.Resources.OAuth2))
                {
                    Tracing.Error("OAuth2 endpoint authorization failed for user: "******"Resource owner credential validation failed: " + userName);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            var           sts = new STS();
            TokenResponse tokenResponse;

            if (sts.TryIssueToken(appliesTo, principal, tokenType, out tokenResponse))
            {
                var resp = Request.CreateResponse <TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return(resp);
            }
            else
            {
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest));
            }
        }
Ejemplo n.º 15
0
        private async Task <bool> IsHashValidAsync(HttpContent payload)
        {
            var normalizedPayload = new NormalizedPayload(payload);

            byte[] data = await normalizedPayload.ToBytesAsync();

            bool isHashValid = this.hasher.IsValidHash(data, artifacts.PayloadHash);

            if (!isHashValid)
            {
                Tracing.Information(
                    String.Format("Invalid payload hash {0} for data {1}", artifacts.PayloadHash.ToBase64String(),
                                  Encoding.UTF8.GetString(data)));
            }

            return(isHashValid);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Returns true if the timestamp sent in by the client is fresh subject to the
        /// maximum allowed skew and the adjustment offset.
        /// </summary>
        private static bool IsTimestampFresh(ulong now, ArtifactsContainer artifacts, Options options)
        {
            now = now + Convert.ToUInt64(options.LocalTimeOffsetMillis);

            ulong shelfLife = (Convert.ToUInt64(options.ClockSkewSeconds) * 1000);
            var   age       = Math.Abs((artifacts.Timestamp * 1000.0) - now);

            bool isFresh = (age <= shelfLife);

            if (!isFresh)
            {
                Tracing.Information(
                    String.Format("Stale Timestamp: Age {0} is more than shelf life of {1}", age, shelfLife));
            }

            return(isFresh);
        }
        public ClaimsPrincipal Validate(string userName, string password)
        {
            var binding     = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var credentials = new ClientCredentials();

            credentials.UserName.UserName = userName;
            credentials.UserName.Password = password;

            GenericXmlSecurityToken genericToken;

            try
            {
                genericToken = WSTrustClient.Issue(
                    new EndpointAddress(_address),
                    new EndpointAddress(_realm),
                    binding,
                    credentials) as GenericXmlSecurityToken;
            }
            catch (MessageSecurityException ex)
            {
                Tracing.Error("WSTrustResourceOwnerCredentialValidation failed: " + ex.ToString());
                return(null);
            }

            var config = new SecurityTokenHandlerConfiguration();

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(_realm));

            config.CertificateValidationMode = X509CertificateValidationMode.None;
            config.CertificateValidator      = X509CertificateValidator.None;

            var registry = new ConfigurationBasedIssuerNameRegistry();

            registry.AddTrustedIssuer(_issuerThumbprint, _address);
            config.IssuerNameRegistry = registry;

            var handler = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection(config);

            ClaimsPrincipal principal;
            var             token = genericToken.ToSecurityToken();

            principal = new ClaimsPrincipal(handler.ValidateToken(token));

            Tracing.Information("Successfully requested token for user via WS-Trust");
            return(FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager.Authenticate("ResourceOwnerPasswordValidation", principal));
        }
        public override ReadOnlyCollection <ClaimsIdentity> ValidateToken(SecurityToken token)
        {
            this.Configuration.IssuerNameRegistry = new ClientCertificateIssuerNameRegistry();

            Tracing.Information("Beginning client certificate token validation and authentication for SOAP");
            Container.Current.SatisfyImportsOnce(this);

            // call base class implementation for validation and claims generation
            var identity = base.ValidateToken(token).First();

            // retrieve thumbprint
            var clientCert = ((X509SecurityToken)token).Certificate;

            Tracing.Information(String.Format("Client certificate thumbprint: {0}", clientCert.Thumbprint));

            // check if mapped user exists
            string userName;

            if (!UserRepository.ValidateUser(clientCert, out userName))
            {
                var message = String.Format("No mapped user exists for thumbprint {0}", clientCert.Thumbprint);
                Tracing.Error(message);
                throw new SecurityTokenValidationException(message);
            }

            Tracing.Information(String.Format("Mapped user found: {0}", userName));

            // retrieve issuer name
            var issuer = identity.Claims.First().Issuer;

            Tracing.Information(String.Format("Certificate issuer: {0}", issuer));

            // create new ClaimsIdentity for the STS issuance logic
            var claims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, userName),
                new Claim(ClaimTypes.AuthenticationMethod, AuthenticationMethods.X509),
                new Claim(ClaimTypes.AuthenticationInstant, identity.FindFirst(ClaimTypes.AuthenticationInstant).Value)
            };

            var id = new ClaimsIdentity(claims, "Client Certificate");

            return(new List <ClaimsIdentity> {
                id
            }.AsReadOnly());
        }
Ejemplo n.º 19
0
        public void Validate(RequestDetails details)
        {
            if (details == null)
            {
                throw new ArgumentNullException("details");
            }

            Tracing.Information("Starting policy validation");

            ValidateKnownRealm(details);
            ValidateRelyingParty(details);
            ValidateReplyTo(details);
            ValidateEncryption(details);
            ValidateDelegation(details);

            Tracing.Information("Policy Validation succeeded");
        }
Ejemplo n.º 20
0
        private bool IsHashValid(string body, string contentType)
        {
            var normalizedPayload = new NormalizedPayload(body, contentType);

            byte[] data = normalizedPayload.ToBytes();

            bool isHashValid = this.hasher.IsValidHash(data, artifacts.PayloadHash);

            if (!isHashValid)
            {
                Tracing.Information(
                    String.Format("Invalid payload hash {0} for data {1}", artifacts.PayloadHash.ToBase64String(),
                                  Encoding.UTF8.GetString(data)));
            }

            return(isHashValid);
        }
Ejemplo n.º 21
0
        private HttpResponseMessage ProcessSamlRequest(TokenRequest request)
        {
            if (string.IsNullOrEmpty(request.Assertion))
            {
                Tracing.Error("ADFS integration SAML authentication request with empty assertion");
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            // un-base64 saml token string
            string incomingSamlToken;

            try
            {
                incomingSamlToken = Encoding.UTF8.GetString(Convert.FromBase64String(request.Assertion));
            }
            catch
            {
                Tracing.Error("ADFS integration SAML authentication request with malformed SAML assertion: " +
                              request.Assertion);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            Tracing.Information("Starting ADFS integration SAML authentication request for scope: " + request.Scope);

            var bridge = new AdfsBridge(ConfigurationRepository);
            GenericXmlSecurityToken token;

            try
            {
                Tracing.Verbose("ADFS integration SAML authentication request for assertion: " + request.Assertion);

                token = bridge.AuthenticateSaml(incomingSamlToken, request.Scope);
            }
            catch (Exception ex)
            {
                Tracing.Error("Error while communicating with ADFS: " + ex);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest));
            }

            var response = CreateTokenResponse(token, request.Scope);

            Tracing.Verbose("ADFS integration SAML authentication request successful");

            return(response);
        }
 private static void Trace(string source, string name, string value)
 {
     if (value == null)
     {
         Tracing.Information(
             "Did not find configuration setting {0} in {1}.",
             name,
             source);
     }
     else
     {
         Tracing.Information(
             "Found configuration setting {0} in {1} with value '{2}'.",
             name,
             source,
             value);
     }
 }
        /// <summary>
        /// Produces the output identity that gets transformed into a token
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="request">The request.</param>
        /// <param name="scope">The scope.</param>
        /// <returns>An IClaimsIdentity describing the subject</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var requestDetails = (scope as RequestDetailsScope).RequestDetails;

            var userClaims     = GetOutputClaims(principal, requestDetails, ClaimsRepository);
            var outputIdentity = new ClaimsIdentity(userClaims);

            if (requestDetails.IsActAsRequest)
            {
                Tracing.Information("Issuing act as token");
                return(GetActAsClaimsIdentity(outputIdentity, requestDetails));
            }
            else
            {
                Tracing.Information("Issuing identity token");
                return(outputIdentity);
            }
        }
Ejemplo n.º 24
0
        protected virtual void AnalyzeRequestClaims(RequestDetails details)
        {
            // check if specific claims are requested
            if (details.Request.Claims != null && details.Request.Claims.Count > 0)
            {
                details.ClaimsRequested = true;
                details.RequestClaims   = details.Request.Claims;

                var requestClaims = new StringBuilder(20);
                details.RequestClaims.ToList().ForEach(rq => requestClaims.AppendFormat("{0}\n", rq.ClaimType));
                Tracing.Information("Specific claims requested");
                Tracing.Information(String.Format("Request claims: {0}", requestClaims));
            }
            else
            {
                Tracing.Information("No request claims");
            }
        }
        private void LogTableStorageOperationInvoking(
            string tableUri,
            long contentLength        = default(long),
            string storageAccountName = default(string))
        {
            string format = "For table '{0}', begin invoking operation '{1}', individualRequestId '{2}', length '{3}', storage account '{4}'";

            string message = string.Format(
                CultureInfo.InvariantCulture,
                format,
                tableUri,
                this.operationName,
                this.requestId,
                contentLength,
                storageAccountName);

            Tracing.Information(message);
        }
        /// <summary>
        /// Returns a ClaimsPrincipal object with the NameIdentifier and Name claims, if the request can be
        /// successfully authenticated based on query string parameter bewit or HTTP Authorization header (hawk scheme).
        /// </summary>
        public async Task <ClaimsPrincipal> AuthenticateAsync()
        {
            string bewit;
            bool   isBewit = Bewit.TryGetBewit(this.request, out bewit);

            if (isBewit)
            {
                Tracing.Information("Bewit Found");
            }

            var authentication = isBewit ?
                                 Bewit.AuthenticateAsync(bewit, now, request, credentialsFunc) :
                                 HawkSchemeHeader.AuthenticateAsync(now, request, credentialsFunc);

            this.result = await authentication;

            if (result.IsAuthentic)
            {
                // At this point, authentication is successful but make sure the request parts match what is in the
                // application specific data 'ext' parameter by invoking the callback passing in the request object and 'ext'.
                // The application specific data is considered verified, if the callback is not set or it returns true.
                bool isAppSpecificDataVerified = this.verificationCallback == null ||
                                                 this.verificationCallback(request, result.ApplicationSpecificData);

                if (isAppSpecificDataVerified)
                {
                    // Set the flag so that Server-Authorization header is not sent for bewit requests.
                    this.isBewitRequest = isBewit;

                    var idClaim   = new Claim(ClaimTypes.NameIdentifier, result.Credential.Id);
                    var nameClaim = new Claim(ClaimTypes.Name, result.Credential.User);

                    var identity = new ClaimsIdentity(new[] { idClaim, nameClaim }, HawkConstants.Scheme);

                    return(new ClaimsPrincipal(identity));
                }
                else
                {
                    Tracing.Information("Invalid Application Specific Data, though authentication is successful.");
                }
            }

            return(Principal.Anonymous);
        }
Ejemplo n.º 27
0
        public virtual void SignIn(UserAccount account, string method, bool persistent = false)
        {
            if (account == null)
            {
                throw new ArgumentNullException("account");
            }
            if (String.IsNullOrWhiteSpace(method))
            {
                throw new ArgumentNullException("method");
            }

            Tracing.Information("[AuthenticationService.SignIn] sign in called: {0}", account.ID);

            if (!account.IsLoginAllowed || account.IsAccountClosed)
            {
                throw new ValidationException(UserAccountService.GetValidationMessage(AppConstants.ValidationMessages.LoginNotAllowed));
            }

            if (!account.IsAccountVerified && UserAccountService.Configuration.RequireAccountVerification)
            {
                throw new ValidationException(UserAccountService.GetValidationMessage(AppConstants.ValidationMessages.AccountNotVerified));
            }

            // gather claims
            var claims = GetAllClaims(account, method);

            // get custom claims from properties
            claims.AddRange(UserAccountService.MapClaims(account));

            // create principal/identity
            var id = new ClaimsIdentity(claims, method);
            var cp = new ClaimsPrincipal(id);

            // claims transform
            if (ClaimsAuthenticationManager != null)
            {
                cp = ClaimsAuthenticationManager.Authenticate(String.Empty, cp);
            }

            // issue cookie
            Tracing.Verbose("[AuthenticationService.SignIn] token issued: {0}", account.ID);
            IssueToken(cp, persistentCookie: persistent);
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(ValidatedRequest validatedRequest)
        {
            Tracing.Information("Processing resource owner credential request");

            ClaimsPrincipal principal;

            try
            {
                principal = _rocv.Validate(validatedRequest.UserName, validatedRequest.Password);
            }
            catch (Exception ex)
            {
                Tracing.Error("Resource owner credential validation failed: " + ex.ToString());
                throw;
            }

            if (principal != null && principal.Identity.IsAuthenticated)
            {
                var sts      = new TokenService(this._config.GlobalConfiguration);
                var response = sts.CreateTokenResponse(validatedRequest, principal);

                // check if refresh token is enabled for the client
                if (validatedRequest.Client.AllowRefreshToken && validatedRequest.Application.AllowRefreshToken)
                {
                    var handle = StoredGrant.CreateRefreshTokenHandle(
                        principal.GetSubject(),
                        validatedRequest.Client,
                        validatedRequest.Application,
                        principal.Claims,
                        validatedRequest.Scopes,
                        DateTime.UtcNow.AddYears(5));

                    _handleManager.Add(handle);
                    response.RefreshToken = handle.GrantId;
                }

                return(Request.CreateTokenResponse(response));
            }
            else
            {
                return(Request.CreateOAuthErrorResponse(OAuthConstants.Errors.InvalidGrant));
            }
        }
Ejemplo n.º 29
0
        public virtual void SetPassword(string tenant, string username, string newPassword)
        {
            Tracing.Information(String.Format("[UserAccountService.SetPassword] called: {0}, {1}", tenant, username));

            if (!_settings.MultiTenant)
            {
                tenant = _settings.DefaultTenant;
            }

            if (String.IsNullOrWhiteSpace(tenant))
            {
                throw new ValidationException("Invalid tenant.");
            }
            if (String.IsNullOrWhiteSpace(username))
            {
                throw new ValidationException("Invalid username.");
            }
            if (String.IsNullOrWhiteSpace(newPassword))
            {
                throw new ValidationException("Invalid newPassword.");
            }

            ValidatePassword(tenant, username, newPassword);

            var account = this.GetByUsername(tenant, username);

            if (account == null)
            {
                throw new ValidationException("Invalid tenant and/or username.");
            }

            Tracing.Information(String.Format("[UserAccountService.SetPassword] setting new password for: {0}, {1}", tenant, username));

            account.SetPassword(newPassword);
            this.userRepository.SaveOrUpdate(account);

            if (this.notificationService != null)
            {
                this.notificationService.SendPasswordChangeNotice(account);
            }

            _unitOfWork.Commit();
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(TokenRequest request, string tokenType,
                                                                          Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);
            var appliesTo = new EndpointReference(request.Scope);

            if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
            }

            if (UserRepository.ValidateUser(request.UserName, request.Password))
            {
                return(CreateTokenResponse(request.UserName, client, appliesTo, tokenType, client.AllowRefreshToken));
            }
            Tracing.Error("Resource owner credential validation failed: " + request.UserName);
            return(OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant));
        }