I am trying to develop a Custom Page, wherein, I am trying to get a List of all Components that are present in a particular publication.
In the Page Load of the aspx page, I need to get the session for the currently logged in User.
When I try to use the code
Session currSession = new Session();
Response.Write(currSession.User.Id);
I get the following error.
Access is denied for the user NT AUTHORITY\NETWORK SERVICE
When I try the code with
Session currSession = new Session(WindowsIdentity.GetCurrent());
Response.Write(currSession.User.Id);
I get the following error.
The name 'WindowsIdentity' does not exist in the current context
1.) What should be a proper method to get the session in a Custom Page ?
Can we use the HttpContext.Current.Request.ServerVariables.Get("REMOTE_USER"), to get the user.
2.) Should Custom Page use CoreServices or TOM.NET API's to get information from CM. Which is the preferred option.
You cannot use the TOM.NET API for processes other than Templates and Event System. Please use the Core Service API instead for this (there you won't need a Session).
I might rephrase this to: you should not use the TOM.NET API for processes other than Templates and Event System. As technically it is possible, but it's not supposed to be used like that, that is what the core service is introduced for.
If you want to use Windows Authentication, you can use this snippet to view the current user and the roles attached in your .aspx:
<%# Import Namespace="System.Web.Security" %>
<%
string[] rolesArray = Roles.GetRolesForUser();
Response.Write("<strong>LoggedIn User = </strong>" + HttpContext.Current.User.Identity.Name + "<br />");
Response.Write("<strong>Roles LoggedIn User = </strong><br />" + string.Join(",<br />", rolesArray));
%>
Maybe you need to add this to the web.config of your custom page:
<authentication mode="Windows" />
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider" />
Hope this helps,
Guus
Related
I need to develop an iPhone client that consumes JSON data from somewhere. I chose Web API from MS because it seemed easy enough but when it comes to authenticating users, things get quite frustrating.
I am amazed how I've not been able to find a clear example of how to authenticate a user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.
This is not a question but a request for an example of how to do this exactly. I have looked at the following pages:
Making your ASP.NET Web API's Secure
Basic Authentication With ASP.NET Web API
Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.
Anyone willing to write a nice simple example or point me in the right direction, please?
I am amazed how I've not been able to find a clear example of how to authenticate a user right from the login screen down to using the Authorize attribute over my ApiController methods after several hours of Googling.
That's because you are getting confused about these two concepts:
Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:
Who is the user?
Is the user really who he/she represents himself to be?
Authorization is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:
Is user X authorized to access resource R?
Is user X authorized to perform operation P?
Is user X authorized to perform operation P on resource R?
The Authorize attribute in MVC is used to apply access rules, for example:
[System.Web.Http.Authorize(Roles = "Admin, Super User")]
public ActionResult AdministratorsOnly()
{
return View();
}
The above rule will allow only users in the Admin and Super User roles to access the method
These rules can also be set in the web.config file, using the location element. Example:
<location path="Home/AdministratorsOnly">
<system.web>
<authorization>
<allow roles="Administrators"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
However, before those authorization rules are executed, you have to be authenticated to the current web site.
Even though these explain how to handle unauthorized requests, these do not demonstrate clearly something like a LoginController or something like that to ask for user credentials and validate them.
From here, we could split the problem in two:
Authenticate users when consuming the Web API services within the same Web application
This would be the simplest approach, because you would rely on the Authentication in ASP.Net
This is a simple example:
Web.config
<authentication mode="Forms">
<forms
protection="All"
slidingExpiration="true"
loginUrl="account/login"
cookieless="UseCookies"
enableCrossAppRedirects="false"
name="cookieName"
/>
</authentication>
Users will be redirected to the account/login route, there you would render custom controls to ask for user credentials and then you would set the authentication cookie using:
if (ModelState.IsValid)
{
if (Membership.ValidateUser(model.UserName, model.Password))
{
FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "The user name or password provided is incorrect.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
Cross - platform authentication
This case would be when you are only exposing Web API services within the Web application therefore, you would have another client consuming the services, the client could be another Web application or any .Net application (Win Forms, WPF, console, Windows service, etc)
For example assume that you will be consuming the Web API service from another web application on the same network domain (within an intranet), in this case you could rely on the Windows authentication provided by ASP.Net.
<authentication mode="Windows" />
If your services are exposed on the Internet, then you would need to pass the authenticated tokens to each Web API service.
For more info, take a loot to the following articles:
http://stevescodingblog.co.uk/basic-authentication-with-asp-net-webapi/
http://codebetter.com/johnvpetersen/2012/04/02/making-your-asp-net-web-apis-secure/
If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.
void EnsureAuthenticated(string role)
{
string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
if (role != null && !Roles.IsUserInRole(parts[0], role))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}
From the client side, this helper creates a HttpClient with the authentication header in place:
static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
return client;
}
I am working on a MVC5/Web API project and needed to be able to get authorization for the Web Api methods. When my index view is first loaded I make a call to the 'token' Web API method which I believe is created automatically.
The client side code (CoffeeScript) to get the token is:
getAuthenticationToken = (username, password) ->
dataToSend = "username=" + username + "&password=" + password
dataToSend += "&grant_type=password"
$.post("/token", dataToSend).success saveAccessToken
If successful the following is called, which saves the authentication token locally:
saveAccessToken = (response) ->
window.authenticationToken = response.access_token
Then if I need to make an Ajax call to a Web API method that has the [Authorize] tag I simply add the following header to my Ajax call:
{ "Authorization": "Bearer " + window.authenticationToken }
In my MVC application I want to render a table in a cshtml file, if the current log in user is some x person. I am using windows authentication and I have made the following changes in web.config file.
<authentication mode="Windows">
</authentication>
And in my controller when I am trying to access the current user name I am not getting any user name. I am trying the following:
ViewBag.LogInUserName = Request.RequestContext.HttpContext.User.Identity.Name;
This above line was working before. But I don't know whats wrong now. Also I have hosted my application on IIS now.
Take a look at the web project's properties, in particular:
Anonymous Authentication - Set to "Disabled"
Windows Authentication - Set to "Enabled"
By default these are set to the opposite of what you're probably looking for.
(Image sourced from MSDN)
You need to put the [Authorize] attribute on your controller.
You can use User.Identity.Name in your controllers.
[Authorize]
public class YourController : Controller
{
public ActionResult SomeAction()
{
var userName = User.Identity.Name;
}
}
A little bit late, but this may serve others in the future.
I had the same problem once after deploying my site to a new IIS server, and the anonymous authentication was enabled, so make sure that anonymous authentication is disabled and it should work.
We have a lot of domains running on one IIS WebSite/AppPool.
Right now we are in the process of implementing SSO with Windows Identity Foundation.
in web.config the realm has to be set with
<wsFederation passiveRedirectEnabled="true" issuer="http://issuer.com" realm="http://realm.com" requireHttps="false" />
My problem is that the realm is dependent on which domain the user accessed the website on
so what I did is that I set it in an global action filter like this
var module = context.HttpContext.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as WSFederationAuthenticationModule;
module.Realm = "http://" + siteInfo.DomainName;
My question is. When I set the realm like this, is it set per user instance
or application instance.
Scenario.
User A loads the page and the realm get set to domain.a.com.
User B is already logged in on domain.b.com and presses login.
Since user A loaded the page before User B pressed login, user A will hit the STS
with the wrong realm set.
What will happen here?
If this is not the way to set the realm per user instance, is there another way to do it?
I have already solved the problem.
I set PassiveRedirectEnabled to false in web.config
I set up the mvc project to use forms authentication, eventhough I dont.
I do that so that I will get redirected to my login controller with a return url everytime a controller with [Authorize] is run.
In my login controller I do
var module = HttpContext.ApplicationInstance.Modules["WSFederationAuthenticationModule"] as WSFederationAuthenticationModule;
module.PassiveRedirectEnabled = true;
SignInRequestMessage mess = module.CreateSignInRequest("passive", returnUrl, false);
mess.Realm = "http://" + Request.Url.Host.ToLower();
HttpContext.Response.Redirect(mess.WriteQueryString());
This is definitely not really how it should be, for me it feels like Windows Identity Foundation is lagging behind, both in documentation and microsoft technology wise, no examples for MVC.
For other MVC people i recommend them to not use the fedutil wizard, and instead write the code and configuration themself
My ASP.NET app is using windows authentication. If I run the following code:
WindowsIdentity wi = (WindowsIdentity)User.Identity;
foreach (IdentityReference r in wi.Groups)
{
ListBox1.Items.Add(r.Translate (typeof (NTAccount)).Value);
}
if (User.IsInRole ("Everyone"))
Label1.Text = "Is in role";
The listbox will contain the name of every group the user belongs to. If I then call User.IsInRole, and pass in the name of any of those groups, I always get a false.
Can anyone tell me what I am doing wrong?
Thanks
We need to see your web.config. How are roles handled? Is the role manager even enabled?
EDIT:
You need to use this format:
User.IsInRole(#"DOMAINNAME\rolename")
You are leaving off the domain name. If that still doesn't work, make sure you've got your role provider set in web.config:
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>
This information comes straight from MSDN. Look at the "Checking Role Membership in Code" section. It's all there.
I'm trying to understand how error handling works when using the Authorize [Authorize] Action Filter in MVC Preview 4.
I have an action that looks like this:
[Authorize(Roles = "DOMAIN\\NOTAUTHORISED_ROLE" )]
[HandleError]
public ActionResult NeedAuthorisation()
{
throw new NotImplementedException();
}
When I visit the url: http://localhost:2197/testAuthorisation/NeedAuthorisation, I get a blank page in my browser. In Firebug I can see that a request was made and a response-status of 401 - Unauthorised has been returned. But I'm not being redirected or having a customError returned. Everything works as expected when using a role that I'm authorized for.
This is using Windows authentication. I'm in the middle of writing some code to try out Forms authentication to see if I get the same issue.
I have <customerrors mode="On"/> set and have created error pages, both in the testAuthorisation folder and the Shared folder.
I eventually found this MVC tutorial which solved my problem:
Exactly what happens when you attempt to invoke a controller action
without being the right permissions depends on the type of
authentication enabled. By default, when using the ASP.NET Development
Server, you simply get a blank page. The page is served with a 401 Not
Authorized HTTP Response Status.
If you've got CustomErrors set to Off or RemoteOnly then you won't get re-directed to the page specified by HandleError (default is Error.aspx). Set it to "On" and then see what happens. Any custom error pages you specify explicitly will take precedence, however, so you need to remove these, and have just:
<customErrors mode="On" />
You need an error view in the corresponding view folder, i.e. you need the file Views/TestAuthorization/Error.aspx in order to have anything show up.
You can also customize this behaviour by what view that you want to use and to what exception you want it to be triggered with.
[HandleError(ExceptionType = typeof(SqlException), View = "DatabaseError")]]
[HandleError(ExceptionType = typeof(NullReferenceException), View = "LameErrorHandling")]]