LDAP user to reset their own password, without older password - openldap

I have the requirement that the ldap user has to change password for himself, without having the older password. As this is for the forgot password feature.
public static JsonObject updatePassword(String username, String newPassword, String dnTemplate) {
JsonObject response=new JsonObject();
String dn = "uid=" + username + "," + dnTemplate;
ModificationItem[] mods = new ModificationItem[1];
mods[0] = new ModificationItem(DirContext.REPLACE_ATTRIBUTE,
new BasicAttribute("userPassword", hashMD5Password(newPassword)));
try {
ldapContext.modifyAttributes(dn, mods);
ldapContext.close();
} catch (NamingException e) {
System.out.println(e);
}
return response;
}
public static void main(String[] args) {
boolean isldapContext=LDAPUtils.initilaizeLDAP("ldap://ip:389","","","");
System.out.println("isldapContext:"+isldapContext);
JsonObject res=LDAPUtils.updatePassword("username","password","ou=People,dc=xxx,dc=xxx");
System.out.println(res);
}
When the above code is executed, m getting the below error:
isldapContext:true
javax.naming.AuthenticationNotSupportedException: [LDAP: error code 8 - modifications require authentication]; remaining name 'uid=111,ou=People,dc=xxx,dc=xxx'

Related

throw exception to change password in ASP.NET

i wanna ask again. How can i resolve this problem
Eror Picture
always find error, and i won't stop. I must be try with help from you guys.
after you look my error, this is my code:
using System;
using System.Web;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Web.SessionState;
namespace FormsAuthAd
{
public class ChangePasswordPSI
{
public bool ChangePass(HttpSessionState Session, string OldPassword, string NewUPassword)
{
string Domain = Session["domain"].ToString();
string Username = Session["username"].ToString();
try
{
string ldapPath = "LDAP://MyDomain.com";
DirectoryEntry user = new DirectoryEntry(ldapPath, Domain + "\\" + Username, OldPassword);
if (user != null)
{
DirectorySearcher search = new DirectorySearcher(user);
search.Filter = "(SAMAccountName=" + Username + ")";
search.PropertiesToLoad.Add("cn");
SearchResult result = search.FindOne();
if (result != null)
{
object ret = user.Invoke("ChangeUserPassword", new object[] { OldPassword, NewUPassword });
user.CommitChanges();
return true;
}
}
}
catch (Exception ex)
{
throw ex;
}
return false;
}
}
}
can somebody tell me, what should i do?
thank you
If you are using try..catch and cannot find where exactly the exception occurred, delete try and catch and execute the code again. In your example, it might happen on Invoke("ChangeUserPassword"... - as far as I see the method name should be "ChangePassword"
https://msdn.microsoft.com/en-us/library/ms180896(v=vs.80).aspx

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

Encrypt and decrypt FormsAuthenticationTicket to authenticate users

I'm trying to create my own authentication mechanism which relies on FormsAuthentication. I'm basically using OAuth to allow users to authenticate in an Authorization Server, and once they are authenticated, I need to use FormsAuthentication to authenticate them across the session. So anyway, I created an HttpModule and a helper class to make this work. Unfortunately, it does not.
What happens is that on PostAuthenticateRequest I encrypt the ticket and add a cookie to the response, then redirect the user to the root of the website. Once the user is re-directed, another HTTP request is issued so the HttpModule is triggered again, and on the AuthenticateRequest event I'm checking whether this user is authenticated or not. In order to check if the user is authenticated, I'm trying to read the cookie, get the username from it and then set the Thread.CurrentPrincipal property. But, for some reason, the cookie cannot be found.
Here's my code:
public class OAuthModule : IHttpModule
{
private const String USERNAME = "username";
public void Dispose()
{
}
public void Init(HttpApplication context)
{
context.AuthenticateRequest += context_AuthenticateRequest;
context.PostAuthenticateRequest += context_PostAuthenticateRequest;
}
void context_PostAuthenticateRequest(object sender, EventArgs e)
{
var application = sender as HttpApplication;
if (application != null)
{
String username = application.Context.Items[USERNAME].ToString();
String uri = RemoveQueryStringFromUri(application.Context.Request.Url.AbsoluteUri);
var cookie = IdentityHelper.GetEncryptedFormsAuthenticationCookie(username, uri);
application.Context.Response.Cookies.Add(cookie);
application.Context.Response.Redirect(uri);
}
}
void context_AuthenticateRequest(object sender, EventArgs e)
{
HttpApplication application = sender as HttpApplication;
if (sender != null)
{
if (!application.Context.Request.Url.AbsolutePath.Contains("."))
{
if (!IdentityHelper.IsAuthenticated)
{
HttpContextWrapper wrapper = new HttpContextWrapper(application.Context);
String clientId = WebConfigurationManager.AppSettings["ClientId"];
String clientSecret = WebConfigurationManager.AppSettings["ClientSecret"];
String authorizationServerAddress = WebConfigurationManager.AppSettings["AuthorizationServerAddress"];
var client = OAuthClientFactory.CreateWebServerClient(clientId, clientSecret, authorizationServerAddress);
if (String.IsNullOrEmpty(application.Context.Request.QueryString["code"]))
{
InitAuthentication(wrapper, client);
}
else
{
OnAuthCallback(wrapper, client);
}
}
}
}
}
private void InitAuthentication(HttpContextWrapper context, WebServerClient client)
{
var state = new AuthorizationState();
var uri = context.Request.Url.AbsoluteUri;
uri = RemoveQueryStringFromUri(uri);
state.Callback = new Uri(uri);
var address = "https://localhost";
state.Scope.Add(address);
OutgoingWebResponse outgoingWebResponse = client.PrepareRequestUserAuthorization(state);
outgoingWebResponse.Respond(context);
}
private void OnAuthCallback(HttpContextWrapper context, WebServerClient client)
{
try
{
IAuthorizationState authorizationState = client.ProcessUserAuthorization(context.Request);
AccessToken accessToken = AccessTokenSerializer.Deserialize(authorizationState.AccessToken);
String username = accessToken.User;
context.Items[USERNAME] = username;
}
catch (ProtocolException e)
{
EventLog.WriteEntry("OAuth Client", e.InnerException.Message);
}
}
private String RemoveQueryStringFromUri(String uri)
{
int index = uri.IndexOf('?');
if (index > -1)
{
uri = uri.Substring(0, index);
}
return uri;
}
}
public class IdentityHelper
{
public static Boolean IsAuthenticated
{
get
{
String username = DecryptFormsAuthenticationCookie();
if (!String.IsNullOrEmpty(username))
{
SetIdentity(username);
return Thread.CurrentPrincipal.Identity.IsAuthenticated;
}
return false;
}
}
private static String DecryptFormsAuthenticationCookie()
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null)
{
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
return ticket.UserData;
}
return String.Empty;
}
internal static HttpCookie GetEncryptedFormsAuthenticationCookie(String username, String domain)
{
var expires = DateTime.Now.AddMinutes(30);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, username, DateTime.Now, expires, true, username, FormsAuthentication.FormsCookiePath);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName);
cookie.Value = FormsAuthentication.Encrypt(ticket);
cookie.Domain = domain;
cookie.Expires = expires;
return cookie;
}
private static void SetIdentity(String username)
{
ClaimsIdentity claimsIdentity = new ClaimsIdentity(new List<Claim> { new Claim(ClaimTypes.Name, username) });
var principal = new ClaimsPrincipal(claimsIdentity);
Thread.CurrentPrincipal = principal;
}
}
Where did I go wrong? Any ideas?
Ok so I finally got it solved. It was as simple as the following:
application.Context.Response.Redirect(uri, false);
I needed to tell the module not to kill the current response (hence the false) so it would preserve the cookie in the coming request.

Unable to create user on windows server 2008 due to access permission

I am getting below error while trying to create user on remote computer.
System.UnauthorizedAccessException: General access denied error at System.DirectoryServices.Interop.UnsafeNativeMethods.IAds.GetInfo() at System.DirectoryServices.DirectoryEntry.RefreshCache() at System.DirectoryServices.AccountManagement.PrincipalContext.DoMachineInit() at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize() at System.DirectoryServices.AccountManagement.PrincipalContext.ContextForType(Type t) at System.DirectoryServices.AccountManagement.Principal.GetStoreCtxToUse() at System.DirectoryServices.AccountManagement.Principal.set_DisplayName(String value) at testemail.CreateLocalWindowsAccount(String username, String password, String displayName, String description, Boolean canChangePwd, Boolean pwdExpires)
here is the code.
public void CreateLocalWindowsAccount(string username, string password, string displayName, string description, bool canChangePwd, bool pwdExpires)
{
try
{
PrincipalContext context = new PrincipalContext(ContextType.Machine, "127.0.0.1");
UserPrincipal user = new UserPrincipal(context);
user.SetPassword(password);
user.DisplayName = displayName;
user.Name = username;
user.Description = description;
user.UserCannotChangePassword = canChangePwd;
user.PasswordNeverExpires = pwdExpires;
user.Save();
//now add user to "Users" group so it displays in Control Panel
GroupPrincipal group = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users");
group.Members.Add(user);
group.Save();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

IsAuthenticated is false! weird behaviour + review question

This is the login function (after I validate user name and password, I load user data into "user" variable and call Login function:
public static void Login(IUser user)
{
HttpResponse Response = HttpContext.Current.Response;
HttpRequest Request = HttpContext.Current.Request;
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
user.UserId.ToString(), DateTime.Now, DateTime.Now.AddHours(12), false,
UserResolver.Serialize(user));
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(ticket));
cookie.Path = FormsAuthentication.FormsCookiePath;
Response.Cookies.Add(cookie);
string redirectUrl = user.HomePage;
Response.Redirect(redirectUrl, true);
}
UserResolver is the following class:
public class UserResolver
{
public static IUser Current
{
get
{
IUser user = null;
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity;
FormsAuthenticationTicket ticket = id.Ticket;
user = Desrialize(ticket.UserData);
}
return user;
}
}
public static string Serialize(IUser user)
{
StringBuilder data = new StringBuilder();
StringWriter w = new StringWriter(data);
string type = user.GetType().ToString();
//w.Write(type.Length);
w.WriteLine(user.GetType().ToString());
StringBuilder userData = new StringBuilder();
XmlSerializer serializer = new XmlSerializer(user.GetType());
serializer.Serialize(new StringWriter(userData), user);
w.Write(userData.ToString());
w.Close();
return data.ToString();
}
public static IUser Desrialize(string data)
{
StringReader r = new StringReader(data);
string typeStr = r.ReadLine();
Type type=Type.GetType(typeStr);
string userData = r.ReadToEnd();
XmlSerializer serializer = new XmlSerializer(type);
return (IUser)serializer.Deserialize(new StringReader(userData));
}
}
And the global.asax implements the following:
void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
IPrincipal p = HttpContext.Current.User;
if (p.Identity.IsAuthenticated)
{
IUser user = UserResolver.Current;
Role[] roles = user.GetUserRoles();
HttpContext.Current.User = Thread.CurrentPrincipal =
new GenericPrincipal(p.Identity, Role.ToString(roles));
}
}
First question:
Am I do it right?
Second question - weird thing!
The user variable I pass to Login has 4 members: UserName, Password, Name, Id.
When UserResolver.Current executed, I got the user instance.
I descided to change the user structure - I add an array of Warehouse object.
Since that time, when UserResolver.Current executed (after Login), HttpContext.Current.User.Identity.IsAuthenticated was false and I couldn't get the user data.
When I removed the Warehouse[] from user structure, it starts to be ok again and HttpContext.Current.User.Identity.IsAuthenticated become true after I Login.
What is the reason to this weird behaviour?
First, you don't need to do an HttpContext.Current from Global.asax. Global.asax derives from HttpApplication. So all you need to do is to get the Context property. This might help make that code a little cleaner.
//this is all you need in your global.asax
void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if(Context.User.Identity.IsAuthenticated)
{
var user = UserResolver.Current;
Context.User = Thread.CurrentPrincipal = new UserWrapperPrincipal(user, Context.User.Identity);
}
}
//this helper class separates the complexity
public class UserWrapperPrincipal: IPrincipal, IUser
{
private readonly IUser _user;
private readonly IIdentity _identity;
public UserWrapperPrincipal(IUser user, IIdentity identity)
{
_user = user;
_identity = identity;
}
private IList<string> RoleNames
{
get { return _user.GetUserRoles().Select(role => role.ToString()); }
}
public IIdentity Identity { get { return _identity; } }
public bool IsInRole(string role) { return RoleNames.Contains(role); }
}
Based on your error, it seems like the issue is that either your serializing function or your deserializing function corrupts the data. However, the problem area is probably not those functions. Either there is an issue in serializing the Warehouse object (serializing complex types can sometimes be tricky), or in the serialization of the actual array. Since you are using the default .NET XmlSerializer, There is a good article on customizing and controlling the way different objects are handled available at http://www.diranieh.com/NETSerialization/XMLSerialization.htm .
On another note, are you sure that this is the best way for you to store this data in your application? Storing a user-id and name makes sense. When you start storing serialized arrays of complex objects in your cookie, it might indicate you are not approaching the problem correctly to begin with.
I am guessing that your code is in a log on event somewhere and your building a custom forms auth.
You also need to then build the User object from the cookie on every page request
public class AuthHttpModule : IHttpModule {
public virtual void Init(HttpApplication app) {
app.AuthenticateRequest += new EventHandler(app_AuthenticateRequest);
}
private void app_AuthenticateRequest(object source, EventArgs e) {
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie == null) {
HttpContext.Current.User = null;
} else {
cookie = HttpContext.Current.Response.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(ticket), new string[0]);
}
bool result = HttpContext.Current.Request.IsAuthenticated;
}
}
EDIT
Try adding this to your global
void Application_AuthenticateRequest(Object sender, EventArgs e)
HttpCookie cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null) {
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(new FormsIdentity(ticket), new string[0]);
}
}

Resources