Monday, September 17, 2007

SharePoint 2007: Using AllowUnsafeUpdate to Dynamically Change User Id

For a recent development, the customer had a requirement wherein the user should be able to change his/her user id at any time. For this, the user need not log on to the site (created in WSS 3.0). Just selects an option on the "Login" page, which then takes the user to the page where he/she can provide a new user id.

Of course, the system first validates the user's old id and password, but that's what not this post is about. The interesting bit is how we got this working. Also, just FYI, we would delete the old user id and create a new one (for reasons out of scope of this blog). If we consider this practically, there are only a few ways in which this can be done:

1. User makes a request to change the id. Task is created for the administrator, who then does the needful. Ideal!!!
2. Let the users themselves make the change.

There's no issues in the first approach. In the second one, there are a couple of problems. In the code to make the relevant changes to SharePoint:

1. ...it can automatically log on with the provided credentials and "try" and make the changes.
2. ...or, it could - again, automatically - log on as an administrator and make the changes.

In the first approach - log on as user - the moment the current user id is deleted, the system would either throw an exception or not allow the operation at all because the user is indeed currently logged on. Also, the user may not have sufficient priviliges to perform "delete" operations.

In either case, you have to log on as "someone" so that you can access the SharePoint resources. Or else it would shout (read "throw execptions") at you.

So, the only viable solution here seems to be the code automatically logs on as administrator. This again could be done by having the administrators credentials stored in some config file somewhere (or in some registry entry) and get it to work.

But, the way my co-worker resolved this problem was what I was not happy about. He used neither of the above two methods to change the user id. All he did was use a property called AllowUnsafeUpdate of the SPWeb class. He just set it to true and voila! Everything worked.

He was setting it to false immediately afterwards, but what I kept pondering over was "Is this the right approach?". I couldn't spend much time on it and neither could ask the developer to look for an alternative as the team was anyways short of time (ho-hum). But if anyone can enlighten me on this, I'd really appreciate it.

No comments: