Access denied error - asp.net

i created a web application on (Machine 1) and published it in IIS 7 (this machine running windows server 2008),from another machine (machine 2) running windows 2008 i send url string to create local windows account on the other machine (i.e machine1) but i always get access denied error.
here th code snippet of create user account on machine1
protected void Page_Load(object sender, EventArgs e)
{
try
{
if (Request.QueryString["UserName"] != null)
{
if (createUserAccount(Decrypt(HttpUtility.UrlDecode(Request.QueryString["UserName"].ToString())), Decrypt(HttpUtility.UrlDecode(Request.QueryString["Password"].ToString())), Convert.ToDateTime(HttpUtility.UrlDecode(Request.QueryString["ExpireDate"].ToString()))))
Response.Write("user created successfuly");
else
Response.Write("failed");
}
else if (Request.QueryString["Account"] != null)
{
if(ChangeExpirationDate(Decrypt(HttpUtility.UrlDecode(Request.QueryString["Account"].ToString())),Convert.ToDateTime(HttpUtility.UrlDecode(Request.QueryString["newExpireDate"].ToString()))))
Response.Write("expiration date was updated successfuly");
else
Response.Write("failed");
}
}
catch (Exception)
{
Response.Redirect("AccessDeniedPage.aspx");
}
}
Boolean createUserAccount(String User, String Pass,DateTime expirationDate)
{
try
{
String currentuser=Environment.UserName;//IUSER
DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer");
DirectoryEntry NewUser = AD.Children.Add(User, "user");
NewUser.Invoke("SetPassword", new object[] { Pass });
NewUser.Invoke("Put", new object[] { "Description", "Virtual account to connect to PLC LAB" });
NewUser.Invoke("Put", new object[] { "AccountExpirationDate", expirationDate });
NewUser.CommitChanges();
DirectoryEntry grp;
grp = AD.Children.Find("Administrators", "group");
if (grp != null)
{
grp.Invoke("Add", new object[] { NewUser.Path.ToString() });
}
return true;
}
catch (Exception exception)
{
return false;
}
}
please help

Related

How can we insert date into the SQLite database

For each data insert in SQLite database, I would like to get insert the current Date as well. How can I do it in Xamarin Forms app ?
Below is my code which now insert some status data into the database.
public void OnOKButtonClicked(object sender, EventArgs e)
{
overlay.IsVisible = false;
DisplayAlert("Result",
string.Format("You entered {0}", EnteredStatus.Text), "OK");
SoccerAvailability soccerAvailability = new SoccerAvailability();
soccerAvailability.SoccerStatus = EnteredStatus.Text;
var dailySoccerStatus = EnteredStatus.Text;
int x = 0;
try
{
if (!string.IsNullOrWhiteSpace(EnteredStatus.Text))
{
//Insert the soccer status to the database:
x = conn.Insert(soccerAvailability);
}
else
{
DisplayAlert("Soccer Availability", "Availability cannot be left blank", "OK");
}
}
catch (Exception ex)
{
throw ex;
}
if (x == 1)
{
Navigation.PushAsync(new Settings(soccerAvailability));
}
DisplaySoccerStatus();
}
just create a CurrentDate DateTime property on your SoccerAvailability model
soccerAvailability.CurrentDate = DateTime.Now;
x = conn.Insert(soccerAvailability);

Trying to prevent session tampering works on local environment but not on prod server

So i want to prevent session tampering in my site and i implemented this in global.asax. What im doing is im generating a hash key using the GenerateHashKey function. which basically uses the browser version,userhost address etc to create a hash key. This hash key im attaching to ASP.NET_SessionId cookie. Now this works perfectly in local environment. but as soon as i host it to prod server, the "Invalid" exception is thrown the first time and then it works fine. why is this happening
I used this article
http://www.codeproject.com/Articles/859579/Hack-proof-your-asp-net-applications-from-Session
protected void Application_BeginRequest(object sender, EventArgs e)
{
try
{
if (Request.Cookies["ASP.NET_SessionId"] != null && Request.Cookies["ASP.NET_SessionId"].Value != null)
{
string newSessionID = Request.Cookies["ASP.NET_SessionId"].Value;
//Check the valid length of your Generated Session ID
if (newSessionID.Length <= 24)
{
//Log the attack details here
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30);
Response.Cookies["ASP.NET_SessionId"].Value = null;
throw new HttpException("Empty");
}
//Genrate Hash key for this User,Browser and machine and match with the Entered NewSessionID
if (GenerateHashKey() != newSessionID.Substring(24))
{
//Log the attack details here
Response.Cookies["TriedTohack"].Value = "True";
Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddDays(-30);
Response.Cookies["ASP.NET_SessionId"].Value = null;
throw new HttpException("Invalid:"+newSessionID);
}
//Use the default one so application will work as usual//ASP.NET_SessionId
Request.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Substring(0, 24);
}
}
catch(Exception Ex)
{
if (Ex.Message == "Invalid")
{
Response.Redirect(string.Format("~/PraiseError.aspx?Message={0}", Uri.EscapeDataString(Ex.Message)));
}
else
{
Response.Redirect("~/Home.aspx");
}
}
}
protected void Application_EndRequest(object sender, EventArgs e)
{
string gn = GenerateHashKey();
try
{
//Pass the custom Session ID to the browser.
if (Response.Cookies["ASP.NET_SessionId"] != null)
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value.Replace(gn, "") + gn;
}
else
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + gn;
}
}
catch
{
Response.Cookies["ASP.NET_SessionId"].Value = Request.Cookies["ASP.NET_SessionId"].Value + gn;
}
}
private string GenerateHashKey()
{
StringBuilder myStr = new StringBuilder();
myStr.Append(Request.Browser.Browser);
myStr.Append(Request.Browser.Platform);
myStr.Append(Request.Browser.MajorVersion);
myStr.Append(Request.Browser.MinorVersion);
myStr.Append(Request.UserHostAddress);
//myStr.Append(Request.LogonUserIdentity.User.Value);
SHA1 sha = new SHA1CryptoServiceProvider();
byte[] hashdata = sha.ComputeHash(Encoding.UTF8.GetBytes(myStr.ToString()));
return Convert.ToBase64String(hashdata);
}

Create New AEM User in adobe CQ with user rights in Java Code

How to create a new adobe aem User with user rights in the java code.
With a SlingAllMethodsServlet you can get the Parameter from a Post Request.
Than you can create a User with the given Informations. the User will be added in the CQ Server with the rights you gave him.
username = request.getParameter("username");
password = request.getParameter("password");
givenname = request.getParameter("givenname");
name = request.getParameter("name");
email = request.getParameter("email");
ResourceResolver resourceResolver = request.getResourceResolver();
Session session = resourceResolver.adaptTo(Session.class);
UserManager userManager = resourceResolver.adaptTo(UserManager.class);
User u = null;
try {
//check if user does exist, easy check with username, username is id in cq
u = (User) userManager.getAuthorizable(username);
} catch (RepositoryException e) {
logger.error("User cannot be checked: " + e.getMessage());
e.printStackTrace();
}
if(u != null) {
logger.error("User" + username + " exists already in CQ!! Can't create user again!");
try {
json.put("error", "User already exists");
response.setStatus(HttpServletResponse.SC_CONFLICT);
} catch (JSONException e) {
logger.error(e.getMessage());
}
}else {
/*Just create user if it does not exist*/
try {
user = userManager.createUser(username, password);
ValueFactory valueFactory = session.getValueFactory();
emailValue = valueFactory.createValue(email);
givennameValue = valueFactory.createValue(givenname);
nameValue = valueFactory.createValue(name);
//User class just accepts Value Object
user.setProperty("profile/" + UserProperties.EMAIL, emailValue);
user.setProperty("profile/" + UserProperties.FAMILY_NAME,nameValue);
user.setProperty("profile/" + UserProperties.GIVEN_NAME, nameValue);
} catch (RepositoryException e) {
logger.error("Failed while creating user: " + e.getMessage());
}
try {
/* add Group to user */
Group g = (Group) userManager.getAuthorizable(GROUP_NAME);
g.addMember(user);
session.save();
session.logout();
} catch (RepositoryException e) {
logger.error("Can't add group to new created User : " + username + e.getMessage());
}
How to get the CQ admin Session / How to get the CQ admin UserManager
if you can't save the user, with session and usermanager then you have to get the admin Session.
Add the dependency for AccessControlUtil (check the version)
add SlingRepository variable as #Reference
login as Administrative to get the admin session (parameter have to be null, or an admin User, than you have to make SimpleCredentials(Name, password.asChar)
get the Usermanager with AccessControlUtil and the admin session
#Reference
private SlingRepository repository;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException {
try {
Session adminSession = repository.loginAdministrative(null);
UserManager usermanager = AccessControlUtil.getUserManager(adminSession);
//your stuff like manipulating user, get authorizab
adminSession.save();
} catch (RepositoryException e) {
e.printStackTrace();
}
}

HttpModule Web Api

I'm trying to get an auth basic on my web api. I've written a simple HttpModule to check it
public class BasicAuth : IHttpModule
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["Connection"].ConnectionString);
private const string Realm = "MyRealm";
public void Init(HttpApplication context)
{
// Register event handlers
context.AuthorizeRequest += new EventHandler(OnApplicationAuthenticateRequest);
context.EndRequest += new EventHandler(OnApplicationEndRequest);
}
private static void SetPrincipal(IPrincipal principal)
{
Thread.CurrentPrincipal = principal;
if (HttpContext.Current != null)
{
HttpContext.Current.User = principal;
}
}
private bool CheckPassword(string username, string password)
{
var parameters = new DynamicParameters();
parameters.Add("#UserName", username);
parameters.Add("#Password", password);
con.Open();
try
{
var query = //query to db to check username and password
return query.Count() == 1 ? true : false;
}
catch
{
return false;
}
finally
{
con.Close();
}
}
private bool AuthenticateUser(string credentials)
{
try
{
var encoding = Encoding.GetEncoding("iso-8859-1");
credentials = encoding.GetString(Convert.FromBase64String(credentials));
int separator = credentials.IndexOf(':');
string name = credentials.Substring(0, separator);
string password = credentials.Substring(separator + 1);
if (CheckPassword(name, password))
{
var identity = new GenericIdentity(name);
SetPrincipal(new GenericPrincipal(identity, null));
return true;
}
else
{
return false;
}
}
catch
{
return false;
}
}
private void OnApplicationAuthenticateRequest(object sender, EventArgs e)
{
var authHeader = request.Headers["Authorization"];
if (authHeader != null)
{
var authHeaderVal = AuthenticationHeaderValue.Parse(authHeader);
// RFC 2617 sec 1.2, "scheme" name is case-insensitive
if (authHeaderVal.Scheme.Equals("basic",
StringComparison.OrdinalIgnoreCase) &&
authHeaderVal.Parameter != null)
{
if (AuthenticateUser(authHeaderVal.Parameter))
{
//user is authenticated
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
else
{
HttpContext.Current.Response.StatusCode = 401;
}
}
catch
{
HttpContext.Current.Response.StatusCode = 401;
}
}
private static void OnApplicationEndRequest(object sender, EventArgs e)
{
var response = HttpContext.Current.Response;
if (response.StatusCode == 401)
{
response.Headers.Add("WWW-Authenticate",
string.Format("Basic realm=\"{0}\"", Realm));
}
}
public void Dispose()
{
}
}
well, this code works pretty well, except the fact it asks for basic auth even on controller I don't put the [Authorize] tag on. And when it occurs, it gives the right data back.
Let me explain:
My HistoryController has [Authorize] attribute, to make a POST request I have to send Header auth to get data, if I don't do it, I receive 401 status code and a custom error.
My HomeController doesn't have [Authorize] attribute, if i make a get request on my homepage, the browser popups the authentication request, but if I hit Cancel it shows my home page. (The page is sent back with 401 error, checked with fiddler).
What am I doing wrong?

How to get access token identity in asp.net webforms external login page?

I'm using the new Microsoft identity to manage my website login and register.
I've configured the website to start using external login (Facebook).
How i can get the Access Token in the (RegisterExternalLogin) page?
``
protected void Page_Load(){
// Process the result from an auth provider in the request
ProviderName = IdentityHelper.GetProviderNameFromRequest(Request);
if (String.IsNullOrEmpty(ProviderName))
{
RedirectOnFail();
return;
}
if (!IsPostBack)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var loginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo();
if (loginInfo == null)
{
RedirectOnFail();
return;
}
var user = manager.Find(loginInfo.Login);
if (user != null)
{
IdentityHelper.SignIn(manager, user, isPersistent: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else if (User.Identity.IsAuthenticated)
{
Response.Write("ok.2");
// Apply Xsrf check when linking
var verifiedloginInfo = Context.GetOwinContext().Authentication.GetExternalLoginInfo(IdentityHelper.XsrfKey, User.Identity.GetUserId());
if (verifiedloginInfo == null)
{
RedirectOnFail();
return;
}
var result = manager.AddLogin(User.Identity.GetUserId(), verifiedloginInfo.Login);
if (result.Succeeded)
{
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
else
{
AddErrors(result);
return;
}
}
else
{
try
{
var accessToken = "What can i get the access token";
Response.Write(accessToken + "<br>");
var client = new FacebookClient(accessToken);
//var client = new FacebookClient();
dynamic me = client.Get("me");
string firstName = me.first_name;
string lastName = me.last_name;
Response.Write(firstName + " " + lastName);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
email.Text = loginInfo.Email;
}
}
}
Regards,
Moayyad

Resources