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

Event code: 4005 Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired.

$
0
0

Recently some CIS Windows hardening policies were applied to one of our Windows 2012R2 Datacenter servers.

When smoke testing the web applications on these servers, we discovered that the authentication no longer worked and we are now receiving 403 errors when accessing the web applications:

403 - Forbidden: Access is denied.

You do not have permission to view this directory or page using the credentials that you supplied.

In the Windows Event Viewer the following information event is logged:

Event code: 4005
Event message: Forms authentication failed for the request. Reason: The ticket supplied has expired.
Event time: 5/2/2017 9:02:30 AM
Event time (UTC): 5/2/2017 2:02:30 PM
Event ID: 5dd78f5603644e26b620998f702d0923
Event sequence: 22
Event occurrence: 10
Event detail code: 50202 

I saw some similar errors where this problem was resolved by regenerating a Machine Key, however that did not work.

Any idea of next steps in finding the root cause of this issue?

Thanks.


Prevent posting messages

$
0
0

Hello. I have some form on web site that return model to controller . Model have some three string properties: Name, Note and Email

visitors fill theese properties and push "send" button. Then the controller action resend visitors's Name, Note and Email to my Email.
My question:
How to prevent sending more than one message per day for each one web site visitor ?

May be there is some open function or solution for this  ?

ASP.NET MVC 5 - Microsoft Account OAuth2 sign-on stop to work after update the Microsoft.Owin packages from v3.0.1 to v3.1.0

$
0
0

I have updated the following Nuget packages from v3.0.1 to v3.1.0:

  • Microsoft.Owin
  • Microsoft.Owin.Host.SystemWeb
  • Microsoft.Owin.Security
  • Microsoft.Owin.Security.Cookies
  • Microsoft.Owin.Security.Google
  • Microsoft.Owin.Security.MicrosoftAccount

And after these updates the following issue is displayed when I try to authenticate using a Microsoft Account:

Correlation ID: 1a411cc0-446c-42bb-8659-cdd7dd9e6199
AADSTS70011: The provided value for the input parameter 'scope' is not valid. The scope wl.emails is not valid.

Important notes:

  • This issue is only happening when I try to use a Microsoft Account for authenticating. There is no issue when I use a Google account for authenticating it
  • When I do the downgrade for the v3.0.1 the Microsoft Account authentication back to work again

Does anyone know if something has changed in Microsoft authentication on Microsoft.Owin.Security.MicrosoftAccount v3.1.0 that I have to change in my source code?

Here are the Startup.Auth.cs and AccountController.cs from the System:

Startup.Auth.cs

using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.Google;
using Microsoft.Owin.Security.MicrosoftAccount;
using Owin;

namespace IRIS
{
    public partial class Startup
    {
        private void ConfigureAuth(IAppBuilder app)
        {
            var cookieAuthenticationOptions = new CookieAuthenticationOptions { ExpireTimeSpan = System.TimeSpan.FromMinutes(120), LoginPath = new PathString("/Account/Login") };
            app.UseCookieAuthentication(cookieAuthenticationOptions);
            app.SetDefaultSignInAsAuthenticationType(cookieAuthenticationOptions.AuthenticationType);
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions { ClientId = "<MyGoogleClientId>", ClientSecret = "<MyGoogleClientSecret>" });
            app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions { ClientId = "<MyMicrosoftClientId>", ClientSecret = "<MyClientSecret>", Scope = { "wl.emails" } });
        }
    }
}

AccountController.cs

using System.Web;
using System.Web.Mvc;

namespace IRIS.Controllers
{
    public class AccountController : Controller
    {
        [AllowAnonymous]
        [OutputCache(NoStore = true, Location = System.Web.UI.OutputCacheLocation.None)] //Evita o seguinte erro de login: http://stackoverflow.com/questions/24376800/the-back-button-and-the-anti-forgery-token
        public ActionResult Login(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult ExternalLogin(string provider, string returnUrl)
        {
            return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
        }

        [AllowAnonymous]
        public ActionResult ExternalLoginCallback(string error, string returnUrl)
        {
            string[] outputParameters = new string[4];
            if (error != "access_denied")
            {
                Models.Data.DbException dbException = Models.Data.Firebird.ExecuteProcedure("I_ACCOUNT_LOGIN", new string[] { System.Security.Claims.ClaimsPrincipal.Current.FindFirst(System.Security.Claims.ClaimTypes.Email).Value }, outputParameters);
                if (dbException.ErrorCode == null)
                    if (outputParameters[0] == "0")
                    {
                        Models.Utils.Cookies.Account.Save(outputParameters[1], outputParameters[2], outputParameters[3], System.Security.Claims.ClaimsPrincipal.Current.FindFirst(System.Security.Claims.ClaimTypes.Email).Value);
                        Models.Utils.Cookies.App.Save((new string[12] { "skin-black", "skin-black-light", "skin-blue", "skin-blue-light", "skin-green", "skin-green-light", "skin-purple", "skin-purple-light", "skin-red", "skin-red-light", "skin-yellow", "skin-yellow-light", })[new System.Random().Next(0, 12)], (new string[3] { "", "fixed", "layout-boxed" })[new System.Random().Next(0, 3)], (new string[2] { "sidebar-open", "sidebar-collapse" })[new System.Random().Next(0, 2)], (new string[2] { "true", "false" })[new System.Random().Next(0, 2)]);
                    }
                    else
                    {
                        Models.Utils.Cookies.Account.Save(outputParameters[0], System.Security.Claims.ClaimsPrincipal.Current.FindFirst(System.Security.Claims.ClaimTypes.Email).Value);
                        Models.Utils.Cookies.App.Delete();
                    }
                else
                {
                    Models.Utils.Cookies.Account.Delete();
                    Models.Utils.Cookies.App.Save(dbException.ErrorCode.ToString(), dbException.Message);
                }
            }
            return outputParameters[0] != null && outputParameters[0] == "0" ? RedirectToLocal(returnUrl) : RedirectToAction("Logout", "Account", new { ReturnUrl = returnUrl });
        }

        [AllowAnonymous]
        public ActionResult Logout(string returnUrl)
        {
            HttpContext.GetOwinContext().Authentication.SignOut();
            return returnUrl == null ? RedirectToAction("Index", "Home") : RedirectToLocal(returnUrl);
        }

        #region Helpers
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            return RedirectToAction("Index", "Home");
        }

        internal class ChallengeResult : HttpUnauthorizedResult
        {
            public ChallengeResult(string provider, string redirectUri)
            {
                LoginProvider = provider;
                RedirectUri = redirectUri;
            }

            public string LoginProvider { get; set; }
            public string RedirectUri { get; set; }

            public override void ExecuteResult(ControllerContext context)
            {
                var properties = new Microsoft.Owin.Security.AuthenticationProperties { RedirectUri = RedirectUri };
                context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
            }
        }
        #endregion
    }
}



The name 'ConfigureAuth' does not exist in the current context

$
0
0

Hi, I have this error above in this line in my startup.cs file:

[assembly: OwinStartupAttribute(typeof(ContosoUniversity.Startup))]
namespace ContosoUniversity
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);
            createRolesandUsers();
        }
}
}

I have more code but I just put the affected code here.

Actually, I tried to copy the default Identity membership code to my project.

And in my App_Start folder, I already have the ConfigureAuth method in Startup.Auth.cs file. Below is the code:

namespace ContosoUniversity.App_Start
{
    public partial class Startup
    {
        // For more information on configuring authentication, please visit http://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);

            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);


        }
    }
}

How do I fix the error?

Managed Service Account (MSA)

$
0
0

Hi folks,

I have an application that I want to use MSA account to connect to the database server. Can someone help with sample code or explanation that I can use in my web config? I have the WCF and the Web application. Do I need to do it on both web.config or just the WCF web.config?

Appreciated very much.

Built in Login Control

$
0
0

Hi,

I am bug fixing an existing vb.net website.  The site uses the built-in Login control.  I have been trying to figure out how to get the userID and the user login status so that I can log off  programmatically as needed.  I have not used this control before.  Can you help get me pointed in the right direction?  I have tried using Global.asax, but found out I would need a user context.  Can you help me out?

Ed

Mock specific claim and specific role using et Asp.net identity

$
0
0

Hi, 

I want to moq  specific claim and specific role using  et Asp.net identity 

public static ClaimsPrincipal MockIdentity(int userId, string username, List<Claim> userClaims,
			bool isAuthenticated = true, string[] userRoles = null, Claim ClaimToVerify = null)
		{
			Mock<GenericIdentity> mockGenericIdentity = new Mock<GenericIdentity>(username);
			mockGenericIdentity.Setup(x => x.Claims).Returns(userClaims);
			mockGenericIdentity.Setup(x => x.HasClaim(c => c.Type == ClaimToVerify.Type && c.Value == ClaimToVerify.Value)).Returns(true);
			mockGenericIdentity.Setup(x => x.IsAuthenticated).Returns(isAuthenticated);

			mockGenericIdentity.Setup(x => x.IsAuthenticated).Returns(isAuthenticated);

			Mock<ClaimsPrincipal> mockClaimsPrincipal = new Mock<ClaimsPrincipal>(mockGenericIdentity.Object);
			mockClaimsPrincipal.Setup(x => x.Identity.IsAuthenticated).Returns(isAuthenticated);
			mockClaimsPrincipal.Setup(x => x.Identity.Name).Returns(username);

			mockClaimsPrincipal.Setup(x => x.Claims).Returns(userClaims);
			mockClaimsPrincipal.Setup(x => x.IsInRole("admin")).Returns(true);
			return mockClaimsPrincipal.Object;
		}

principal.HasClaim(x => x.Type == ClaimType && x.Value == ClaimValue)))    returns always false, why

public override Task OnAuthorizationAsync(HttpActionContext actionContext, System.Threading.CancellationToken cancellationToken)
		{
			var principal = actionContext.RequestContext.Principal as ClaimsPrincipal;

			if (!principal.Identity.IsAuthenticated)
			{
				actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
				return Task.FromResult<object>(null);
			}

			if (Roles.Any(r => !principal.IsInRole(r)))
			{
				actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
				return Task.FromResult<object>(null);
			}

			if (!(principal.HasClaim(x => x.Type == ClaimType && x.Value == ClaimValue)))
			{
				actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
				actionContext.Response.Headers.Add("WWW-Authenticate", "Bearer");
				return Task.FromResult<object>(null);
			}

			//User is Authorized, complete execution
			return Task.FromResult<object>(null);
		}

Regards

Updating data in User Accounts - Value cannot be null. Parameter name: manager

$
0
0

I'm having issues with geting the user data to update in MVC5. I created a form and when I click on submit, it runs the method below, which throws the error  

Value cannot be null. Parameter name: manager


I know if has to do with UserManager, but I can't find any resource that helps me with this particular issue. I've been pulling my hair out for a couple days now trying to get the user data to update via the form so any help is greatly appreciated.

Let me know if any other info is needed

Controller

[ValidateAntiForgeryToken]
public async Task<ActionResult> Update(TierViewModel model)
{

ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());


user.FirstName = model.ApplicationUser.FirstName;
user.LastName = model.ApplicationUser.LastName;
user.Email = model.ApplicationUser.Email;
user.Opid = model.ApplicationUser.Opid;
user.PhoneNumbers = model.ApplicationUser.PhoneNumbers;
user.TierId = model.ApplicationUser.TierId;
IdentityResult result = await UserManager.UpdateAsync(user);

return RedirectToAction("EmployeeDetails");


}

ApplicationUser

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;

namespace NewProject.Models
{
    public class ApplicationUser : IdentityUser
    {



        [Required(ErrorMessage = "Your must provide a PhoneNumber")]
        [Display(Name = "Home Phone")]
        [DataType(DataType.PhoneNumber)]
        [DisplayFormat(DataFormatString = "{0:###-###-####}")]

        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]
        public string PhoneNumbers { get; set; }


        public string EmailAccount => Email;
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Tier Tier { get; set; }
        [Display(Name="Tier Level")]
        public int TierId { get; set; }

        public string Opid { get; set; }



        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {



            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here

            userIdentity.AddClaim(new Claim("PhoneNumbers", this.PhoneNumbers.ToString()));
            userIdentity.AddClaim(new Claim("FirstName", this.FirstName.ToString()));
            userIdentity.AddClaim(new Claim("Opid", this.Opid.ToString()));
            userIdentity.AddClaim(new Claim("TierId", this.TierId.ToString()));



            return userIdentity;
        }


        public ApplicationUser()
        {
            this.TierId = 4;

        }

    }
}           

I also tried using a viewmodel with the update method code, but got a different error on the following line in my .cshtml file saying 

<td>@Html.TextBoxFor(m => m.ApplicationUser.FirstName)</td> 

Error: Object refence not set to an instance of an object

[ValidateAntiForgeryToken]
public async Task<ActionResult> Update(ApplicationUser applicationUser)
{
try
{

var viewModel = new TierViewModel()
{
ApplicationUser = applicationUser,
TierLevel = _context.Tier.ToList()


};

ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());


user.FirstName = viewModel.ApplicationUser.FirstName;
user.LastName = viewModel.ApplicationUser.LastName;
user.Email = viewModel.ApplicationUser.Email;
user.Opid = viewModel.ApplicationUser.Opid;
user.PhoneNumbers = viewModel.ApplicationUser.PhoneNumbers;
user.TierId = viewModel.ApplicationUser.TierId;
IdentityResult result = await UserManager.UpdateAsync(user);
return View("EmployeeDetails", viewModel);

}

catch (ArgumentNullException e)
{
Console.WriteLine(e);

}
return View("EmployeeDetails");


Username and hashed password authentication on login form C#

$
0
0

Hello I am working on a project, and I am trying to authenticate the user to log in to my website. I do have the password hashed and salt in the database. I can get it to work if the password is in plain text, but now that it is hashed for better security, I am having trouble comparing the Hashed password from when the user signed up, to when they log back in. Here is a look at my code, and any help would be greatly appreciated.  

Also please show some code examples if you can, thanks

protected void LogInClick_Click(object sender, EventArgs e)
{
InsertDatabase LogIn = new InsertDatabase();
GenerateHash HashAndSalt = new GenerateHash();

string GetSalt = HashAndSalt.CreateSalt(10);

PasswordText.Text = HashAndSalt.GenarateHash(PasswordText.Text, GetSalt);

LogIn.LogInAccount(UserText.Text, PasswordText.Text, InvalidLogIn);

Response.Redirect("~/Profile.aspx/");
}



public string CreateSalt(int SaltSize)
{
var rng = new System.Security.Cryptography.RNGCryptoServiceProvider();
byte[] buff = new byte[SaltSize];
rng.GetBytes(buff);
return Convert.ToBase64String(buff);
}

public string GenarateHash(string UserPassword, string salt)
{
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(UserPassword + salt);
System.Security.Cryptography.SHA256Managed PasswordHash = new System.Security.Cryptography.SHA256Managed();

byte[] hash = PasswordHash.ComputeHash(bytes);

return Convert.ToBase64String(hash);
}



public void LogInAccount(string UserName, string UserPassword, Label InvalidLogIn)
{
GenerateHash PasswordHash = new GenerateHash();

connection.ConnectionString = @"connection string";
connection.Open();


string compare = @"Select UserName, UserPassword FROM UserInfo WHERE UserName=@UserName";

//string compare = "select ISNULL(UserName, '') As UserName, ISNULL(UserPassword, '') As UserPassword from UserInfo where UserName= @UserName";

SqlCommand CompareUser = new SqlCommand(compare, connection);

CompareUser.Parameters.AddWithValue("@UserName", UserName);

CompareUser.Parameters.AddWithValue("@UserPassword", UserPassword);

SqlDataReader dr = CompareUser.ExecuteReader();

string GetSalt = PasswordHash.CreateSalt(10);

string Pwd = PasswordHash.GenarateHash(UserPassword, GetSalt);
while(dr.Read())
{
if (UserPassword == Pwd)
{
FormsAuthentication.RedirectFromLoginPage(UserName, true);
}
}

connection.close();


User Roles and Permissions

$
0
0

Hello, is there a good tutorial or blog that shows how to set user roles and give users permission to view forms and not view other forms in a project? Thanks

how to get windows login from webform website with authentication mode ="windows"

$
0
0

I created an empty basic default webform website in VS2015 (windows 7 pro workstation) and set windows authentication = enabled and anonymous authentication = disabled and in web.config I set authentication mode = "windows".  When I launch the site (with anonymous authentication = disabled) I get this error message:

HTTP Error 404.15 - Not Found

The request filtering module is configured to deny a request where the query string is too long.

and some crazy url

Requested URL   http://localhost:34687/Account/Login?ReturnUrl=%2FAccount%2FLogin%3FReturnUrl%3D%252FAccount%252FLogin%253FReturnUrl%253D%25252FAccount%25252FLogin%25253FReturnUrl%25253D%2525252FAccount%2525252FLogin%2525253FReturnUrl%2525253D%252525252FAccount%252525252FLogin%252525253FReturnUrl%252525253D%25252525252FAccount%25252525252FLogin%25252525253FReturnUrl%25252525253D%2525252525252FAccount%2525252525252FLogin%2525252525253FReturnUrl%2525252525253D%252525252525252FAccount%252525252525252FLogin%252525252525253FReturnUrl%252525252525253D%25252525252525252FAccount%25252525252525252FLogin%25252525252525253FReturnUrl%25252525252525253D%2525252525252525252FAccount%2525252525252525252FLogin%2525252525252525253FReturnUrl%2525252525252525253D%252525252525252525252FAccount%252525252525252525252FLogin%252525252525252525253FReturnUrl%252525252525252525253D%25252525252525252525252FAccount%25252525252525252525252FLogin%25252525252525252525253FReturnUrl%25252525252525252525253D%2525252525252525252525252FAccount%2525252525252525252525252FLogin%2525252525252525252525253FReturnUrl%2525252525252525252525253D%252525252525252525252525252FAccount%252525252525252525252525252FLogin%252525252525252525252525253FReturnUrl%252525252525252525252525253D%25252525252525252525252525252FAccount%25252525252525252525252525252FLogin%25252525252525252525252525253FReturnUrl%25252525252525252525252525253D%2525252525252525252525252525252FAccount%2525252525252525252525252525252FLogin%2525252525252525252525252525253FReturnUrl%2525252525252525252525252525253D%252525252525252525252525252525252FAccount%252525252525252525252525252525252FLogin%252525252525252525252525252525253FReturnUrl%252525252525252525252525252525253D%25252525252525252525252525252525252FAccount%25252525252525252525252525252525252FLogin%25252525252525252525252525252525253FReturnUrl%25252525252525252525252525252525253D%2525252525252525252525252525252525252FAccount%2525252525252525252525252525252525252FLogin%2525252525252525252525252525252525253FReturnUrl%2525252525252525252525252525252525253D%252525252525252525252525252525252525252FAccount%252525252525252525252525252525252525252FLogin%252525252525252525252525252525252525253FReturnUrl%252525252525252525252525252525252525253D%25252525252525252525252525252525252525252F
Physical Path   C:\B_myStuff\VSprojects\WebSite1\Account\Login
Logon Method   Not yet determined
Logon User   Not yet determined
Request Tracing Directory   C:\Users\rprotzel\Documents\IISExpress\TraceLogFiles\WEBSITE1(1)

If I enable anonymous authentication then the website starts up OK but when I try

string userid = HttpContext.Current.User.Identity.Name;

in the site.Master page  the value of userid = "".   How can I get the windows login value?  How can I make the website run with anonymous authentication set to disabled and use windows authentication = enabled?

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.

Error 401.2: Unauthorized: Logon failed due to server configuration

$
0
0

We have used Microsoft.AspNet.FriendlyUrls for that we install from nuget package manager and added following code into Global.ASAX file.

protected void Application_Start(object sender, EventArgs e)
{
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
 public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Permanent;
            routes.EnableFriendlyUrls(settings);
        }

This is working fine onto localhost but after publishing on to IIS 8.0 server the following error :

Note: Our Application Authentication Mode is  authentication mode="Forms"

Access is denied.

Description: An error occurred while accessing the resources required to serve this request. The server may not be configured for access to the requested URL.
Error message 401.2.: Unauthorized: Logon failed due to server configuration. Verify that you have permission to view this directory or page based on the credentials you supplied and the authentication methods enabled on the Web server. Contact the Web server’s administrator for additional assistance.

I searched for this issue onto different forum but i did not found the solution. kindly help me

Website Login problem with Identity 2

$
0
0

I have created a ASP.net 4.5 website in Visual Studio 2015  using identity 2. I have added the most recent Nuget packages for OWIN

On my local machine with Firefox I experience no problems but since publishing to a host the Login process is not working

The page simply returns to the login Page after each attempt. I have done some homework and found this thread

http://stackoverflow.com/questions/20737578/asp-net-sessionid-owin-cookies-do-not-send-to-browser?noredirect=1&lq=1

However my attempts to utilize the learning have failed.

I have 2 problems

  1. I am not sure exactly where to place the code on my site and which is the best approach
  2. I am using vb.net and attempts to translate the Katana approach have failed

I would really appreciate a simple, easy to implement guide to the solution to this problem

Thankyou

Michael

Asp.Net Identity Globalization

$
0
0

I am trying to use globalization in my Asp.NET Identity specifically in TokenEndpointPath.

My dll versions are the following:

Microsoft.AspNet.Identity.Core - 2.0.0.0

Microsoft.AspNet.Identity.EntityFramework - 2.0.0.0

Microsoft.AspNet.Identity.Owin - 2.0.0.0

Microsoft.Owin - 3.0.1.0

For each of them I download also the pt-BR localization:

<package id="Microsoft.AspNet.Identity.Core.pt-br" version="2.2.1" targetFramework="net452" /><package id="Microsoft.AspNet.Identity.EntityFramework.pt-br" version="2.2.1" targetFramework="net452" /><package id="Microsoft.AspNet.Identity.Owin.pt-br" version="2.2.1" targetFramework="net452" /><package id="Microsoft.Owin.pt-br" version="3.0.1" targetFramework="net452" />

And I added the following line in my 

web.config
:
<system.web><globalization culture="pt-BR" uiCulture="pt-BR"/></system.web>

I am also using restSharp or Postman to make a few endpoints calls trying to force pt-BR language usage.

public async TaskInvalidPasswordLoginTest(){Lessor lessor;

    using (ApplicationUserManager userManager =UserManager){
        lessor =newLessor{Name="Master and Commander Lessor",Email="master-lessor@email.com",UserName="master-lessor@email.com"};

        await userManager.CreateAsync(lessor,"passwd1");}#region Execute Test Actions//Autenticate Uservar request =newRestRequest("/Token",Method.POST);
    request.AddParameter("grant_type","password");
    request.AddParameter("password","passwd12");
    request.AddParameter("username", lessor.UserName);
    request.AddHeader("Content-Type","application/x-www-form-urlencoded");IRestResponse response =Client.Execute(request);Assert.That(response.StatusCode,Is.EqualTo(HttpStatusCode.BadRequest));#endregion}

But my response is has the following content:

"{\"error\":\"invalid_grant\",\"error_description\":\"The user name or password is incorrect.\"}"

Instead of the pt-BR version. Is this supposed to happen? Any idea of what I might be doing wrong?


ASP.NET Identity and Database-First Approach

$
0
0

ASP.NET Identity and Entity Framework Database-First Approach

I have used ASP.NET Identity in my code-first projects before and tried using it in a project that has an existing database-first approach in MySQL.

I have gone through almost everything I could find on the internet to make this work, but failed with errors like missing key or changed entity at runtime. I must be missing something here.

I would be really grateful if anyone gave me a comprehensive guide to implementing databse-first with ASP.Net identity. Thanks!

newbee - anyone who has gotten a cert and set up SSL would easily be able to answer these beginner questions

$
0
0

hi all,

I am using vs2010 asp.net web app . I want this cert for ssl for a directory that will have a shopping cart. I am using winhost.com as my IIS 7 web server

1. The site is not showing all images and loads slower. I expected the slow down cuz encryption, but missing images. why are images missing?

2. If I view it in chrome the https in the address bar is struck through with a red line and the warning is:

  "Your connection to https://www.greenzonekicker.com is encrypted, However this page includes other resources which are not secure...some resources can be viewed by others or attackers while in transit....connection uses tls 1.0...SHA1...and RSA...the connection is not compressed"

What other resources are not secured? 

How do I set up compression and should I?

3. I really only want the security when entering the shopping cart directory (which i am still working on), how to do this

simply if someclicks on a product to buy, make the link go to https and not just http? example link goes to https://www.greenzonekicker.com/SecureCart/ . I suppose thats all I need to do.yes?

Thanks Very much for your help

Thanks,

Adam

context Identity is not set in AuthorizationHandler

$
0
0

Hello!

I am using policy based authorization. Here is what I have in my Startup.cs:

services.AddSingleton<IAuthorizationHandler, PrivateAuthorizationHandler>();
services.AddAuthorization(options =>
{
   options.AddPolicy("User", policy => policy.Requirements.Add(new PrivateRequirement(new[] {1}, "User")));
   options.AddPolicy("Super User", policy => policy.Requirements.Add(new PrivateRequirement(new[] {1, 2}, "Super User")));
   options.AddPolicy("Admin", policy => policy.Requirements.Add(new PrivateRequirement(new[] {1, 2, 3}, "Admin")));
});

My handler looks like that:

protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, PrivateRequirement requirement)
        {
            try
            {
                var ntName = context.User.Identity.Name; // <= always empty string ""
                if (string.IsNullOrWhiteSpace(ntName))
                {
                    context.Fail(); // <= always getting here
                }
                else
                {
                      //check requirement
                }
            }
            catch (Exception ex)
            {
                context.Fail();
            }

            return Task.CompletedTask;
        }



I am using Windows Authentication. Locally it is working fine. When I deploy the project to IIS, I am getting the issue above. It is like context is not being passed to the handler correctly.

Any idea on how to get Authenticated User in a handler?

Thank you!

Identity Login with mobile phone number

$
0
0

I am using Identity in .NET to make my token based authentication. At the moment the login is done using the username (email) and password, but I would also like to add the possibility to login using other information like for instance mobile phone number.

What is the best way to achieve it? My idea is to implement a Login Endpoint that will search the database to get the users email and makes a call to the current Login endpoint /Token just like the way it is (following this idea), but I wonder if there is no other option available to make this without the necessity to make a double call. Any suggestion would be welcome.

Claim based Authentication and Authorization

$
0
0

Hi All,

I am trying to implement claim based authentication and authorization in Web Api and Mvc. 

Can anyone please help me how can I implement security using Claim?  

Thanks

Selvakumar R

Viewing all 4737 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>