/// <summary>
        /// Converts the specified HTTP request data into a standard form appropriate for signing.
        /// </summary>
        /// <param name="request">The HTTP request that needs to be signed.</param>
        /// <param name="accountName">The name of the storage account that the HTTP request will access.</param>
        /// <returns>The canonicalized string containing the HTTP request data in a standard form appropriate for signing.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx">Authentication for the Windows Azure Storage Services</seealso>
        public string CanonicalizeHttpRequest(HttpWebRequest request, string accountName)
        {
            CommonUtility.AssertNotNull("request", request);

            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method);

            // Add the Content-* HTTP headers. Empty values are allowed.
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.ContentEncoding]);
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.ContentLanguage]);
            AuthenticationUtility.AppendCanonicalizedContentLengthHeader(canonicalizedString, request);
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.ContentMd5]);
            canonicalizedString.AppendCanonicalizedElement(request.ContentType);

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add If-* headers and Range header
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.IfModifiedSince]);
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.IfMatch]);
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.IfNoneMatch]);
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.IfUnmodifiedSince]);
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.Range]);

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
示例#2
0
        /// <summary>
        /// Converts the specified HTTP request data into a standard form appropriate for signing.
        /// </summary>
        /// <param name="request">The HTTP request that needs to be signed.</param>
        /// <param name="accountName">The name of the storage account that the HTTP request will access.</param>
        /// <returns>The canonicalized string containing the HTTP request data in a standard form appropriate for signing.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/Azure/dd179428.aspx">Authentication for the Microsoft Azure Storage Services</seealso>
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            CommonUtility.AssertNotNull("request", request);

            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method.Method, ExpectedCanonicalizedStringLength);

            // Add the Content-* HTTP headers. Empty values are allowed.
            if (request.Content != null)
            {
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentMD5 == null) ? null :
                                                               Convert.ToBase64String(request.Content.Headers.ContentMD5));
                //canonicalizedString.AppendCanonicalizedElement(HttpRequestParsers.GetContentCRC64(request)); // should be covered by custom headers
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentType == null) ? null :
                                                               request.Content.Headers.ContentType.ToString());
            }
            else
            {
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
            }

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
示例#3
0
        public EmployeeMutation(IEmployeeRepository employeeRepository, IDbContextScopeFactory dbContextScope)
        {
            _authUtility = new AuthenticationUtility();

            FieldAsync <EmployeeType>("addEmployee",
                                      arguments: new QueryArguments {
                new QueryArgument <NonNullGraphType <AddEmployeeType> > {
                    Name = "employeeData"
                }
            },
                                      resolve: async context =>
            {
                if (!_authUtility.ValidateContext(context))
                {
                    throw new ExecutionError("ErrorCode: UNAUTHORIZED_USER, Message: 401 Unautherized error.");
                }

                AddEmployeeDataModel employeeData = context.GetArgument <AddEmployeeDataModel>("employeeData");

                using (dbContextScope.Create(DbContextScopeOption.ForceCreateNew))
                {
                    return(await employeeRepository.AddEmployee(employeeData));
                }
            });
        }
示例#4
0
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method.Method, ExpectedCanonicalizedStringLength);

            // Add the Content-* HTTP headers. Empty values are allowed.
            if (request.Content != null)
            {
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentMD5 == null) ? null :
                                                               Convert.ToBase64String(request.Content.Headers.ContentMD5));
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentType == null) ? null :
                                                               request.Content.Headers.ContentType.ToString());
            }
            else
            {
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
            }

            // Add the Date HTTP header (or the x-ms-date header if it is being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request, true);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
示例#5
0
        public static PayloadData Create(InitialHandshakePayload handshake, ConnectionSettings cs, bool useCompression, CharacterSet characterSet, byte[] connectionAttributes)
        {
            // TODO: verify server capabilities
            var writer = CreateCapabilitiesPayload(handshake.ProtocolCapabilities, cs, useCompression, characterSet);

            writer.WriteNullTerminatedString(cs.UserID);
            var authenticationResponse = AuthenticationUtility.CreateAuthenticationResponse(handshake.AuthPluginData, 0, cs.Password);

            writer.Write((byte)authenticationResponse.Length);
            writer.Write(authenticationResponse);

            if (!string.IsNullOrWhiteSpace(cs.Database))
            {
                writer.WriteNullTerminatedString(cs.Database);
            }

            if ((handshake.ProtocolCapabilities & ProtocolCapabilities.PluginAuth) != 0)
            {
                writer.WriteNullTerminatedString("mysql_native_password");
            }

            if (connectionAttributes != null)
            {
                writer.Write(connectionAttributes);
            }

            return(writer.ToPayloadData());
        }
        /// <summary>The receive async.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        /// <exception cref="Exception"></exception>
        public async Task ReceiveAsync(AuthenticationTokenReceiveContext context)
        {
            try
            {
                var allowedOrigin = context.OwinContext.Get <string>("as:clientAllowedOrigin");
                if (!context.OwinContext.Response.Headers.ContainsKey("Access-Control-Allow-Origin"))
                {
                    context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { allowedOrigin });
                }

                var hashedTokenId = AuthenticationUtility.GetHash(context.Token);

                var refreshTokenController = AuthHelper.FindRefreshTokenController(hashedTokenId);
                var refreshTokenDict       = await this.authFacade.SelectAll(refreshTokenController);

                var refreshToken = refreshTokenDict.Values.FirstOrDefault();

                if (refreshToken != null)
                {
                    // Get protectedTicket from refreshToken class
                    context.DeserializeTicket(refreshToken.ProtectedTicket);

                    // var expires = context.Ticket.Properties.ExpiresUtc;
                    await this.authFacade.Delete(new List <long> {
                        refreshToken.Id
                    });
                }
            }
            catch (System.Exception ex)
            {
                throw new System.Exception("some error occured while reading the refersh token", ex);
            }
        }
        public void ProcessRequest(HttpContext context)
        {
            AuthenticationResponse response = AuthenticationUtility.HandleResponse();

            if (response.IDTokenPayload.IssueTimestamp.ToLocalTime() > DateTime.Now && response.IDTokenPayload.ExpirationTimestamp.ToLocalTime() > DateTime.Now)
            {
                //The token is expired or not valid anymore, go back to Root of application now
                context.Response.Redirect("~/", true);
            }

            /*
             *      Use the E-Mail address of the user as an identifier for demonstration purposes
             *      Note: you may want to use response.IDTokenPayload.UserUniqueIdentifier instead
             *      that represents the sub parameter as google recommends to do so. See
             *      the "sub" parameter description at "An ID token's payload":
             *      https://developers.google.com/accounts/docs/OpenIDConnect#obtainuserinfo
             *      Before you call SetAuthCookie method, you could also do some additional authorization
             *      checks with the given user information.
             */
            FormsAuthentication.SetAuthCookie(response.IDTokenPayload.Email, false);

            context.Session["UserInformation"] = response.UserInformation;

            //We've but the redirect url in the state before authenticating, so let's go back there now
            context.Response.Redirect(response.State, true);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            AuthenticationRequest authenticationRequest = new AuthenticationRequest(Scope.OpenID | Scope.Email | Scope.Profile);

            authenticationRequest.State = Request.Params["ReturnUrl"];
            AuthenticationUtility.Authenticate(authenticationRequest);
        }
        public RedirectResult LogOn(string federationLocation)
        {
            var module = AuthenticationUtility.CurrentModuleProvider.GetModule();
            var realm  = AuthenticationUtility.GetApplicationUri(HttpContext.Request);

            AuthenticationUtility.EnsureRealmAudienceUri(module, realm);
            return(new RedirectResult(federationLocation));
        }
        public ViewResult Login()
        {
            LoginModel model = new LoginModel();

            model.Realm     = AuthenticationUtility.GetApplicationUri(HttpContext.Request);
            model.Namespace = CloudConfigurationManager.GetSetting("AcsNamespace");
            return(View(model));
        }
示例#11
0
 public AuthController(
     TimeishContext context,
     IConfiguration configuration,
     AuthenticationUtility authUtil)
 {
     _context       = context;
     _configuration = configuration;
     _authUtil      = authUtil;
 }
        public void WhenIViewLogin_ThenViewModelRealmIsApplicationUrl()
        {
            string expected = AuthenticationUtility.GetApplicationUri(MockHttpContext.Request);

            ViewResult result = Target.Login();

            LoginModel actual = result.AssertGetViewModel <LoginModel>();

            Assert.AreEqual(expected, actual.Realm);
        }
示例#13
0
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method.Method);

            // Add the Content-* HTTP headers. Empty values are allowed.
            if (request.Content != null)
            {
                canonicalizedString.AppendCanonicalizedElement(HttpWebUtility.CombineHttpHeaderValues(request.Content.Headers.ContentEncoding));
                canonicalizedString.AppendCanonicalizedElement(HttpWebUtility.CombineHttpHeaderValues(request.Content.Headers.ContentLanguage));
                AuthenticationUtility.AppendCanonicalizedContentLengthHeader(canonicalizedString, request);
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentMD5 == null) ? null :
                                                               Convert.ToBase64String(request.Content.Headers.ContentMD5));
                canonicalizedString.AppendCanonicalizedElement((request.Content.Headers.ContentType == null) ? null :
                                                               request.Content.Headers.ContentType.ToString());
            }
            else
            {
                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
                if (request.Method == HttpMethod.Put || request.Method == HttpMethod.Delete)
                {
                    canonicalizedString.AppendCanonicalizedElement("0");
                }
                else
                {
                    canonicalizedString.AppendCanonicalizedElement(null);
                }

                canonicalizedString.AppendCanonicalizedElement(null);
                canonicalizedString.AppendCanonicalizedElement(null);
            }

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add If-* headers and Range header
            canonicalizedString.AppendCanonicalizedElement(AuthenticationUtility.GetCanonicalizedHeaderValue(request.Headers.IfModifiedSince));
            canonicalizedString.AppendCanonicalizedElement(CommonUtility.GetFirstHeaderValue(request.Headers.IfMatch));
            canonicalizedString.AppendCanonicalizedElement(CommonUtility.GetFirstHeaderValue(request.Headers.IfNoneMatch));
            canonicalizedString.AppendCanonicalizedElement(AuthenticationUtility.GetCanonicalizedHeaderValue(request.Headers.IfUnmodifiedSince));
            canonicalizedString.AppendCanonicalizedElement((request.Headers.Range == null) ? null :
                                                           CommonUtility.GetFirstHeaderValue(request.Headers.Range.Ranges));

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
示例#14
0
        public HttpResponseMessage Login([FromBody] LoginInfo login)
        {
            var token = AuthenticationUtility.AuthenticateUser(login.Username, login.Password, out int userID);

            if (token != null)
            {
                return(Request.CreateResponse(HttpStatusCode.OK, new { token, userID }));
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }
        }
        public string CanonicalizeHttpRequest(HttpRequestMessage request, string accountName)
        {
            // Add the Date HTTP header (or the x-ms-date header if it is being used)
            string dateHeaderValue = AuthenticationUtility.GetPreferredDateHeaderValue(request);
            CanonicalizedString canonicalizedString = new CanonicalizedString(dateHeaderValue, ExpectedCanonicalizedStringLength);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
示例#16
0
        public async Task <bool> TryResetConnectionAsync(ConnectionSettings cs, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            VerifyState(State.Connected);

            try
            {
                if (ServerVersion.Version.CompareTo(ServerVersions.SupportsResetConnection) >= 0)
                {
                    await SendAsync(ResetConnectionPayload.Create(), ioBehavior, cancellationToken).ConfigureAwait(false);

                    var payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

                    OkPayload.Create(payload);

                    // the "reset connection" packet also resets the connection charset, so we need to change that back to our default
                    payload = QueryPayload.Create("SET NAMES utf8mb4 COLLATE utf8mb4_bin;");
                    await SendAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                    payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

                    OkPayload.Create(payload);
                }
                else
                {
                    // optimistically hash the password with the challenge from the initial handshake (supported by MariaDB; doesn't appear to be supported by MySQL)
                    var hashedPassword = AuthenticationUtility.CreateAuthenticationResponse(AuthPluginData, 0, cs.Password);
                    var payload        = ChangeUserPayload.Create(cs.UserID, hashedPassword, cs.Database, m_supportsConnectionAttributes ? s_connectionAttributes : null);
                    await SendAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                    payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

                    if (payload.HeaderByte == AuthenticationMethodSwitchRequestPayload.Signature)
                    {
                        payload = await SwitchAuthenticationAsync(cs, payload, ioBehavior, cancellationToken).ConfigureAwait(false);
                    }
                    OkPayload.Create(payload);
                }

                return(true);
            }
            catch (IOException)
            {
            }
            catch (SocketException)
            {
            }

            return(false);
        }
        /// <summary>The create async.</summary>
        /// <param name="context">The context.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        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");

            ClaimsIdentity userIdentity   = context.Ticket.Identity;
            var            firstOrDefault = userIdentity.Claims.FirstOrDefault(c => c.Type == "GUID");

            if (firstOrDefault != null)
            {
                var sessionGuid = new Guid(firstOrDefault.Value);

                var refreshTokenLifeTime = context.OwinContext.Get <string>("as:clientRefreshTokenLifeTime");

                var clientController = AuthHelper.FindClientController(clientid);
                var clientAppId      = await this.authFacade.FindClient(clientController);

                var token = new RefreshToken
                {
                    RefreshTokenId     = AuthenticationUtility.GetHash(refreshTokenId),
                    Id                 = clientAppId.Id,
                    UserName           = context.Ticket.Identity.Name,
                    IssuedTimestamp    = DateTime.Now,
                    ExpiryTimestamp    = DateTime.Now.AddMinutes(Convert.ToDouble(refreshTokenLifeTime)),
                    SessionGuId        = sessionGuid,
                    LastModifiedUserId = 1,
                    LastModifiedTs     = DateTime.Now,
                    ClientAppId        = (int)clientAppId.Id,
                };

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

                token.ProtectedTicket = context.SerializeTicket();

                // Create Dictionary with Key : filter and Value is JSON String
                await this.authFacade.Update(new List <RefreshToken> {
                    token
                });

                context.SetToken(refreshTokenId);
            }
        }
示例#18
0
        /// <summary>
        /// Converts the specified HTTP request data into a standard form appropriate for signing.
        /// </summary>
        /// <param name="request">The HTTP request that needs to be signed.</param>
        /// <param name="accountName">The name of the storage account that the HTTP request will access.</param>
        /// <returns>The canonicalized string containing the HTTP request data in a standard form appropriate for signing.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx">Authentication for the Windows Azure Storage Services</seealso>
        public string CanonicalizeHttpRequest(HttpWebRequest request, string accountName)
        {
            CommonUtility.AssertNotNull("request", request);

            // Add the x-ms-date or Date HTTP header
            string dateHeaderValue = AuthenticationUtility.GetPreferredDateHeaderValue(request);
            CanonicalizedString canonicalizedString = new CanonicalizedString(dateHeaderValue, ExpectedCanonicalizedStringLength);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
        public void InitializeTest()
        {
            FakeModuleProvider provider = new FakeModuleProvider();

            MockAuthenticationModule = MockRepository.GenerateMock <WSFederationAuthenticationModule>();
            provider.ModuleToReturn  = MockAuthenticationModule;
            AuthenticationUtility.SetModuleProvider(provider);
            TestUser = new User {
                Id = 20, UserKey = "3u2e2"
            };
            Identity = new ClaimsIdentity();
            MockHttpContext.Request.Expect(m => m.RequestContext).Return(new RequestContext(MockHttpContext, new RouteData()));
            MockHttpContext.Request.Expect(m => m.Url).Return(new Uri("http://tempuri.org"));
            MockAccountManager       = MockRepository.GenerateMock <IAccountManager>();
            Target                   = new AccountController(MockAccountManager);
            Target.ControllerContext = new ControllerContext(MockHttpContext, new RouteData(), Target);
        }
        public void GivenNoClaimsIdentityExists_WhenIAuthenticate_ThenCorrectRedirectResponseIssued()
        {
            AuthorizationContext authorizationContext = CreateAuthorizationContext(true, "whatever");

            authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf");

            WSFederationAuthenticationModule module = new WSFederationAuthenticationModule {
                Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com"
            };
            IAuthenticationModuleProvider provider = MockRepository.GenerateMock <IAuthenticationModuleProvider>();

            provider.Expect(m => m.GetModule()).Return(module);
            AuthenticationUtility.SetModuleProvider(provider);

            Target.OnAuthorization(authorizationContext);
            Assert.IsInstanceOfType(authorizationContext.Result, typeof(RedirectToRouteResult));
            ((RedirectToRouteResult)authorizationContext.Result).AssertActionRedirection("Login", "Account");
        }
        public void GivenNoClaimsIdentityExists_WhenIAuthenticate_ThenNoUserEntityIsSet()
        {
            AuthorizationContext authorizationContext = CreateAuthorizationContext(true, "whatever");

            authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf");

            WSFederationAuthenticationModule module = new WSFederationAuthenticationModule {
                Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com"
            };
            IAuthenticationModuleProvider provider = MockRepository.GenerateMock <IAuthenticationModuleProvider>();

            provider.Expect(m => m.GetModule()).Return(module);
            AuthenticationUtility.SetModuleProvider(provider);

            Target.OnAuthorization(authorizationContext);

            Assert.IsNull(Target.UserEntity);
        }
        /// <summary>
        /// Converts the specified HTTP request data into a standard form appropriate for signing.
        /// </summary>
        /// <param name="request">The HTTP request that needs to be signed.</param>
        /// <param name="accountName">The name of the storage account that the HTTP request will access.</param>
        /// <returns>The canonicalized string containing the HTTP request data in a standard form appropriate for signing.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx">Authentication for the Windows Azure Storage Services</seealso>
        public string CanonicalizeHttpRequest(HttpWebRequest request, string accountName)
        {
            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method, ExpectedCanonicalizedStringLength);

            // Add the Content-* HTTP headers. Empty values are allowed.
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.ContentMd5]);
            canonicalizedString.AppendCanonicalizedElement(request.ContentType);

            // Add the Date HTTP header (or the x-ms-date header if it is being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request, true);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.Address, accountName, true);

            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return(canonicalizedString.ToString());
        }
示例#23
0
        public IHttpActionResult Login([FromBody] LoginInfo login)
        {
            var token = AuthenticationUtility.AuthenticateUser(login.Username, login.Password, out string role, out int userID);

            if (token != null)
            {
                if (role.Equals("admin"))
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new { token, userID })));
                }
                else
                {
                    return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Forbidden)));
                }
            }
            else
            {
                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Unauthorized)));
            }
        }
示例#24
0
 public override void OnAuthorization(HttpActionContext actionContext)
 {
     //base.OnAuthorization(actionContext);
     if (actionContext.Request.Headers.Authorization == null)
     {
         actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
     }
     else
     {
         string authenticationToken = actionContext.Request.Headers.Authorization.Parameter;
         var    user = AuthenticationUtility.VerifyToken(authenticationToken);
         if (user != null)
         {
             Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(user.Username), new string[] { user.Role });
         }
         else
         {
             actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
         }
     }
 }
        public void GivenAnAuthenticatedUserWasAlreadyAuthorized_AndNoClaimsIdentityExists_WhenIAuthenticate_ThenNoUserEntityIsSet()
        {
            string userKey = "whatever";
            AuthorizationContext authorizationContext = CreateAuthorizationContext(false, userKey);

            authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf");
            MockAccountManager.Expect(m => m.EnsureUserEntity(authorizationContext.HttpContext.User.Identity as System.Security.Claims.ClaimsIdentity)).Return(new User());
            Target.OnAuthorization(authorizationContext);
            authorizationContext = CreateAuthorizationContext(true, userKey);
            authorizationContext.HttpContext.Request.Expect(m => m.FilePath).Return("hsdjkfhdkjhsfkjhdkjsf");

            WSFederationAuthenticationModule module = new WSFederationAuthenticationModule {
                Issuer = "http://blah.com", HomeRealm = "http://blah.com", Realm = "http://site.com"
            };
            IAuthenticationModuleProvider provider = MockRepository.GenerateMock <IAuthenticationModuleProvider>();

            provider.Expect(m => m.GetModule()).Return(module);
            AuthenticationUtility.SetModuleProvider(provider);

            Target.OnAuthorization(authorizationContext);

            Assert.IsNull(Target.UserEntity);
        }
        /// <summary>
        /// Converts the specified HTTP request data into a standard form appropriate for signing.
        /// </summary>
        /// <param name="request">The HTTP request that needs to be signed.</param>
        /// <param name="accountName">The name of the storage account that the HTTP request will access.</param>
        /// <returns>The canonicalized string containing the HTTP request data in a standard form appropriate for signing.</returns>
        /// <seealso href="http://msdn.microsoft.com/en-us/library/windowsazure/dd179428.aspx">Authentication for the Windows Azure Storage Services</seealso>
        public string CanonicalizeHttpRequest(HttpWebRequest request, string accountName)
        {
            CommonUtility.AssertNotNull("request", request);

            // Add the method (GET, POST, PUT, or HEAD).
            CanonicalizedString canonicalizedString = new CanonicalizedString(request.Method, ExpectedCanonicalizedStringLength);

            // Add the Content-* HTTP headers. Empty values are allowed.
            canonicalizedString.AppendCanonicalizedElement(request.Headers[HttpRequestHeader.ContentMd5]);
            canonicalizedString.AppendCanonicalizedElement(request.ContentType);

            // Add the Date HTTP header (only if the x-ms-date header is not being used)
            AuthenticationUtility.AppendCanonicalizedDateHeader(canonicalizedString, request);

            // Add any custom headers
            AuthenticationUtility.AppendCanonicalizedCustomHeaders(canonicalizedString, request);

            // Add the canonicalized URI element
            string resourceString = AuthenticationUtility.GetCanonicalizedResourceString(request.RequestUri, accountName, true);
            canonicalizedString.AppendCanonicalizedElement(resourceString);

            return canonicalizedString.ToString();
        }
示例#27
0
        public EmployeeQuery(IEmployeeRepository employeeRepository, IDbContextScopeFactory dbContextScope)
        {
            _authUtility = new AuthenticationUtility();

            FieldAsync <ListGraphType <EmployeeType> >(Name = "employees", resolve: async context =>
            {
                if (!_authUtility.ValidateContext(context))
                {
                    throw new ExecutionError("ErrorCode: UNAUTHORIZED_USER, Message: 401 Unautherized error.");
                }

                using (dbContextScope.CreateReadOnly())
                {
                    return(await employeeRepository.GetEmployees());
                }
            });

            FieldAsync <EmployeeType>(Name = "employee",
                                      arguments: new QueryArguments {
                new QueryArgument <NonNullGraphType <EmployeeFilterType> > {
                    Name = "employeeFilter"
                }
            },
                                      resolve: async context =>
            {
                if (!_authUtility.ValidateContext(context))
                {
                    throw new ExecutionError("ErrorCode: UNAUTHORIZED_USER, Message: 401 Unautherized error.");
                }

                EmployeeModelFilter employeeFilter = context.GetArgument <EmployeeModelFilter>("employeeFilter");
                using (dbContextScope.CreateReadOnly())
                {
                    return(await employeeRepository.GetEmployee(employeeFilter.EmployeeId));
                }
            });
        }
        public static byte[] Create(InitialHandshakePacket handshake, ConnectionSettings cs)
        {
            // TODO: verify server capabilities

            var writer = CreateCapabilitiesPayload(handshake.ProtocolCapabilities, cs);

            writer.WriteNullTerminatedString(cs.UserID);
            var authenticationResponse = AuthenticationUtility.CreateAuthenticationResponse(handshake.AuthPluginData, 0, cs.Password);

            writer.WriteByte((byte)authenticationResponse.Length);
            writer.Write(authenticationResponse);

            if (!string.IsNullOrWhiteSpace(cs.Database))
            {
                writer.WriteNullTerminatedString(cs.Database);
            }

            if ((handshake.ProtocolCapabilities & ProtocolCapabilities.PluginAuth) != 0)
            {
                writer.WriteNullTerminatedString("mysql_native_password");
            }

            return(writer.ToBytes());
        }
        private async Task ResetConnectionAsync(CancellationToken cancellationToken)
        {
            if (m_session.ServerVersion.Version.CompareTo(ServerVersions.SupportsResetConnection) >= 0)
            {
                await m_session.SendAsync(ResetConnectionPayload.Create(), cancellationToken).ConfigureAwait(false);

                var payload = await m_session.ReceiveReplyAsync(cancellationToken).ConfigureAwait(false);

                OkPayload.Create(payload);
            }
            else
            {
                // optimistically hash the password with the challenge from the initial handshake (supported by MariaDB; doesn't appear to be supported by MySQL)
                var hashedPassword = AuthenticationUtility.HashPassword(m_session.AuthPluginData, 0, m_connectionStringBuilder.Password);
                var payload        = ChangeUserPayload.Create(m_connectionStringBuilder.UserID, hashedPassword, m_database);
                await m_session.SendAsync(payload, cancellationToken).ConfigureAwait(false);

                payload = await m_session.ReceiveReplyAsync(cancellationToken).ConfigureAwait(false);

                if (payload.HeaderByte == AuthenticationMethodSwitchRequestPayload.Signature)
                {
                    // if the server didn't support the hashed password; rehash with the new challenge
                    var switchRequest = AuthenticationMethodSwitchRequestPayload.Create(payload);
                    if (switchRequest.Name != "mysql_native_password")
                    {
                        throw new NotSupportedException("Only 'mysql_native_password' authentication method is supported.");
                    }
                    hashedPassword = AuthenticationUtility.HashPassword(switchRequest.Data, 0, m_connectionStringBuilder.Password);
                    payload        = new PayloadData(new ArraySegment <byte>(hashedPassword));
                    await m_session.SendReplyAsync(payload, cancellationToken).ConfigureAwait(false);

                    payload = await m_session.ReceiveReplyAsync(cancellationToken).ConfigureAwait(false);
                }
                OkPayload.Create(payload);
            }
        }
示例#30
0
        private async Task <PayloadData> SwitchAuthenticationAsync(ConnectionSettings cs, PayloadData payload, IOBehavior ioBehavior, CancellationToken cancellationToken)
        {
            // if the server didn't support the hashed password; rehash with the new challenge
            var switchRequest = AuthenticationMethodSwitchRequestPayload.Create(payload);

            switch (switchRequest.Name)
            {
            case "mysql_native_password":
                AuthPluginData = switchRequest.Data;
                var hashedPassword = AuthenticationUtility.CreateAuthenticationResponse(AuthPluginData, 0, cs.Password);
                payload = new PayloadData(hashedPassword);
                await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                return(await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false));

            case "mysql_clear_password":
                if (!m_isSecureConnection)
                {
                    throw new MySqlException("Authentication method '{0}' requires a secure connection.".FormatInvariant(switchRequest.Name));
                }
                payload = new PayloadData(Encoding.UTF8.GetBytes(cs.Password));
                await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                return(await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false));

            case "caching_sha2_password":
                var scrambleBytes = AuthenticationUtility.CreateScrambleResponse(Utility.TrimZeroByte(switchRequest.Data), cs.Password);
                payload = new PayloadData(scrambleBytes);
                await SendReplyAsync(payload, ioBehavior, cancellationToken).ConfigureAwait(false);

                payload = await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false);

                var cachingSha2ServerResponsePayload = CachingSha2ServerResponsePayload.Create(payload);
                if (cachingSha2ServerResponsePayload.Succeeded)
                {
                    return(await ReceiveReplyAsync(ioBehavior, cancellationToken).ConfigureAwait(false));
                }

                goto case "sha256_password";

            case "sha256_password":
                if (!m_isSecureConnection && cs.Password.Length > 1)
                {
#if NET45
                    throw new MySqlException("Authentication method '{0}' requires a secure connection (prior to .NET 4.6).".FormatInvariant(switchRequest.Name));
#else
                    var publicKey = await GetRsaPublicKeyAsync(switchRequest.Name, cs, ioBehavior, cancellationToken).ConfigureAwait(false);

                    return(await SendEncryptedPasswordAsync(switchRequest, publicKey, cs, ioBehavior, cancellationToken).ConfigureAwait(false));
#endif
                }
                else
                {
                    return(await SendClearPasswordAsync(cs, ioBehavior, cancellationToken).ConfigureAwait(false));
                }

            case "mysql_old_password":
                throw new NotSupportedException("'MySQL Server is requesting the insecure pre-4.1 auth mechanism (mysql_old_password). The user password must be upgraded; see https://dev.mysql.com/doc/refman/5.7/en/account-upgrades.html.");

            default:
                throw new NotSupportedException("Authentication method '{0}' is not supported.".FormatInvariant(switchRequest.Name));
            }
        }
        public void JsonWeaklyTypedContractTest()
        {
            var request = HttpWebRequest.Create(ApplyTimeZoneOperationPath);
            request.Headers[OAuthHelper.OAuthHeader] = OAuthHelper.GetAuthenticationHeader();
            request.Method = "POST";

            DateTime inputDateTime = DateTime.Now;
            var requestContract = new
            {
                dateTime = inputDateTime,
                timeZoneOffset = 3
            };
            var requestContractString = JsonConvert.SerializeObject(requestContract);

            using (var stream = request.GetRequestStream())
            {
                using (var writer = new StreamWriter(stream))
                {
                    writer.Write(requestContractString);
                }
            }

            using (var response = (HttpWebResponse)request.GetResponse())
            {
                using (Stream responseStream = response.GetResponseStream())
                {
                    using (StreamReader streamReader = new StreamReader(responseStream))
                    {
                        string responseString = streamReader.ReadToEnd();
                        JToken jsonObject = JToken.Parse(responseString);
                        DateTime appliedTimeZone = jsonObject.Value<DateTime>();

                        Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                        Assert.IsFalse(string.IsNullOrEmpty(responseString));
                        Console.WriteLine(responseString);
                        Assert.IsNotNull(appliedTimeZone);
                        Assert.AreNotEqual(appliedTimeZone.Hour, inputDateTime.Hour);
                    }
                }
            }
        }