Set Form authentication in WEB API - javascript

Actually i have two project. One for Mvc and another one is Web Api. I have written form as below in mvc project.
<form>
<div class="form-group">
<input type="email" class="form-control" id="email" placeholder="Username">
</div>
<div class="form-group">
<input type="password" class="form-control" id="pwd" placeholder="Password">
</div>
<div class="checkbox">
<input class="customCheckBox" onclick="setIsRemember()" type="checkbox" name="" value="false"><label for=""><span><span></span></span>Remember me</label>
</div>
<button id="buttonSubmit" class="btn btn-default">LOG IN</button>
</form>
Then i have written script for cross domain as below,
$("#buttonSubmit").click(function (e) {
var user =
{
UserName: $("#email").val(),
Password: $("#pwd").val(),
IsRemember: $(".customCheckBox").val()
}
$.ajax({
type: "POST",
url: "http://localhost:55016/api/ajaxapi/loginmethod",
data: user,
success: function (response) {
if (response.Success == false) {
alert("login fail");
}
if (response.Success == true) {
alert("login true");
}
}
});
});
I have written login credential checking in web Api. After login success i have set form authentication as below in web api source,
public class UserLogOn
{
public interface IFormsAuthentication
{
void SignIn(string userName, bool createPersistentCookie);
void SignOut();
}
public IFormsAuthentication FormsAuth
{
get;
private set;
}
public void FormsChange(IFormsAuthentication formsAuth)
{
this.FormsAuth = formsAuth ?? new FormsAuthenticationService();
}
public void LogOnUserCookieCreation(UserValuesForLogOn user)
{
this.FormsChange(null);
this.FormsAuth.SignIn(user.UserName, user.IsRemember);
if (user.IsRemember)
{
HttpCookie cookie = new HttpCookie("SignedIn");
cookie.Values.Add("UserName", user.UserName);
cookie.Values.Add("Password", user.Password);
FormsAuthentication.SetAuthCookie(user.UserName, true);
System.Web.HttpContext.Current.Response.Cookies.Add(cookie);
}
}
public class FormsAuthenticationService : IFormsAuthentication
{
public void SignIn(string userName, bool createPersistentCookie)
{
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
public void SignOut()
{
FormsAuthentication.SignOut();
}
}
When this above code is working if set authentication in same project. But its not working when set authentication using webapi. Please share your suggestion.
Thanks......

Related

Insert Category data in mvc using jquery

my java code is not working when pulling data in database.
Where am I going wrong? I tried many times but it didn't work.
I'm looking at debug mode mastercontroller. data is not coming.
I have jquery.min.js attached on my layout page.
I tried another js code as a trial, it works. I'm waiting for your help
My java code is not working when adding category array to mvc using jquery
//categoryaddt.js
$(document).ready(function () {
$("#categoryform").validate({
rules: {
Name: { required: true },
},
messages: {
Nanem: "Please Enter a Valid Name."
},
submitHandler: function (e) {
var chk = 0;
if ($("#closeButton").prop('checked') == true) {
chk = 1;
}
var RequestCls = {
Name: $("#txtName").val(),
Active: chk
}
var UrlApi = '#Url.Content("~")' + "Master/AddCategory";
$.ajax({
url: UrlApi,
type: 'POST',
data: JSON.stringify(RequestCls),
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.message);
},
error: function (data) {
alert(data.message);
}
});
}
})
});
//Category.cshtml
#{
ViewBag.Title = "Category";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div class="row">
<div class="row">
<div class="card">
<div class="card-body">
<form id="categoryform" method="post">
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="Name">Name</label>
<input id="txtName" name="Name" type="text" class="form-control" autocomplete="off" />
</div>
<div class="custom-control custum-checkbox mb-2">
<input type="checkbox" class="custom-control-input input-mini" id="closeButton" value="checked" />
<label class="custom-control-label" for="closeButton">Is Active</label>
</div>
</div>
</div>
<button type="submit" id="btnSave" class="btn btn-primary mr-1 waves-effect waves-light"></button>
</form>
</div>
</div>
</div>
</div>
#section scripts{
<script src="~/Scripts/categoryaddt.js"></script>
}
//MasterCls.cs
using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls
{
public class MasterCls : IMaster
{
QrperidEntities dbEntity;
public MasterCls()
{
dbEntity = new QrperidEntities();
}
public ResponseCls AddCategory(RequestCls obj)
{
ResponseCls result = new ResponseCls();
result.message = "Kayıt Başarı ile Yapıldı...!";
result.status = "succes";
result.flag = 1;
try
{
using (var db = dbEntity)
{
Category _category = new Category();
_category.Name = obj.Name;
_category.Active = obj.Active;
db.Category.Add(_category);
db.SaveChanges();
}
}
catch (Exception ex)
{
result.message = ex.Message.ToString();
result.status = "error";
result.flag = 0;
}
return result;
}
}
}
//IMaster.cs
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using Nero_Medya_Inventory_Management_System.Utility.Responsecls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Nero_Medya_Inventory_Management_System.BusinessLogic.IService
{
public interface IMaster
{
ResponseCls AddCategory( RequestCls obj );
}
}
//Category.cs
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Nero_Medya_Inventory_Management_System
{
using System;
using System.Collections.Generic;
public partial class Category
{
public int Id { get; set; }
public string Name { get; set; }
public Nullable<int> Active { get; set; }
}
}
//MasterController.cs
using Nero_Medya_Inventory_Management_System.BusinessLogic.IService;
using Nero_Medya_Inventory_Management_System.BusinessLogic.ServiceCls;
using Nero_Medya_Inventory_Management_System.Utility.RequestCls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Nero_Medya_Inventory_Management_System.Controllers
{
public class MasterController : Controller
{
// GET: Master
IMaster _master;
public MasterController()
{
_master = new MasterCls();
}
public ActionResult Category()
{
return View();
}
[HttpPost]
public JsonResult AddCategory(RequestCls obj)
{
var result = _master.AddCategory(obj);
return Json(result,JsonRequestBehavior.AllowGet);
}
}
}

How to send client data to MVC controller for Login page?And save to database?

Login.cshtml
<script type="text/javascript">
function data() {
var n = document.getElementById("username").value;
var m = document.getElementById("password").value;
?
</script>
<button type="submit"class="btn-login" onClick="Data()">
Giriş Yap </button>
Account Controller
DBEntities dB = new DBEntities();
[HttpPost] (username) (password)
public ActionResult Login(string KullaniciAdi,string Sifre)
{
// Session[KullaniciAdi] = dB.Profil.Where(x => x.KullaniciAdi == KullaniciAdi && x.Sifre == Sifre).FirstOrDefault();
var session = (from p in dB.Profil
where p.KullaniciAdi == KullaniciAdi
select p).FirstOrDefault();
return View();
}
My OOP homework is this website and i want to create a login with sending password and username to controller and compare submitted data and the data in the database .Please help :)
You can send client data by using ajax request,
this is your inputs
<input id="username" type="text" />
<input id="password" type="password" />
<input id="loginbutton" onclick="UserLogin()" type="submit" value="Submit" />
Submit button bind with UserLogin js function.
here is the js function. we are sending ajax post request here to our controller
<script type="text/javascript">
function UserLogin() {
var n = document.getElementById("username").value;
var p = document.getElementById("password").value;
var postObj = JSON.stringify({
"username": n,
"password": p
});
$.ajax({
url: "/Home/Login", // endpoint
type: "POST",
data: postObj,
contentType: "application/json; charset=utf-8",
success: function (result) {
// success
},
error: function (errorData) { onError(errorData); }
});
}
</script>
And your controller should be like, you can implement login logic inside of the method.
[HttpPost]
public ActionResult Login(string username, string password)
{
// use your code loged in
return Json(true, JsonRequestBehavior.AllowGet);
}
First You Create a Class :
public class LoginModel
{
[Required(ErrorMessage = "User Name can not be empty!")]
public string LOGINID { get; set; }
[Required(ErrorMessage = "Password can not be empty!")]
public string LOGINPW { get; set; }
}
Then Your Controller Action Method do this:
public ActionResult Login()
{
return View();
}
[HttpPost]
public ActionResult Login(LoginModel model)
{
//Here check the Login Id and Password
return View();
}
Now in view Write this. Now when you click the submit button a post call go to the Login Controller with given LOGINID and LOGINPW :
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
<!-- login screen -->
<form action="#">
#Html.TextBoxFor(m => m.LOGINID, htmlAttributes: new { #class = "form-control", placeholder = "Login ID" })
#Html.ValidationMessageFor(model => model.LOGINID, "", new { #class = "text-danger", style = "float: left" })
#Html.PasswordFor(m => m.LOGINPW, htmlAttributes: new { #class = "form-control", placeholder = "Password" })
#Html.ValidationMessageFor(model => model.LOGINPW, "", new { #class = "text-danger", style = "float: left" })
<button type="submit" class="btn btn-primary" style="background: #2e6da4; color: #FFF;">Login</button>
</form>
}
#{
var actionURL = Url.Action("Action", "Controller",
FormMethod.Post, Request.Url.Scheme)
+ Request.Url.PathAndQuery;
}
#using (Html.BeginForm("Action", "Controller", FormMethod.Post,
new { #action = actionURL }))
{
<input type="text" name="username">
<input type="text" name="password">
<button type="submit"class="btn-login"></button>
}//Then use Request.Form[0] with the id to get the user name and password in the controller action.

Passing BraintreeJS paymentnonce payload to ASP.NET Web Form

I'm trying to integrate Chargebee with Braintree using ChargeBee's API+BraintreeJS (easiest to get PCI compliance). Here is the link of methods that could be used (https://www.chargebee.com/docs/braintree.html). Based on that document, I can conclude that these are the steps
1) Generate clientToken using Braintree SDK for .NET
2) Use BraintreeJS to tokenize all hosted fields and send to Braintree API to get payment nonce
3) Use ChargeBee SDK for .NET and send payment nonce to create subscription in ChargeBee
I've managed to do (1) and (2) but my issue is how could I read the payment nonce during postback? I've tried using controller but still getting null value
Here's my code
<script>
var form = document.querySelector('#cardForm');
var authorization = '<%=clientToken%>';
braintree.client.create({
authorization: authorization
}, function (err, clientInstance) {
if (err) {
console.error(err);
return;
}
createHostedFields(clientInstance);
});
function createHostedFields(clientInstance) {
braintree.hostedFields.create({
client: clientInstance,
styles: {
'input': {
'font-size': '16px',
'font-family': 'courier, monospace',
'font-weight': 'lighter',
'color': '#ccc'
},
':focus': {
'color': 'black'
},
'.valid': {
'color': '#8bdda8'
}
},
fields: {
number: {
selector: '#card-number',
placeholder: '4111 1111 1111 1111'
},
cvv: {
selector: '#cvv',
placeholder: '123'
},
expirationDate: {
selector: '#expiration-date',
placeholder: 'MM/YYYY'
},
postalCode: {
selector: '#postal-code',
placeholder: '11111'
}
}
}, function (hostedFieldsErr, hostedFieldsInstance) {
if (hostedFieldsErr) {
console.error(hostedFieldsErr);
return;
}
submit.removeAttribute('disabled');
form.addEventListener('submit', function (event) {
event.preventDefault();
hostedFieldsInstance.tokenize(function (tokenizeErr, payload) {
if (tokenizeErr) {
console.error(tokenizeErr);
return;
}
// If this was a real integration, this is where you would
// send the nonce to your server.
var noncestr = payload.nonce
alert(noncestr); // Confirm nonce is received.
console.log('Got a nonce: ' + payload.nonce);
$('#paymentmethodnonce').attr("value", noncestr); // Add nonce to form element.
form.submit();
});
}, false);
});
}
</script>
<body>
<div class="demo-frame">
<form action="/" method="post" id="cardForm">
<label class="hosted-fields--label" for="card-number">Card Number</label>
<div id="card-number" class="hosted-field"></div>
<label class="hosted-fields--label" for="expiration-date">Expiration Date</label>
<div id="expiration-date" class="hosted-field"></div>
<label class="hosted-fields--label" for="cvv">CVV</label>
<div id="cvv" class="hosted-field"></div>
<label class="hosted-fields--label" for="postal-code">Postal Code</label>
<div id="postal-code" class="hosted-field"></div>
<div class="button-container">
<input type="submit" class="button button--small button--green" value="Purchase" id="submit" />
</div>
<asp:Label runat="server" ID="lblResult"></asp:Label>
</form>
</div>
<script src="https://js.braintreegateway.com/web/3.8.0/js/client.js"></script>
<script src="https://js.braintreegateway.com/web/3.8.0/js/hosted-fields.js"></script>
</body>
</html>
public partial class Default : System.Web.UI.Page
{
protected string clientToken;
private BraintreeGateway gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "xxx",
PublicKey = "xxx",
PrivateKey = "xxx"
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
//generate clienttoken from braintree sdk
clientToken = gateway.ClientToken.generate();
}
else
{
var paymentnonce = Request.Form["paymentmethodnonce"];
}
}
}
Full disclosure: I work at Braintree. If you have any further questions, feel free to contact support.
The callback that you pass to hostedFieldsInstance.tokenize uses a css selector to find an element with ID paymentmethodnonce and store the generated nonce inside of it. However, there's no element with that ID in the HTML that you submitted. Based on the HTML you've shared, that call should fail, and your subsequent attempt to retrieve paymentmethodnonce using Request.Form will also fail.
You should be able to solve this by adding a hidden input element to your form with the id paymentmethodnonce.
<input type="hidden" id="paymentmethodnonce" />
This will give your tokenize callback a place to put the nonce, and it will make the nonce part of the form, which should allow your Request.Form to retrieve it successfully.

Uploading file and posting text input values in one click?

I'm trying build an Asp.net web api for posting files. I found the following example in
https://code.msdn.microsoft.com/AngularJS-with-Web-API-22f62a6e
The Web API method is:
[RoutePrefix("api/photo")]
public class PhotoController : ApiController
{
private IPhotoManager photoManager;
public PhotoController()
: this(new LocalPhotoManager(HttpRuntime.AppDomainAppPath + #"\Album"))
{
}
public PhotoController(IPhotoManager photoManager)
{
this.photoManager = photoManager;
}
// GET: api/Photo
public async Task<IHttpActionResult> Get()
{
var results = await photoManager.Get();
return Ok(new { photos = results });
}
// POST: api/Photo
public async Task<IHttpActionResult> Post()
{
// Check if the request contains multipart/form-data.
if(!Request.Content.IsMimeMultipartContent("form-data"))
{
return BadRequest("Unsupported media type");
}
try
{
var photos = await photoManager.Add(Request);
return Ok(new { Message = "Photos uploaded ok", Photos = photos });
}
catch (Exception ex)
{
return BadRequest(ex.GetBaseException().Message);
}
}
And the file uploader html code: (I added a text input <input type="text" id="test" value="testit" /> for test.
<form name="newPhotosForm" role="form" enctype="multipart/form-data" ng-disabled="appStatus.busy || photoManagerStatus.uploading">
<div class="form-group" ng-hide="hasFiles">
<label for="newPhotos">select and upload new photos</label>
<input type="file" id="newPhotos" class="uploadFile" accept="image/*" eg-files="photos" has-files="hasFiles" multiple>
<input type="text" id="test" value="testit" /> <!--- Added a text input for test -->
</div>
<div class="form-group" ng-show="hasFiles && !photoManagerStatus.uploading">
<ul class="list-inline">
<li><strong>files:</strong></li>
<li ng-repeat="photo in photos"> {{photo.name}}</li>
</ul>
<input class="btn btn-primary" type="button" eg-upload="upload(photos)" value="upload">
<input class="btn btn-warning" type="reset" value="cancel" />
</div>
<div class="form-group" ng-show="photoManagerStatus.uploading">
<p class="help-block">uploading</p>
</div>
</form>
The JS upload function:
function upload(photos)
{
service.status.uploading = true;
appInfo.setInfo({ busy: true, message: "uploading photos" });
var formData = new FormData();
angular.forEach(photos, function (photo) {
formData.append(photo.name, photo);
});
return photoManagerClient.save(formData)
.$promise
.then(function (result) {
if (result && result.photos) {
result.photos.forEach(function (photo) {
if (!photoExists(photo.name)) {
service.photos.push(photo);
}
});
}
appInfo.setInfo({message: "photos uploaded successfully"});
return result.$promise;
},
function (result) {
appInfo.setInfo({message: "something went wrong: " + result.data.message});
return $q.reject(result);
})
['finally'](
function () {
appInfo.setInfo({ busy: false });
service.status.uploading = false;
});
}
However, it seems the value of the added input test cannot be passed to the Web API code?
You need to add custom DTO/POCO class, set the values and then pass it as parameter to your post method. Since file is not a simple type default MediaTypeFormatter of webAPI won't work so you need to build your custom MediaTypeFormatter.
Sample POCO class
Public Class Attachment
{
public string Input {get;set;}
public byte[] Content{get;set;}
}
Custom Media formatter as below
public class CustomFormatter : MediaTypeFormatter
{
/// <summary>
///
/// </summary>
public CustomFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("multipart/form-data"));
}
public override bool CanReadType(Type type)
{
return type == typeof(Attachment);
}
public override bool CanWriteType(Type type)
{
return false;
}
public async override Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
var provider = await content.ReadAsMultipartAsync();
var modelContent = provider.Contents
.FirstOrDefault(c => c.Headers.ContentType.MediaType == "application/json");
var attachment = await modelContent.ReadAsAsync<Attachment>();
var fileContents = provider.Contents
.Where(c => c.Headers.ContentType.MediaType == "image/jpeg").FirstOrDefault(); // or whatever is the type of file to upload
attachment.Content = await fileContents.ReadAsByteArrayAsync();
return attachment;
}
}
Register the custom media formatter:
private void ConfigureWebApi(HttpConfiguration config)
{
//other code here
config.Formatters.Add(new CustomFormatter());
}
Pass the POCO to your Web-API Controller
public async Task<IHttpActionResult> Post(Attachment attachment)
{
I haven't tested this in Visual Studio, but this is the approach you need to follow
More information here:
http://www.asp.net/web-api/overview/formats-and-model-binding/media-formatters
And a sample here
http://blog.marcinbudny.com/2014/02/sending-binary-data-along-with-rest-api.html#.V5MDDzV7qYg

How to use POST in ApiController

I have searched for at least an hour and a half now and I'm not any closer to learning how to use POST methods in my ApiController. I need an effective way of using post to create a login system that will search my database based on the username/password combination and create a JSON object that I can send back to my web page. Any resources on using post? I've tried to acomplish this with get but I can use any variables more than 'ID'
public IHttpActionResult GetLogin(string id)
{
//Query Database for Unique username.
if (id == "mager1794")
{
//Create Login class with username, and password details.
return Ok( new Models.Login() { id = 1, userName = "mager1794", passWord = "*******" });
}
return Ok(-1);
}
This is what I have for my Get method but I'm just not having any luck creating a POST version of this.
Maybe something like this:
[RoutePrefix("api/account")]
public class AccountController : ApiController
{
public class LoginInfo
{
[Required]
public string Username { get; set; }
[Required]
public string Password { get; set; }
}
[Route("login")]
[HttpPost]
public IHttpActionResult AuthenticateUser(LoginInfo loginInfo)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!Membership.ValidateUser(loginInfo.Username, loginInfo.Password))
{
ModelState.AddModelError("", "Incorrect username or password");
return BadRequest(ModelState);
}
FormsAuthentication.SetAuthCookie(loginInfo.Username, true);
return Ok();
}
}
Client side:
<form action="#" id="login-form">
<label for="username">Username:</label>
<input type="text" name="username" id="username"/>
<label for="password">Password:</label>
<input type="password" name="password" id="password"/>
<div><input type="submit"/></div>
</form>
<script>
$(document).ready(function () {
$("#login-form").submit(function (e) {
e.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: '/api/account/Login/',
data: { Username: username, Password: password },
success: function () {
// refresh the page if username and password are correct
location.reload();
}
});
});
});
</script>

Categories