I cannot seem to get Windows Authentication to work in the Silverlight Business Application.
I have made the changes required see below
Changed to Windows authentication in App.xaml
public App()
{
InitializeComponent();
// Create a WebContext and add it to the ApplicationLifetimeObjects
// collection. This will then be available as WebContext.Current.
WebContext webContext = new WebContext();
//webContext.Authentication = new FormsAuthentication();
webContext.Authentication = new WindowsAuthentication();
this.ApplicationLifetimeObjects.Add(webContext);
}
Changed to Windows authentication in web.config
<authentication mode="Windows"/>
<roleManager enabled="true" defaultProvider="AspNetWindowsTokenRoleProvider"/>
I put a breakpoint on the Application_UserLoaded event but nothing happens:-
private void Application_UserLoaded(LoadUserOperation operation)
{
foreach (var r in WebContext.Current.User.Roles)
{
//do something
}
}
Can anyone suggest what is going wrong. I have made no other changes to the project at all.
This happened to me previously as well. It turned out that Silverlight debugging wasn't enabled in the properties of the Web project. Right click on the .Web project and click on properties. Next click on the Web tab and on the bottom ensure the Silverlight checkbox is checked.
You must have this line in the Application_Startup:
WebContext.Current.Authentication.LoadUser(this.Application_UserLoaded, null);
This will automatically authenticate a user when using Windows authentication.
Related
I'm trying to set up an MVC Core Web App with Windows Authentication in Visual Studio 2022 but I can't get it to work.
I create a new project and select the Windows Authentication option. I immediately try to run the app but I get a blank page.
For troubleshooting I then added the following else clause so I can see what the problem is on my development machine.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
// Development Environment
app.UseStatusCodePages();
}
and I can then see that I have a '401 Unauthorised' status code. And then if I add [AllowAnonymous] to my Index action I can finally see the home page but my windows username is not displayed. I would expect to see 'Hello username' displayed in the top right but I don't seem to be authenticated, let alone authorized.
Apart from the two troubleshooting steps above, this is a brand new project straight out of the box but I've pasted my Program.cs below for reference.
What do I need to do to get Windows Authentication to work?
Thanks
using Microsoft.AspNetCore.Authentication.Negotiate;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
.AddNegotiate();
builder.Services.AddAuthorization(options =>
{
// By default, all incoming requests will be authorized according to the default policy.
options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
else
{
// Development Environment
app.UseStatusCodePages();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
You can follow my steps to fix the issue.
Enable IIS features in your develop machine, this just want to enable Windows authentication on Windows.
Tips: Please expand all the fields and tick them, then click Apply.
Delete the .vs folder inside your project, this steps just want to reset the applicationhost.config.
The latest step, we need to double check the settings file in project.
Then the issue should be fixed now.
I'm building Universal Application,I'm using Azure Active Directory for authentication. I'm using Microsoft.IdentityModel.Clients.ActiveDirectory for SSO. for both Windows 8.1 and Window 10 store App. I've been referring to following URL for connecting to my Azure Active Directory and authenticating user
http://www.cloudidentity.com/blog/2014/08/28/use-adal-to-connect-your-universal-apps-to-azure-ad-or-adfs/
public login()
{
this.InitializeComponent();
redirectURI = Windows.Security.Authentication.Web.WebAuthenticationBroker.
GetCurrentApplicationCallbackUri();
authContext = new AuthenticationContext(authority);
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// When the app starts, fetch the user's To Do list from the service.
GetTodoList();
}
private async void GetTodoList()
{
AuthenticationResult result = await authContext.AcquireTokenAsync("https://graph.windows.net", "e11a0451-ac9d-4c89-afd8-d2fa3322ef68", new Uri("http://li"));
if (result.Status != AuthenticationStatus.Success)
{
if (result.Error == "authentication_canceled")
{
// The user cancelled the sign-in, no need to display a message.
}
else
{
MessageDialog dialog = new MessageDialog(string.Format("If the error continues, please contact your administrator.\n\nError: {0}\n\nError Description:\n\n{1} {2}", result.Error, result.ErrorDescription, s1), "Sorry, an error occurred while signing you in.");
await dialog.ShowAsync();
}
return;
}
I replaced clientID, authority and resource url according to my project. When I run Application from Windows phone , it works perfectly. When I run the same code in Windows 10 and same logic ported in windows 8.1 , Application prompts for user id and password,after entering these credentials I'm getting following error
"We can't connect to the service you need right now. Check your network connection or try this again later"
I see in the output windows of Visual Studio 2015 while running application as below.
"The type 'Page' is defined in an assembly that is not referenced. You must add a
reference to assembly 'Windows.Foundation.UniversalApiContract,
Version=1.0.0.0, Culture=neutral, Pub
The type 'IUICommand' is defined in an assembly that is not referenced. You must add a reference to assembly 'Windows.Foundation.UniversalApiContract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime'licKeyToken=null,
ContentType=WindowsRuntime'. "
I also tried to test same windows store on Windows 8.1, even their also it fails to authenticate User.
I have added all the capabilities like internet and intert client server
Add the following to config.xml:
<preference name="adal-use-corporate-network" value="true" />
The value is false by default.
More info here:
https://github.com/AzureAD/azure-activedirectory-library-for-cordova
this issue got resolved by adding useCorpnetnetwork = true for authenticationcontext along with changes in manifest like internet,internetclientsever,shared certificate . I missed shared certification in package
I'm running a mixed MVC Application inside a sub folder of a web forms application.
Everything worked great in VS 2010 debug (Cassini) but when I deployed to IIS7.5
I got the following error:
'HttpContext.SetSessionStateBehavior' can only be invoked before
'HttpApplication.AcquireRequestState' event is raised.
It errors on the last line (httpHandler.ProcessRequest(HttpContext.Current);) in the default.aspx file of the MVC application sub folder.
public void Page_Load(object sender, System.EventArgs e)
{
string pathToRewriteTo = Request.Path.ToLowerInvariant().Replace("default.aspx", "Home/Index");
HttpContext.Current.RewritePath(pathToRewriteTo, false);
IHttpHandler httpHandler = new MvcHttpHandler();
httpHandler.ProcessRequest(HttpContext.Current);
}
However if I manually navigate to Home/Index from the MVC root folder I can see my application fine from there.
I've looked up the error being thrown and I only find answers dealing with server transfers and not MVC routes.
I have also already checked my IIS7.5 configuration for the route handling module, Application pool running in integrated mode, etc.
Any help would be appreciated.
We faced a similar issue. There are changes to MVCHttpHandler in MVC2 and above.
You need to change it to use httpContext.Server.TransferRequest.
Try the below snippet:
var httpContext = HttpContext.Current;
httpContext.Server.TransferRequest(Url, true); // change to false to pass query string parameters if you have already processed them
I will appreciate any help on steps for an implementation to switch an MVC3/Razor Web Application to offline mode for maintenance. At the offline mode only a static page could be seen by the public but an administrator who is logged in should be able to view, browse and update the site fully. Ideally I want the web administrator just to tick on a value at the administrative back-end which will be registered in the database.
You could simply check some condition within BeginRequest in Global.asax.
protected void Application_BeginRequest()
{
if (myDb.SiteIsOffline && !CurrentUserIsAdministrator())
Response.Redirect("~/offline.html");
}
I was getting fed up with typing this.NavigationService.Navigate(new Uri(page.xaml, UriKind.Relative));, every time I need to navigate to a different page in my app.
So I've created a custom BasePage with a virtual to help with Navigating around my app.
The problem I have is in VS2010, if I have the source and design view open, the design just shows the windows phone background and I get some blue wiggly lines right from the top to the bottom of my xaml and messages along the lines of x isn't supported. This happens on any page that I have set up to Inherit from my custom BasePage.
However, if I run the application on my Windows Phone or in the Emmulator it will work.
Does anyone have any suggestions of what I could try to keep my Design view working whilst apply my custom base, or if I have missed something off?
A slightly cut down version of my BasePage is:
public class BasePage : PhoneApplicationPage
{
public virtual void NavigateTo(string pageName, params Tuple<string,string>[] queryString)
{
// Code to perform this.NavigationService.Navigate
}
}
EDIT 2011-08-16
Part of this base page overrides the PhoneApplicationPage's OnNavigatedTo method, in which I perform a security check to see if:
security has been enabled
User is logged in
If the security is enabled but the user is not logged in, they are immediately redirected to a Login Page.
I found this useful as I don't then have to add any code to existing or new pages to handle this, so long as they derive from the BasePage.
I wouldn't recommend using a BasePage for this. Instead, simply add your NavigateTo method in the App.xaml.cs file, as a static method.
public static void NavigateTo(string pageName, params Tuple<string,string>[] queryString)
{
// Code to perform this.NavigationService.Navigate
}
Also, remember to wrap the call to .Navigate in Dispatcher.BeginInvoke so all transition effects are properly executed.
And as a bonus tip: Don't use the designer in Visual Studio. Instead, set the 'default editor' for XAML files to be the "Source Code" editor, so the designer is never opened. This makes Visual Studio much more stable.
If you want a designer, you should get Microsoft Expression (Blend)