Showing posts with label .Net Core. Show all posts
Showing posts with label .Net Core. Show all posts

Monday, 22 August 2022

Use of .map in jQuery to get selected checkboxes values:

HTML:
<input type="checkbox" class="chkitem" value="1"/>
<input type="checkboxclass="chkitem" value="2"/>
<input type="checkboxclass="chkitem" value="3"/>

jQuery:
var ids = $(".chkitem:checked").map(function () {
                        return $(this).val();
                    }).get();

Simple C# code to Validating email address

 public static bool ValidateEmail(string email)
 {
      string regex = @"^[a-z0-9][-a-z0-9._]+@([-a-z0-9]+\.)+[a-z]{2,5}$";
       return Regex.IsMatch(email, regex);
  }

Formatting phonenumber by removing all alphabets and characters except "+" and numbers in c#.

        public static string FormatPhoneNumber(string phoneNumber)
        {
            phoneNumber = Regex.Replace(phoneNumber, "[^0-9+]", "");
            if (phoneNumber == "+")
            {
                phoneNumber = string.Empty;
            }
            return phoneNumber;
        } 

Thursday, 17 October 2019

Authentication and Authorization in .Net core razor pages with Policies.

Step 1: Update your "Startup.cs=>ConfigureServices" method with following code:
services.Configure<CookiePolicyOptions>(options =>
{
    options.CheckConsentNeeded = context => true;
    options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.AccessDeniedPath = "/account/accessDenied";
        options.LoginPath = "/account/login";
    });

Step 2: Update "Startup.cs=>Configure" method with following code lines:
app.UseCookiePolicy();
app.UseAuthentication();

Step 3: Design Login page with following html code:
@page
@model LoginModel
@{
}
<form method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed">
    <h3 class="text-center">Login</h3>
    <hr />
    <div class="row form-group">
        <label class="col-md-4">User Name</label>
        <div class="col-md-4">
            <input type="text" asp-for="Email" />
        </div>
    </div>
    <div class="row form-group">
        <label class="col-md-4">Password</label>
        <div class="col-md-4">
            <input type="text" asp-for="Password" />
        </div>
    </div>
    <div class="row form-group">
        <label class="col-md-4"></label>
        <div class="col-md-4">
            <input type="submit" value="Submit" class="btn btn-primary" />
        </div>
    </div>
</form>


@if (!string.IsNullOrWhiteSpace(Model.Message))
{
    <div>
        <h3>@Model.Message</h3>
    </div>
}
@section Scripts{
    <script src="~/js/jquery.unobtrusive-ajax.js"></script>
    <script>
        function completed(data) {
            window.location.href = "/";
        }
    </script>
}
<style>
    form {
        max-width: 500px;
        margin: 50px auto 0 auto;
        padding: 20px;
        border: 1px solid grey;
    }
</style>

Step 4: Update code behind file "LoginModel.cs" file with following code:
  public class LoginModel : PageModel
    {
        [BindProperty]
        public string Email { get; set; }
        [BindProperty]
        public string Password { get; set;  }
        [BindProperty]
        public string Message { get; set;  }
        public void OnGet()
        {
        }

        public async Task<JsonResult> OnPostAsync()
        {
            var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name,Email),
                    new Claim(ClaimTypes.Email,Email),
                    new Claim(ClaimTypes.Role,"admin")
                    };

            var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var authProperties = new AuthenticationProperties
            {
                IsPersistent = false,
                RedirectUri = this.Request.Host.Value
            };

            await HttpContext.SignInAsync(
               CookieAuthenticationDefaults.AuthenticationScheme,
               new ClaimsPrincipal(claimsIdentity),
               authProperties);

            return new JsonResult(new { success = true });
        }
    }

Note: Now you have successfully implemented the cookies based security in your .net core razor pages app. This authentication bypass the [Authorize] attribute after successfully login. However if you want to implement your custom attribute with additional checks then you have to implement policies. Adding Custom attribute like MVC in .net core razor pages is not possible. So for this purpose, .net core provides Policies. Continue with following steps to implement policy in your .net core razor pages application.

Step 5: Add new class named "SessionTimeoutRequirement.cs" and update as bellow code:
 public class SessionTimeoutRequirement : IAuthorizationRequirement
    {
        public SessionTimeoutRequirement(string usernamePattern)//Remove "usernamePattern" parameter if no need.
        {
            UsernamePattern = usernamePattern;
        }

        public string UsernamePattern { get; } //Remove this property if no need.
    }

Step 6: Add new class named "SessionTimeoutRequirementHandler.cs" and update with following code:
 public class SessionTimeoutRequirementHandler : AuthorizationHandler<SessionTimeoutRequirement>
    {
        protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, SessionTimeoutRequirement requirement)
        {
// Write your custom logic to implement
            if (context.User.Identity.Name == requirement.UsernamePattern)
            {
                context.Succeed(requirement);
            }

            return Task.CompletedTask;
        }
    }

Step 7: Update your "Startup.cs=>ConfigureServices" method with following code:
services.AddAuthorization(options =>
{
    options.AddPolicy("RolePolicy", policy => policy.RequireClaim(ClaimTypes.Role, "Admin"));
    options.AddPolicy("SessionTimeoutPolicy", policy => policy.Requirements.Add(new SessionTimeoutRequirement("test")));
});

Step 8: Now specify the policy with authorize attribute as following code:
[Authorize(Policy = "SessionTimeoutPolicy")]
public class IndexModel : PageModel
{
    public void OnGet()
    {
    }
}

Friday, 4 October 2019

Add .NET Core DI(Dependency Injection) and Config settings using appsettings.json file to AWS Lambda Functions.

Step 1: Add following nuget packages into your .Net core AWS Lamda project:
1. Microsoft.Extensions.DependencyInjection
2. Microsoft.Extensions.Configuration
3. Microsoft.Extensions.Configuration.FileExtensions
4. Microsoft.Extensions.Configuration.Json

Note: Versions of NuGet packages you install need to match the version of .NET Core supported by AWS Lambda for the project you created.  In this example it is 2.1.0.

Step 2: Add new file named appsettings.json in root of your .Net core AWS Lambda project and Define your keys as bellow:
{
  "TestKeys": {
    "Key1": "value1",
    "Key2": "value2",
   }
}

Step 3: Add new AppSettings.cs file as bellow:
    public class AppSettings
    {
        public string Key1 { get; set; }
        public string Key2 { get; set; }
    }

Step 4: Add new Interface named IConfigurationService.cs as bellow:
    public interface IConfigurationService
    {
        AppSettings GetAppSettings();
    }

Step 5: Add new class named ConfigurationService.cs and implement IConfigurationService.cs interface on it. Here method GetAppSettings() reads the appsettings.json file and fill the data into AppSettings and return.
  public class ConfigurationService : IConfigurationService
    {
        private readonly IConfiguration _configuration;
        public ConfigurationService()
        {
            _configuration = getConfiguration();
        }

        public AppSettings GetAppSettings()
        {
            var appSettings = new AppSettings
            {
                Key1 = _configuration["TestKeys:Key1"],
                Key2 = _configuration["TestKeys:Key2"]
            };

            return appSettings;
        }
        private IConfiguration getConfiguration()
        {
            return new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json")
                .Build();
        }
    }

Step 6: Now time to define dependencies of your service classes. Add new class named Startup.cs in root of your project.
   public class Startup
    {
        public static void ConfigureServices(IServiceCollection serviceCollection)
        {
            serviceCollection.AddTransient<IConfigurationService, ConfigurationService>();
            serviceCollection.AddTransient<IYourService, YourService>();
        }
    }

Step 7: Set up Dependency Injection in your main class Functions.cs as bellow:
    public class Function
    {
        IYourService _yourService = null;
        public Function()
        {
            var serviceCollection = new ServiceCollection();
            Startup.ConfigureServices(serviceCollection);
            var serviceProvider = serviceCollection.BuildServiceProvider();
            _yourService = serviceProvider.GetService<IYourService>();
        }

        public async Task<string> FunctionHandler(YourModel input, ILambdaContext context)
        {
            var result = await _yourService.Test(input);
            return JsonConvert.SerializeObject(result);
        }
    }

Step 8: Using the appsettings.js keys into service classes.
public class YourService : IYourService
{
private readonly AppSettings _appSettings;
public EmailService(IConfigurationService configurationService)
  {
        _appSettings = configurationService.GetAppSettings();
  }

public AppSettings Test(){
string key1=_appSettings.Key1;
string key2=_appSettings.Key2;
return _appSettings;
}
}

Now you are all set to use dependency injection and appsetings.json keys in your .Net core AWS Lambda function.