I'm creating one asp.net mvc 4.0 application. in which I want to use default asp.net form authentication.
I've created all required tables in ms sql for storing roles and username password.
help me earliest possible. I'm stuck at this point.
if you are using asp.net mvc 4.0 form authentication with required tables in mssql server.
you can create new user as follows.
[AllowAnonymous]
public JsonResult RegisterUser()
{
String Uid = Request.QueryString["id"];
String Pass = Request.QueryString["pass"];
String username = Uid;
String password = Pass;
try
{
//Session["username"] = username;
Membership.CreateUser(Uid, Pass);
return Json("success", JsonRequestBehavior.AllowGet);
}
catch(Exception e)
{
return Json("falied", JsonRequestBehavior.AllowGet);
}
}
and you can validate the user in the same as follows.
[AllowAnonymous]
public JsonResult ValidateUser()
{
String Uid = Request.QueryString["id"];
String Pass = Request.QueryString["pass"];
String username = Uid;
String password = Pass;
if (Membership.ValidateUser(username, password))
{
//Session["username"] = username;
FormsAuthentication.RedirectFromLoginPage(username, true);
return Json("success", JsonRequestBehavior.AllowGet);
}
else
{
return Json("falied", JsonRequestBehavior.AllowGet);
}
}
Hope this will help you.
Related
I am working with Web API and ASP.NET MVC.
I'm passing a wrong username and password in the address bar then also give the success message that is the issue
This record is not available in my table:
I am creating 2 projects one for Web API framework scaffolding and second is a normal empty ASP.NET MVC project.
Normal empty ASP.NET MVC project (not using Entity Framework)
globalvariable.cs:
namespace Mvc
{
public static class globalvariable
{
public static HttpClient webapiclient = new HttpClient();
static globalvariable()
{
webapiclient.BaseAddress = new Uri("https://localhost:0000/api/");
webapiclient.DefaultRequestHeaders.Clear();
webapiclient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
}
}
}
empsController.cs:
namespace Mvc.Controllers
{
public class empsController : Controller
{
public JsonResult Index()
{
IEnumerable<mvcempmodel> empList;
HttpResponseMessage response = globalvariable.webapiclient.GetAsync("emps").Result;
empList = response.Content.ReadAsAsync<IEnumerable<mvcempmodel>>().Result;
//return View(empList);
return Json(empList, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public JsonResult Login(string username, string password)
{
if (username == "" || username == null)
{
var data = new
{
message = "Enter Username ",
};
return Json(data, JsonRequestBehavior.AllowGet);
}
else if (password == "" || password == null)
{
var data = new
{
message = "Enter Password",
};
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
var userdata = "select * from emp where username='" + username + "'and password='" + password + "'".First();
if (userdata != null)
{
var data = new
{
message = "Success",
data = new { username }
};
return Json(data, JsonRequestBehavior.AllowGet);
}
else
{
var data = new
{
message = "Username and Password incorrect ",
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
}
}
}
}
Web API project (using Entity Framework)
empsController.cs:
namespace WebApi.Controllers
{
public class empsController : ApiController
{
private empdbEntities db = new empdbEntities();
// GET: api/emps
public IQueryable<emp> Getemps()
{
return db.emps;
}
// GET: api/emps/5
[ResponseType(typeof(emp))]
public IHttpActionResult Getemp(int id)
{
emp emp = db.emps.Find(id);
if (emp == null)
{
return NotFound();
}
return Ok(emp);
}
}
}
What I want to If user enter true credential then give the success message and when the user enter false credential then give the username and password incorrect message
Here I think my query is wrong
var userdata = "select * from emp where username='" + username + "'and password='" + password + "'".First();
Please help
You can check this to url (as you mentioned you are a beginner and wanted to know how to query a database)
In asp.net, You can query a database using
Entity framework (the second link shows how to query local db using Entity framework)
Dapper (micro orm, fast)
ADO.net (old school style and required to write a lot of boiler plate code)
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/getting-started
https://learn.microsoft.com/en-us/aspnet/mvc/overview/getting-started/introduction/creating-a-connection-string
To query Sql server database at remote or local server, just change the connection string.
I have a custom validator that validate the incoming username and password in a webservice .
Once the validation is done, i need to use that user name and password inside the webservice .
Here is my CustomValidator
public class ServiceAuthenticator : UserNamePasswordValidator
{
private static readonly ILog _log = LogManager.GetLogger("ServiceAuthenticator");
public override void Validate(String userName, string password)
{
_log.InfoFormat("-------------{0}/{1}------------------------------", userName, password);
if (userName == null || password == null)
{
_log.WarnFormat(" Missing User-name / Password {0}/{1}", userName, password);
throw new FaultException("Incorrect User name or Password");
}
}
}
Now i have a webservice where i am trying to get the above user name and password
[WebInvoke(Method = "POST", UriTemplate = "Uplooc")]
[WebMethod(Description = "Save documents ")]
public void UploadDocGen(RemoteFileInfo remoteFileInfo)
{
// string UserName = ""; --- How i get the username
// sting Password = ""; -- How to get the password into this
}
We could use the ServiceSecurityContext to obtain the username value, while we could not get the password after the credential is authenticated to pass.
public string SayHello()
{
OperationContext oc = OperationContext.Current;
var username1=oc.ServiceSecurityContext.PrimaryIdentity.Name;
Console.WriteLine(username1);
var username2 = ServiceSecurityContext.Current.PrimaryIdentity.Name;
Console.WriteLine(username2);
return $"Hello Buddy,{DateTime.Now.ToLongTimeString()}";
}
Result.
The security token based on the SAML, we only can obtain the claim sets. It is a complex topic, which I don’t know much.
Here are some related documents, wish it is useful to you.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/how-to-examine-the-security-context
https://learn.microsoft.com/en-us/dotnet/api/system.servicemodel.servicesecuritycontext?view=netframework-4.8
Feel free to let me know if there is anything I can help with.
I have implemented google authentication in my mvc site. Here is my sample code-
AuthConfig.cs
public static class AuthConfig
{
private static string GoogleClientId = ConfigurationManager.AppSettings["GoogleClientId"];
private static string GoogleClientSecret = ConfigurationManager.AppSettings["GoogleClientSecret"];
public static void RegisterAuth()
{
GoogleOAuth2Client clientGoog = new GoogleOAuth2Client(GoogleClientId, GoogleClientSecret);
IDictionary<string, string> extraData = new Dictionary<string, string>();
OpenAuth.AuthenticationClients.Add("google", () => clientGoog, extraData);
}
}
Global.asax
AuthConfig.RegisterAuth();
AccountController.cs
public ActionResult RedirectToGoogle()
{
string provider = "google";
string returnUrl = "";
return new ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
}
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
string ProviderName = OpenAuth.GetProviderNameFromCurrentRequest();
if (ProviderName == null || ProviderName == "")
{
NameValueCollection nvs = Request.QueryString;
if (nvs.Count > 0)
{
if (nvs["state"] != null)
{
NameValueCollection provideritem = HttpUtility.ParseQueryString(nvs["state"]);
if (provideritem["__provider__"] != null)
{
ProviderName = provideritem["__provider__"];
}
}
}
}
GoogleOAuth2Client.RewriteRequest();
var redirectUrl = Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl });
var retUrl = returnUrl;
var authResult = OpenAuth.VerifyAuthentication(redirectUrl);
string ProviderDisplayName = OpenAuth.GetProviderDisplayName(ProviderName);
if (authResult.IsSuccessful)
{
string ProviderUserId = authResult.ProviderUserId;
}
return Redirect(Url.Action("Index", "User"));
}
This code is working fine. But I want to restrict the user to sign-in with his/her organizational account like "abc#example.com". Where I can specify the hosted domain property? When I created app id and secret for this app from google dev console, I saw Verify domain tab. Do I need to add my organizational domain here?
You can sort of. You can specify the hd (Hosted Domain) parameter within the Authentication URI parameters.
hd - OPTIONAL - The hd (hosted domain) parameter streamlines the login process for G Suite hosted accounts. By including the domain of the G Suite user (for example, mycollege.edu), you can indicate that the account selection UI should be optimized for accounts at that domain. To optimize for G Suite accounts generally instead of just one domain, use an asterisk: hd=*.
Don't rely on this UI optimization to control who can access your app, as client-side requests can be modified. Be sure to validate that the returned ID token has an hd claim value that matches what you expect (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is contained within a security token from Google, so the value can be trusted.
I need to create a authentication for my MVC Application and WebAPI.
I have the user credential details & role information in a separate table in database. Can anyone suggest which model i can use to achieve this.
Thanks
Which Web Api are you using if it is 2 than try below code, and let me know if i could help you more, because i had same scenario like you have
you have to create a custom authorization filter and call it above ActionMethod,
Create a different class in your project and change build mode in Compile
public class BasicAuthenticationAttribute : AuthorizationFilterAttribute
{
public static bool VaidateUserRoleWise(string username, string password, int RoleId)
{
//DO DATABASE CONNECTION DO QUERY HERE
if (Username == username && Password == password)
{
return true;
}
else
{
return false;
}
}
public override void OnAuthorization(QuizzrApi.Controllers.QuizzrController.InputParamAdminLogin LoginDetails)
{
System.Web.Http.Controllers.HttpActionContext actionContext = null;
if (LoginDetails == null)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
else
{
//Bellow is the static method called above will return true or false if user matches
if (!VaidateUserRoleWise(LoginDetails.UserName, LoginDetails.Password, 1))
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
}
}
base.OnAuthorization(actionContext);
}
}
In controller :
[Route("AuthorizeSystemAdmin")]
[HttpPost]
[BasicAuthentication]
public HttpResponseMessage Login([FromBody] InputParamAdminLogin AdminLoginInput)
{
//do your logic here
}
I'm having trouble solving architecture of an ASP MVC application that servers html pages and web services through ServiceStack.
The application lives in the base url eg "http://myapplication.com" and SS lives in "http://myapplication.com/api" because it is the easiest way to configure both.
In general everything works fine, but when I reached the part of the authorization and authentication, is where I'm stuck.
For one, I need the application handle cookies as ASP normally do FormsAuthentication through, and users would go through a login screen and could consume actions and controllers when the attribute "Authorize" is used. This is typical of ASP, so I have no problem with it, such as "http://myapplication.com/PurchaseOrders".
On the other hand, clients of my application will consume my web service api from javascript. Those web services will also be tagged in some cases with the attribute "Authenticate" of ServiceStack. For example "http://myapplication.com/api/purchaseorders/25" would have to validate if the user can view that particular purchase order, otherwise send a 401 Unauthorized so javascript can handle those cases and display the error message.
Last but not least, another group of users will make use of my API by a token, using any external application (probably Java or .NET). So I need to solve two types of authentication, one using username and password, the other by the token and make them persistant so once they are authenticated the first time, the next calls are faster to solve from the API.
This is the code that I have so far, I've put it very simply to make clear the example.
[HttpPost]
public ActionResult Logon(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
JsonServiceClient client = new JsonServiceClient("http://myapplication.com/api/");
var authRequest = new Auth { provider = CredentialsAuthProvider.Name, UserName = model.UserName, Password = model.Password, RememberMe = model.RememberMe };
try
{
var loginResponse = client.Send(authRequest);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(loginResponse.UserName, false, 60);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(ticket));
Response.Cookies.Add(cookie);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/") && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
else
{
return RedirectToAction("Index", "Test");
}
}
catch (Exception)
{
ModelState.AddModelError("", "Invalid username or password");
}
}
return View();
}
As for the authentication provider I am using this class
public class MyCredentialsAuthProvider : CredentialsAuthProvider
{
public MyCredentialsAuthProvider(AppSettings appSettings)
: base(appSettings)
{
}
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
//Add here your custom auth logic (database calls etc)
//Return true if credentials are valid, otherwise false
if (userName == "testuser" && password == "nevermind")
{
return true;
}
else
{
return false;
}
}
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
//Fill the IAuthSession with data which you want to retrieve in the app eg:
session.FirstName = "some_firstname_from_db";
//...
session.CreatedAt = DateTime.Now;
session.DisplayName = "Mauricio Leyzaola";
session.Email = "mauricio.leyzaola#gmail.com";
session.FirstName = "Mauricio";
session.IsAuthenticated = true;
session.LastName = "Leyzaola";
session.UserName = "mauricio.leyzaola";
session.UserAuthName = session.UserName;
var roles = new List<string>();
roles.AddRange(new[] { "admin", "reader" });
session.Roles = roles;
session.UserAuthId = "uniqueid-from-database";
//base.OnAuthenticated(authService, session, tokens, authInfo);
authService.SaveSession(session, SessionExpiry);
}
}
On the Configure function of AppHost I am setting my custom authentication class to use it as the default. I guess I should create another class and add it here as well, to handle the token scenario.
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new MyCredentialsAuthProvider(appSettings)
}, htmlRedirect: "~/Account/Logon"));
So far, ServiceStack is working as expected. I can submit a post to /auth/credentials passing username and password and it stores this information, so next call to a service the request is already authorized, great so far!
The question I need to know is how to call (and probably set somewhere in SS) the user that is logging in from my Account controller. If you see the first block of code I am trying to call the web service (looks like I am doing it wrong) and it works, but the next call to any web service looks unauthenticated.
Please don't point me to ServiceStack tutorials, I've been there for the last two days and still cannot figure it out.
Thanks a lot in advance.
Here is what I usually use:
You can replace the "Logon" action method with the code below:
public ActionResult Login(LogOnModel model, string returnUrl)
{
if (ModelState.IsValid)
{
try
{
var authService = AppHostBase.Resolve<AuthService>();
authService.RequestContext = System.Web.HttpContext.Current.ToRequestContext();
var response = authService.Authenticate(new Auth
{
UserName = model.UserName,
Password = model.Password,
RememberMe = model.RememberMe
});
// add ASP.NET auth cookie
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToLocal(returnUrl);
}
catch (HttpError)
{
}
}
// If we got this far, something failed, redisplay form
ModelState.AddModelError("", "The user name or password provided is incorrect.");
return View(model);
}
...and the plugins:
//Default route: /auth/{provider}
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new CustomCredentialsAuthProvider(),
new CustomBasicAuthProvider()
}));
....the Auth provider classes:
public class CustomCredentialsAuthProvider : CredentialsAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
return UserLogUtil.LogUser(authService, userName, password);
}
}
public class CustomBasicAuthProvider : BasicAuthProvider
{
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
return UserLogUtil.LogUser(authService, userName, password);
}
}
...finally, the logging utility class
internal static class UserLogUtil
{
public static bool LogUser(IServiceBase authService, string userName, string password)
{
var userService = new UserService(); //This can be a webservice; or, you can just call your repository from here
var loggingResponse = (UserLogResponse)userService.Post(new LoggingUser { UserName = userName, Password = password });
if (loggingResponse.User != null && loggingResponse.ResponseStatus == null)
{
var session = (CustomUserSession)authService.GetSession(false);
session.DisplayName = loggingResponse.User.FName.ValOrEmpty() + " " + loggingResponse.User.LName.ValOrEmpty();
session.UserAuthId = userName;
session.IsAuthenticated = true;
session.Id = loggingResponse.User.UserID.ToString();
// add roles and permissions
//session.Roles = new List<string>();
//session.Permissions = new List<string>();
//session.Roles.Add("Admin);
//session.Permissions.Add("Admin");
return true;
}
else
return false;
}
}