Quantcast
Channel: Security
Viewing all 4737 articles
Browse latest View live

The required anti-forgery form field __RequestVerificationToken is not present

$
0
0

Im getting this error

<b> Exception Details: </b>System.Web.Mvc.HttpAntiForgeryException: The required anti-forgery form field &quot;__RequestVerificationToken&quot; is not present.<br><br>

Im using typeahead.js to autocomplete in a text box, but the action method on the controller never gets hit. Ive also used the typeahead.js for mvc 5 models helper. Heres my markup in the view

@Html.AutocompleteFor(model => model.NewUser.End_User_Org, model => model.NewUser.End_User_Org, "GetOrganisations", "User", false, new { htmlAttributes = new { @class = "form-control" } })

this is inside a form where ive declared

@Html.AntiForgeryToken()

and my controller action

[HttpGet]
[ActionName("GetOrganisations")]
[ValidateAntiForgeryToken]
public ActionResult Get(string search)
{
JsonResult result = new JsonResult();
if (!string.IsNullOrEmpty(search))
{
GetOrganisationRequestNonPrimary request = new GetOrganisationRequestNonPrimary(search);
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
var organisations = this._organisationService.OrganisationAutoComplete(request);
result.Data = organisations.Organisations.AsQueryable();
result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
}

return result;
}

at runtime Ive checked the html and I have this

<form id="userForm" class="form-horizontal" method="post" style="" role="form" novalidate="novalidate">
<input name="__RequestVerificationToken" value="actual value here..." type="hidden">

so the antiforgery token is present but why isnt it being sent to the controller action ? Is this a known issue with Typeahead.js and the mvc5 model helpers ?


Web Site Administration Tool time out

$
0
0

how can i extend this tool timeout period

User Authentication in web.config

$
0
0
<?xml version="1.0" encoding="utf-8"?><!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=169433
  --><configuration><configSections><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --><section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" /><sectionGroup name="dotNetOpenAuth" type="DotNetOpenAuth.Configuration.DotNetOpenAuthSection, DotNetOpenAuth.Core"><section name="oauth" type="DotNetOpenAuth.Configuration.OAuthElement, DotNetOpenAuth.OAuth" requirePermission="false" allowLocation="true" /><section name="openid" type="DotNetOpenAuth.Configuration.OpenIdElement, DotNetOpenAuth.OpenId" requirePermission="false" allowLocation="true" /><section name="messaging" type="DotNetOpenAuth.Configuration.MessagingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /><section name="reporting" type="DotNetOpenAuth.Configuration.ReportingElement, DotNetOpenAuth.Core" requirePermission="false" allowLocation="true" /></sectionGroup><!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 --></configSections><connectionStrings><!--<add name="ARTSQLConStrng" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-ARTBASE SYSTEMS Web Application-20150702042901;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-ARTBASE SYSTEMS Web Application-20150702042901.mdf" /> --><add name="ARTSQLConStrng" providerName="System.Data.SqlClient" connectionString="Data Source=EMBRYOLOGIST;Initial Catalog=ARTSQL;Persist Security Info=True;User ID=ARTSQLDB;Password=abumaizer85;Integrated Security=SSPI" /></connectionStrings><system.web><authorization><allow users="*" /></authorization><customErrors mode="On" defaultRedirect="~/ARTSQLAPP/ErrorPages/Oops.aspx"><error statusCode="404" redirect="~/404.html" /></customErrors><trace enabled="true" localOnly="false" pageOutput="false" requestLimit="50" /><httpHandlers><add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" validate="false" /></httpHandlers><compilation debug="true" strict="false" explicit="true" targetFramework="4.5"><assemblies><add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" /><add assembly="System.Web.Extensions.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" /><add assembly="Microsoft.ReportViewer.Common, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" /><add assembly="Microsoft.Build.Framework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" /><add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089" /></assemblies><buildProviders><add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /></buildProviders></compilation><httpRuntime maxRequestLength="1048576" requestValidationMode="2.0" targetFramework="4.5" /><!--maxRequestLength="1048576" add by ARTSQL Nov 1 15 , requestValidationMode="2.0" add by ARTSQL Nov 30 15 --><pages smartNavigation="true" maintainScrollPositionOnPostBack="true"><!--smartNavigation="true" maintainScrollPositionOnPostBack="true" add by ARTSQL Dec 14 15 --><namespaces><add namespace="System.Web.Optimization" /></namespaces><controls><add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" /></controls></pages><authentication mode="Forms"><forms loginUrl="~/login.aspx" defaultUrl="~/Default.aspx" timeout="60"  /></authentication><profile defaultProvider="DefaultProfileProvider"><providers><add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="ARTSQLConStrng" applicationName="/ARTdBASE" description="SqlProvider" /></providers><properties><add name="ZipCode" /><add name="CityAndState" /></properties></profile><membership defaultProvider="SqlProvider" userIsOnlineTimeWindow="15"><providers><add connectionStringName="ARTSQLConStrng" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="true" requiresUniqueEmail="true" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" passwordFormat="Hashed" passwordStrengthRegularExpression="(?=.{6,})(?=(.*\d){1,})(?=(.*\W){1,})" applicationName="/ARTdBASE" name="SqlProvider" type="System.Web.Security.SqlMembershipProvider" /></providers></membership><!--<providers><add connectionStringName="ARTSQLConStrng" applicationName="ARTBASE"
          name="DefaultRoleProvider" type="System.Web.Providers.DefaultRoleProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /></providers>--><roleManager enabled="true" defaultProvider="SqlProvider"><providers><clear /><add connectionStringName="ARTSQLConStrng" applicationName="/ARTdBASE"
          name="SqlProvider" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /><add applicationName="/ARTdBASE" name="AspNetWindowsTokenRoleProvider"
          type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" /></providers></roleManager><!--
            If you are deploying to a cloud environment that has multiple web server instances,
            you should change session state mode from "InProc" to "Custom". In addition,
            change the connection string named "ARTSQLConStrng" to connect to an instance
            of SQL Server (including SQL Azure and SQL  Compact) instead of to SQL Server Express.
      --><sessionState mode="InProc" customProvider="SqlProvider" timeout="39"><providers><add name="SqlProvider" applicationName="/ARTdBASE" cookieless="false" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="ARTSQLConStrng" /></providers></sessionState></system.web><!--<location path="Default.aspx"><system.web><compilation debug="true"><assemblies>
          --><!-- A bunch of other assemblies here--><!--<add assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /><add assembly="System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /></assemblies></compilation><httpModules><add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" /></httpModules></system.web></location>--><runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="DotNetOpenAuth.Core" publicKeyToken="2780ccd10d57b246" /><bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="DotNetOpenAuth.AspNet" publicKeyToken="2780ccd10d57b246" /><bindingRedirect oldVersion="0.0.0.0-4.3.0.0" newVersion="4.3.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-1.1.0.0" newVersion="1.1.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" /></dependentAssembly><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="7.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="log4net" publicKeyToken="669e0ddf0bb1aa2a" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-1.2.13.0" newVersion="1.2.13.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="System.Net.Http.Primitives" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" /><bindingRedirect oldVersion="0.0.0.0-4.2.29.0" newVersion="4.2.29.0" /></dependentAssembly></assemblyBinding><!-- When targeting ASP.NET MVC 3, this assemblyBinding makes MVC 1 and 2 references relink
		     to MVC 3 so libraries such as DotNetOpenAuth that compile against MVC 1 will work with it.<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" /></dependentAssembly></assemblyBinding>
		 --><!-- This prevents the Windows Event Log from frequently logging that HMAC1 is being used (when the other party needs it). --><legacyHMACWarning enabled="0" /></runtime><entityFramework><defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework"><parameters><parameter value="v12.0" /></parameters></defaultConnectionFactory><providers><!--<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.DefaultProviderServices, EntityFramework.SqlServer" />--><provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" /></providers></entityFramework><system.webServer><modules runAllManagedModulesForAllRequests="true" /><validation validateIntegratedModeConfiguration="false" /><!--   <directoryBrowse enabled="true" /> --><handlers><add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" /><remove name="ExtensionlessUrlHandler-Integrated-4.0" /><remove name="OPTIONSVerbHandler" /><remove name="TRACEVerbHandler" /><add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" /></handlers><security><requestFiltering><requestLimits maxAllowedContentLength="1073741824" /><!--<security><requestFiltering><requestLimits maxAllowedContentLength="1073741824" /></requestFiltering></security> add by ARTSQL Nov 1 15--></requestFiltering></security></system.webServer><dotNetOpenAuth><!-- This is an optional configuration section where aspects of dotnetopenauth can be customized. --><!-- For a complete set of configuration options see http://www.dotnetopenauth.net/developers/code-snippets/configuration-options/ --><openid><relyingParty><security requireSsl="false"><!-- Uncomment the trustedProviders tag if your relying party should only accept positive assertions from a closed set of OpenID Providers. --><!--<trustedProviders rejectAssertionsFromUntrustedProviders="true"><add endpoint="https://www.google.com/accounts/o8/ud" /></trustedProviders>--></security><behaviors><!-- The following OPTIONAL behavior allows RPs to use SREG only, but be compatible
					     with OPs that use Attribute Exchange (in various formats). --><add type="DotNetOpenAuth.OpenId.RelyingParty.Behaviors.AXFetchAsSregTransform, DotNetOpenAuth.OpenId.RelyingParty" /></behaviors></relyingParty></openid><messaging><untrustedWebRequest><whitelistHosts><!-- Uncomment to enable communication with localhost (should generally not activate in production!) --><!--<add name="localhost" />--></whitelistHosts></untrustedWebRequest></messaging><!-- Allow DotNetOpenAuth to publish usage statistics to library authors to improve the library. --><reporting enabled="true" /></dotNetOpenAuth><uri><!-- The uri section is necessary to turn on .NET 3.5 support for IDN (international domain names),
		     which is necessary for OpenID urls with unicode characters in the domain/host name.
		     It is also required to put the Uri class into RFC 3986 escaping mode, which OpenID and OAuth require. --><idn enabled="All" /><iriParsing enabled="true" /></uri><system.net><defaultProxy enabled="true" /><settings><!-- This setting causes .NET to check certificate revocation lists (CRL)
			     before trusting HTTPS certificates.  But this setting tends to not
			     be allowed in shared hosting environments. --><!--<servicePointManager checkCertificateRevocationList="true"/>--></settings><mailSettings><smtp from="artdbasemail@gmail.com"><network host="google.com" password="Abumaizer85" userName="artdbasemail@gmail.com" /></smtp></mailSettings></system.net><system.serviceModel><bindings /><client /></system.serviceModel><appSettings><add key="ValidationSettings:UnobtrusiveValidationMode" value="None" /><add key="Maintenance Mode" value="off" /></appSettings></configuration>

Now, I have two users, both have the same role as administrator one of them can access all sub directories and the second one keeps returning back to the login page,

the example as below, both can access this page:

http://localhost:1344/Default.aspx

only one can access this one:

http://localhost:1344/ARTSQLAPP/CLNCORE/PatientRegistration.aspx

Any ideas please?

Asp.net identity 2.x cross domain

$
0
0

Hi all

 

is it identity support cross domain ? 

client : http://www.abc.com  
webapi server : http://www.xyz.com 

server already enable cross domain 

var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

so now client send ajax request to webapi to login 

[ODataRoute("User.login")]
public async Task<IHttpActionResult> login(LoginPostData data)
{
    User user = await userManager.FindByNameAsync(data.username);
    if (user != null)
    {
        Request.GetOwinContext().Authentication.SignOut(); //确保每一次只有一个account是登入的
        SignInStatus result = await signInManager.PasswordSignInAsync(data.username, data.password, true, shouldLockout: true);
        switch (result)
        {
            case SignInStatus.Success:
                return Ok();
            case SignInStatus.LockedOut:
                S.log.Info("Login fail : user LockedOut, username : " + data.username);
                return BadRequest("locked");
            case SignInStatus.Failure:
            default:
                S.log.Info("Login fail : user wrong password, username : " + data.username);
                return BadRequest("wrongPassword");
        }
    }
    else
    {
        S.log.Info("Login fail : user not found, username : " + data.username);
        return BadRequest("notFound");
    }
}

it successful , but after that client send normal GET request, all response 401 

[Authorize(Roles = "Staff")]
[ODataRoute("")]
[EnableQuery(AllowedQueryOptions = Helper.ALLOW_QUERY)]
public async Task<IHttpActionResult> get()
{
    return Ok(await service.get(db, user, User));
}


any idea ? 


Why does windows warn on solution files that are emailed to my PC?

$
0
0

Suppose someone sends me his asp.net project via email to my PC.  I unzip it, and try to compile it, and get a warning from Visual Studio that the solution did not originate on my PC, and might run a dangerous script.  Is there a way to know if a solution file is safe?   What is exactly could be dangerous about it?

Help me complete Login to active directory:

$
0
0

Hi, please advise am I on the right track for LDAP querying?

I have implemented the code from Chris Schiffhauer http://www.schiffhauer.com/mvc-5-and-active-directory-authentication/ but i am not sure on how to go about creating a view:

in the Add view dialog box, i filled the view name to: Login

                                                                    Templete: Create

                                                                    Model class: LoginModel (UNSOS Scheduler App)

1. I don't know which data context class to select on the dialog box. Because i don't think am connecting to my application data entities.

2. I already have a database for the application connection string in web.config, please help show me how to edit web.config file to implement the changes to incorporate active directory authentication connection string and my application connection string. 

3. How will i handle the situation where when the active directory asks for credentials.

Regards,

ASP.NET Impersonation with Windows Auth Works in DEV but not PROD

$
0
0

Ok, I have to admit I am a little bit confused here so maybe one of you can help me. What I'm doing in my app is capturing the windows username and using that to personalize the app plus if an error occurs it comes to the web team along with the Windows User Identity. This all works great in DEV. I have Impersonate set to true and using Win Authentication, however the log entry comes up as IIS APPPOOL\.NET v4.5 but I need it to show as Domain\User. Can anyone shed some light on what is necessary for Username Pass Through? It works fine in my DEV environment but will not work in STAGING or PRODUCTION at this point. Let me know what I can do to resolve this. Thanks!!!

Augmenting membership user creation functionality

$
0
0

Dear All,

As its well known that membership create user functionality lacks a lot of user details that someone might need to store. I am presenting my work around it and I need your expert opinion, ( I am using web method)

I m currently using this code (Ref Microsoft)

Public Function GetErrorMessage(status As MembershipCreateStatus) As String

        Select Case status
            Case MembershipCreateStatus.DuplicateUserName
                Return "Username already exists. Please enter a different user name."

            Case MembershipCreateStatus.DuplicateEmail
                Return "A username for that e-mail address already exists. Please enter a different e-mail address."

            Case MembershipCreateStatus.InvalidPassword
                Return "The password provided is invalid. Please enter a valid password value."

            Case MembershipCreateStatus.InvalidEmail
                Return "The e-mail address provided is invalid. Please check the value and try again."

            Case MembershipCreateStatus.InvalidAnswer
                Return "The password retrieval answer provided is invalid. Please check the value and try again."

            Case MembershipCreateStatus.InvalidQuestion
                Return "The password retrieval question provided is invalid. Please check the value and try again."

            Case MembershipCreateStatus.InvalidUserName
                Return "The user name provided is invalid. Please check the value and try again."

            Case MembershipCreateStatus.ProviderError
                Return "The authentication provider Returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator."

            Case MembershipCreateStatus.UserRejected
                Return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator."

            Case Else
                Return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator."
        End Select
    End Function

Public Function GetUsrID(UserName) As String
        Dim sql As String = "SELECT UserId FROM aspnet_Users WHERE UserName= @UserName"
        Using cn As New SqlConnection(ARTSQLDBCOM), _
            cmd As New SqlCommand(sql, cn)
            cmd.Parameters.Add("@UserName", SqlDbType.VarChar, 256).Value = UserName
            cn.Open()
            Dim val As String = String.Empty
            Dim getVal As Object = cmd.ExecuteScalar()
            cn.Close()
            If Not IsNothing(getVal) Then
                val = getVal.ToString
                Return val
            Else
                Return Nothing
            End If
        End Using
    End Function<WebMethod()> _
    Public Function RegNewUser(ByVal Username As String, ByVal Password As String, ByVal Email As String, ByVal JobTitleID As String, ByVal Prfx As String, ByVal fname As String, ByVal Mname As String, ByVal Lname As String, ByVal Initial As String, _
        ByVal disname As String, ByVal UsrDOB As String, ByVal TelNum As String, ByVal UsrSignature As String, ByVal UsrImg_aURL As String, ByVal UsrImg_rURL As String) As String
        Dim status As MembershipCreateStatus
        'Dim passwordQuestion As String = ""
        'Dim passwordAnswer As String = ""

        'If Membership.RequiresQuestionAndAnswer Then
        '    passwordQuestion = PasswordQuestionDDl.Text.Trim()
        '    passwordAnswer = PasswordAnswerTextbox.Text
        'End If
        Try
            Dim newUser As MembershipUser = Membership.CreateUser(Username, Password, Email, Nothing, Nothing, False, status)
            If newUser Is Nothing Then
                Return GetErrorMessage(status)

            Else
                CreateUser_AugmentedUpdate(Username, JobTitleID, Prfx, fname, Mname, Lname, Initial, _
        disname, UsrDOB, TelNum, UsrSignature, UsrImg_aURL, UsrImg_rURL)
                Return "User has been Created Successfully"
            End If
        Catch
            Return "Create User Phase 1 Error. Please refer to your database developer"
        End Try


    End Function

Public Function CreateUser_AugmentedUpdate(ByVal UserName As String, ByVal JobTitleID As String, ByVal Prfx As String, ByVal fname As String, ByVal Mname As String, ByVal Lname As String, ByVal Initial As String, _
        ByVal disname As String, ByVal UsrDOB As String, ByVal TelNum As String, ByVal UsrSignature As String, ByVal UsrImg_aURL As String, ByVal UsrImg_rURL As String)
        Try
            Dim UserID As String = GetUsrID(UserName)
            Dim SQLCmd As New SqlCommand()
            SQLCmd.CommandType = CommandType.StoredProcedure
            SQLCmd.CommandText = "aspnet_Users_CreateUser_AugmentedUpdate"
            SQLCmd.Parameters.Add("@UserId", SqlDbType.NVarChar).Value = UserID.ToString
            If (String.IsNullOrEmpty(JobTitleID)) Then
                SQLCmd.Parameters.Add("@JobTitleID", SqlDbType.Int).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@JobTitleID", SqlDbType.Int).Value = Convert.ToInt32(JobTitleID)
            End If
            If (String.IsNullOrEmpty(Initial)) Then
                SQLCmd.Parameters.Add("@Initial", SqlDbType.Int).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@Initial", SqlDbType.Int).Value = Convert.ToInt32(Initial)
            End If
            If (String.IsNullOrEmpty(Prfx)) Then
                SQLCmd.Parameters.Add("@Prfx", SqlDbType.Int).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@Prfx", SqlDbType.Int).Value = Convert.ToInt32(Prfx)
            End If
            If (String.IsNullOrEmpty(fname)) Then
                SQLCmd.Parameters.Add("@fname", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@fname", SqlDbType.NVarChar).Value = fname.ToString
            End If

            If (String.IsNullOrEmpty(Mname)) Then
                SQLCmd.Parameters.Add("@Mname", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@Mname", SqlDbType.NVarChar).Value = Mname.ToString
            End If
            If (String.IsNullOrEmpty(Lname)) Then
                SQLCmd.Parameters.Add("@Lname", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@Lname", SqlDbType.NVarChar).Value = Lname.ToString
            End If
            If (String.IsNullOrEmpty(disname)) Then
                SQLCmd.Parameters.Add("@disname", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@disname", SqlDbType.NVarChar).Value = disname.ToString
            End If

            Dim dateValue As Date
            If String.IsNullOrWhiteSpace(UsrDOB) Then
                SQLCmd.Parameters.Add("@UsrDOB", SqlDbType.Date).Value = DBNull.Value
            ElseIf Date.TryParse(UsrDOB, dateValue) Then
                SQLCmd.Parameters.Add("@UsrDOB", SqlDbType.Date).Value = dateValue
            Else
                SQLCmd.Parameters.Add("@UsrDOB", SqlDbType.Date).Value = DBNull.Value
            End If

            If (String.IsNullOrEmpty(TelNum)) Then
                SQLCmd.Parameters.Add("@TelNum", SqlDbType.NChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@TelNum", SqlDbType.NChar).Value = TelNum.ToString
            End If
            If (String.IsNullOrEmpty(UsrSignature)) Then
                SQLCmd.Parameters.Add("@UsrSignature", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@UsrSignature", SqlDbType.NVarChar).Value = UsrSignature.ToString
            End If
            If (String.IsNullOrEmpty(UsrImg_aURL)) Then
                SQLCmd.Parameters.Add("@UsrImg_aURL", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@UsrImg_aURL", SqlDbType.NVarChar).Value = UsrImg_aURL.ToString
            End If
            If (String.IsNullOrEmpty(UsrImg_rURL)) Then
                SQLCmd.Parameters.Add("@UsrImg_rURL", SqlDbType.NVarChar).Value = DBNull.Value
            Else
                SQLCmd.Parameters.Add("@UsrImg_rURL", SqlDbType.NVarChar).Value = UsrImg_rURL.ToString
            End If
            SQLCmd.Connection = ARTSQLCON
            ARTSQLCON.Open()
            SQLCmd.ExecuteNonQuery()
            ARTSQLCON.Close()

        Catch
            Return "Create User Phase 2 Error. Please refer to your database developer"
        End Try
    End Function

Now behind this code, I put a trigger on the asp users table to insert the new userID in a different table. My SQL stored procedure (aspnet_Users_CreateUser_AugmentedUpdate)  run a record update on the new table

The code works beautifully but is it a good practice?

Thanks


Active Directory Groups and Roles with AD FS Single Sign On

$
0
0

Hello,

This is my first site in VS and a newbie to any type of code. I have created a site where SSO is enabled and working as expected. The user is redirected from my project URL to the SSO login and after successful login they are presented with the project site. My goal is to limit what the user sees in the site based on their group in Active Directory. However, no matter how I setup my web.config and sitemap the users are presented with all the menu items. I am using server 2012 R2, VS 2015, AD FS 3.0 with this project and real IIS not IIS express. I have three groups in AD with the users associated. Could you let me know what I am missing? Is there something in the Code Behind that I need to add? I have checked several examples but not sure how to get this configured.

WEB CONFIG<?xml version="1.0" encoding="utf-8"?><!--
  For more information on how to configure your ASP.NET application, please visit
   http://go.microsoft.com/fwlink/?LinkId=301880

  --><configuration><appSettings><add key="ida:ADFSMetadata" value="https://FQDN/FederationMetadata/2007-06/FederationMetadata.xml" /><add key="ida:Wtrealm" value="https://myapplication" /></appSettings><system.web><authentication mode="Windows"/><roleManager enabled="true" defaultProvider="WindowsProvider"><providers><add name="WindowsProvider" type="System.Web.Security.WindowsTokenRoleProvider" /></providers></roleManager></system.web><system.web><siteMap defaultProvider="XmlSiteMapProvider" enabled="true"><providers><add name="XmlSiteMapProvider"
          description="Default SiteMap provider."
          type="System.Web.XmlSiteMapProvider "
          siteMapFile="Web.sitemap"
          securityTrimmingEnabled="true" /></providers></siteMap></system.web><location path="~/PAGE.aspx"> <!-- testing page --><system.web><authorization><allow roles="DOMAIN\Group" /> <!--  tried different methods such as usernames and without domain. --><deny users="*" /></authorization></system.web></location><location path="Account"><system.web><authorization><allow users="*" /></authorization></system.web></location><system.web><authorization><deny users="?" /></authorization><compilation debug="true" targetFramework="4.5.2" /><httpRuntime targetFramework="4.5.2" /><pages><namespaces><add namespace="System.Web.Optimization" /></namespaces><controls><add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt" /></controls></pages><httpModules><add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" /></httpModules></system.web><system.webServer><modules><remove name="FormsAuthentication" /><remove name="ApplicationInsightsWebTracking" /><add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler" /></modules><validation validateIntegratedModeConfiguration="false" /></system.webServer><runtime><assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"><dependentAssembly><assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" /><bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" /></dependentAssembly><dependentAssembly><assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35" /><bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" /></dependentAssembly></assemblyBinding></runtime><system.codedom><compilers><compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" /><compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\&quot;Web\&quot; /optionInfer+" /></compilers></system.codedom></configuration>


SITE MAP

<?xml version="1.0" encoding="utf-8" ?><siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" ><siteMapNode url="~/Default.aspx" title="Home Page" description="Home Page" roles="*" ><siteMapNode url="~/PAGE.aspx" title="PAGE" description="PAGE"  roles="Admin" /><siteMapNode url="~/PAGE2.aspx" title="PAGE2" description="PAGE2" roles="Admin" /><siteMapNode url="~/PAGE3.aspx" title="PAGE3" description="PAGE3" roles="Admin,Supervise" /><siteMapNode url="~/PAGE4.aspx" title="PAGE4" description="PAGE4" roles="*" /><siteMapNode url="~/PAGE5.aspx" title="PAGE5" description="PAGE5" roles="Admin" /><siteMapNode url="~/PAGE6.aspx" title="PAGE6" description="PAGE6" roles="*" /><siteMapNode url="~/PAGE7.aspx" title="PAGE7" description="PAGE7" roles="*" /></siteMapNode></siteMap>

Prevent direct access of css image and javascript files

$
0
0

Hi

I have developed application in ASP.NET MVC and deployed the same application on AZURE Web APP.

In the application there are three different folders with relevant files such as- Script,Content,Image.

After deploying the site, I want to restrict direct access of the files from folder Script,Content,Image.

i.e. if user tries to access URL's as

1) URL/Script/main.js

2) URL/Content/main.css

3) URL/Image/logo.jpg

then the file can easily get loaded on browser.

However I want to restrict the above.

Please provide solution to prevent direct access of folder files.

Regards

Uday

WSAT Security Tab Error

$
0
0

Can't access the security tab of WSAT. I get the following error.

There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store. 

The following message may help in diagnosing the problem: Arithmetic operation resulted in an overflow.

I've gone through my code. Role manager is enabled. Server name is valid. I don't see the problem.

Thanks in advance

how deactivate "Error executing child request" in web.config

$
0
0

hi

how deactivate "Error executing child request" in web.config

this ERROR happens when Execute Page or Transfer Page in ASP.NET

Medium Trust Level application

$
0
0

One of my web based application on .net was developed on full trust level environment for dedicated server hosting.

Now, I have to move my application on shared hosting who does not provide the full trust level for my application and assemblies using in the application.

what changes required in either web.config or my application to convert the full trust level into the medium trust level.

Kindly guide.

Thanks in advance.

Replacement for LdapFilterEncode

$
0
0

Hi,

currently we are using Microsoft.Security.Application.Encoder.LdapFilterEncode but now we want to move to some alternative as AntiXSS library is deprecated by microsoft.

Thanks,

Two Factor Authentication

$
0
0

Hello.

I have created a Website on Microsoft Visual Studio 2017. They Web app is just to demonstrate to somebody so there isn't a need to publish it on Azure.

I am using MVS's original template of ASP.Net Web Forms Site where there is already a template for the log-in given. However, I would like to incorporate a two-factor authentication to act as a security measure.

What is the best way of two-factor authentication in this case? Am I able to incorporate CAPTCHA that only allows users to log in after entering the correct CAPTCHA?

Thank you.


External login error ASP Identity C#

$
0
0

 I have a standard ASP web app using standard ASP Identity. I cannot seem to authenticate with facebook I keep getting this error:

URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings. Make sure Client and Web OAuth Login are on and add all your app domains as Valid OAuth Redirect URIs.

My Startup.Auth

public partial class Startup
{
    // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

        // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
        app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

        // Enables the application to remember the second login verification factor such as phone or email.
        // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
        // This is similar to the RememberMe option when you log in.
        app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

        // Uncomment the following lines to enable logging in with third party login providers
        //app.UseMicrosoftAccountAuthentication(
        //    clientId: "",
        //    clientSecret: "");

        //app.UseTwitterAuthentication(
        //   consumerKey: "",
        //   consumerSecret: "");

        app.UseFacebookAuthentication(
           appId: "My APP ID",
           appSecret: "My Secret"
           );

        //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
        //{
        //    ClientId = "",
        //    ClientSecret = ""
        //});
    }
}

The OAuth redirect URI I use in my facebook app is as follows: http://exampledomain.com/account/externalcallback

The External Callback method is the standard version from asp identity:

 // GET: /Account/ExternalLoginCallback
    [AllowAnonymous]
    public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
    {
        var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
        if (loginInfo == null)
        {
            return RedirectToAction("Login");
        }

        // Sign in the user with this external login provider if the user already has a login
        var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
            case SignInStatus.Failure:
            default:
                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl = returnUrl;
                ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
                return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
        }
    }

Not sure where to set what on the facebook app. ANY assistance would be greatly appreciated!

How to authenticate user with username & password using ADFS 3.0 or LDAP using C#

$
0
0

Dear All,

  I'd the latest project which communicates ADFS/LDAP remote server to authenticate username and password of Domain users. 

 During the authorization, need to get all information about the logged-in user from the ADFS. for example., Display Name, Roles, FullName,etc.,

Please help on my above request with real-time examples. Appreciate your feedback. 

Awaiting for your kind reply.

Which field should I use to isolate logged in user's records?

$
0
0

Environment .Net 4.5.2 in VS 2015

I'm using the Web Forms template with Individual User Accounts for authentication.

So if I want to make sure a user is presented with only her records when logged in, would I use the Id field in AspNetUsers table that ASP.NET Identity generates? In other words, when I save any kind of record for a user, I'll need to save this Id field along with the record, correct?

MVC/Word press SSO

$
0
0

I have an existing site that has implemented user management, and I am standing up a wordpress site for forums. I need Single Sign On (SSO) between the two sites. Researching WordPress it appears that OAUTH is my best bet for a SSO implementation. However, I can find plenty of examples of implementing OAUTH in asp.net/mvc to allow sign in with a third party, but I've not found any examples of how to be the third party.

I need my site to manage the users, and pass the required OAUTH data to WordPress, any one able/willing to point me in the right direction?

Thanks
Wayne

How do I customize ASP.NET Identity for my requirement

$
0
0

I need to perform authentication for my MVC application. The database has been defined but without any User schema. My requirement is to use only theUser and Role table.

Being new to ASP.NET Identity, can someone guide me on how to customize Identity for my requirements.

I prefer the DB first approach so any tutorial to use Identity with DB-First approach will also be appreciated.

Viewing all 4737 articles
Browse latest View live