WCF RIA Services Form Authentication ServiceContext.User.Identity.Name Empty - forms-authentication

We are using WCF Ria Services with silverlight 5 project.For authentication we are using Custom membership provider.WCF Ria Service in RIA Services class library.
Client side authentication running.We access current user name with WebContext.Current.User.Name.But server side ServiceContext.User empty.If we use [RequireAuthentication] attr. in DomainServices return always Access Denied.
How Can we push WebContext.Current.user to ServiceContext.user.I read several document and tutorial but every test fail.
Code examples :
CustomMembershipProvider.cs:
public class CustomMembershipProvider : MembershipProvider {
public override bool ValidateUser(string username, string password)
{
using (var context = new TimEntities())
{
var user = context.User.FirstOrDefault(u => u.Username == username &&
u.Password == password);
return user != null;
}
}
}
AuthenticationDomainService:
[EnableClientAccess]
public class AuthenticationDomainService : AuthenticationBase<AuthUser>
{}
public class AuthUser : UserBase
{}
App.Xaml.Cs:
var webContext = new WebContext();
var formsAuth = new FormsAuthentication();
var authContext = new AuthenticationDomainContext();
formsAuth.DomainContext = authContext;
webContext.Authentication = formsAuth;
ApplicationLifetimeObjects.Add(webContext);

I was having the same problem, but I have finally tracked down the answer. I had been messing about trying to expose SOAP endpoints, so I could access the same RIA services from a phone app. As part of that, I had added the following line in the App constructor:
WebRequest.RegisterPrefix("http://", WebRequestCreator.ClientHttp);
Get rid of that, and you should have the user name available again. SOAP endpoints still seem to be exposed to the phone app as well.

At first you have to configure Forms authentication for your hosting website regardless whether you use WCF RIA Service or not. Moreover, Forms authentication have to be installed and enabled on IIS.
Then you have to configure ASP.NET membership in order to use your CustomMembershipProvider class.

Related

How do I create a ClaimsPrincipal in my Blazor/.NetCore "Session"?

Background: I have an old MVC app that I'm experimenting with migrating to a shiny new Blazor app. Blazor seems to tick a lot of boxes for me here. Wunderbar. For clarity this is the solution template in VS2022 where there's a WASM, a .Net Core host, and a shared project. I will have plenty of api calls that need to be secured as well as UI that will be affected by various authorization policies (eg show/hide admin features).
I have a table of users with an ID and hashed password.
I can't get Blazor to use its native authentication/authorization processes with my existing store.
My latest attempt was to create an AccountController on the server app (inherits ControllerBase) and put in a Login method that gets the username and password from a json body for the moment. I have successfully ported the old authentication mechanism and I have my user that I have verified the password for. I now want to use Claims and a ClaimsPrincipal to store some of the things about the user, nothing too complex.
How do I put my ClaimsPrincipal into the app such that the WASM UI can see it AND future calls to api controllers (or ControllerBase controllers) will see it?
I have found hundreds of examples that use built-in scaffolding that lets it use EF to create tables and things but I need to use my existing stores and I can't find anything that joins the dots on how to connect the WASM and the server side.
I have read about and implemented and around the place, and tried some #authorize around the place but my WASM just doesn't know about the authenticated user.
In my login controller I have attempted a bunch of different approaches:
I implemented a custom AuthenticationStateProvider, got it into the controller via DI, called the AuthenticationStateChanged() and for the lifecycle of that one controller call I can see my HttpContext.User gets the new identity. But the WASM doesn't, and if I hit the same method again the User is null again
I tried to implement a SignInManager. This never worked well and my reading suggests that it's not compatible
I discovered ControllerBase.SignIn() which hasn't helped either
HttpContext.SignInAsync() with Cookie authentication (because that was the example I found)
I tried setting HttpContext.User directly (and tried combining that one call with the AuthenticationStateProvider implementation simultaneously)
I tried creating a fresh solution from template to pick through it, but it would appear to be reliant on hacking up my EF DataContext. I just want to find how I tell the whole contraption "Here's a ClaimsPrincipal" and have that work in both the WASM and api controllers.
I'm also not excited to have a dependency on the Duende stuff - I don't see what it brings to the table. I don't really need a whole identity provider, I already have my own code for authorizing against the database I just need to get my very boring ClaimsPrincipal into my app.
Am I going at this all wrong? Has my many years of "old school" experience stopped me from seeing a modern way of doing this? Am I trying to force cool new stuff to behave like clunky old stuff? Yes I'd love to switch to Google/Facebook/Twitter/MS authorization but that's not an option, I have passwords in a database.
You need to build a custom AuthenticationHandler.
Here's the relevant bits of one of mine (see credits at bottom for where I lifted some of the code). You'll need to pick out the pieces from the code to make your work. Ask if you have any specific problems.
The custom AuthenticationHandler looks up your user in your database and if authenticated, builds a standard ClaimsPrincipal object and adds it to the security header. You can then use the standard Authorization and AuthenticationStateProvider.
public class AppAuthenticationHandler : AuthenticationHandler<AppAuthOptions>
{
private const string AuthorizationHeaderName = "Authorization";
private const string BasicSchemeName = "BlazrAuth";
//this is my custom identity database
private IIdentityService _identityService;
public AppAuthenticationHandler(IOptionsMonitor<AppAuthOptions> options, IIdentityService identityService, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock)
: base(options, logger, encoder, clock)
{
_identityService = identityService;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
await Task.Yield();
// Check the Headers and make sure we have a valid set
if (!Request.Headers.ContainsKey(AuthorizationHeaderName))
return AuthenticateResult.Fail("No Authorization Header detected");
if (!AuthenticationHeaderValue.TryParse(Request.Headers[AuthorizationHeaderName], out AuthenticationHeaderValue? headerValue))
return AuthenticateResult.Fail("No Authorization Header detected");
if (!BasicSchemeName.Equals(headerValue.Scheme, StringComparison.OrdinalIgnoreCase))
return AuthenticateResult.Fail("No Authorization Header detected");
if (headerValue is null || headerValue.Parameter is null)
return AuthenticateResult.Fail("No Token detected");
// Get the User Guid from the security token
var headerValueBytes = Convert.FromBase64String(headerValue.Parameter);
var userpasswordstring = Encoding.UTF8.GetString(headerValueBytes);
// This will give you a string like this "me#you.com:password"
if (youcantdecodethestring ))
return AuthenticateResult.Fail("Invalid Token submitted");
// Get the user data from your database
var principal = await this.GetUserAsync(userId);
if (principal is null)
return AuthenticateResult.Fail("User does not Exist");
// Create and return an AuthenticationTicket
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
// method to get the user from the database and retuen a ClaimsPrincipal
public async Task<ClaimsPrincipal?> GetUserAsync(Guid Id)
{
// Get the user object from the database
var result = await _identityService.GetIdentityAsync(Id);
// Construct a ClaimsPrincipal object if the have a valid user
if (result.Success && result.Identity is not null)
return new ClaimsPrincipal(result.Identity);
// No user so return null
return null;
}
}
You can construct a ClaimsIdentity like this:
var identity = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Sid, record.Id.ToString()),
new Claim(ClaimTypes.Name, record.Name),
new Claim(ClaimTypes.Role, record.Role)
}, "MyIdentityProvider");
public class AppAuthOptions : AuthenticationSchemeOptions
{
public string Realm = "BlazrAuth";
}
The service registration:
public static class AuthServicesCollection
{
public static void AddAppAuthServerServices(this IServiceCollection services)
{
services.AddAuthentication("BlazrAuth").AddScheme<AppAuthOptions, AppAuthenticationHandler>("BlazrAuth", null);
services.AddScoped<IIdentityService, IdentityService>();
}
}
Credits: Some of this code was derived from: https://harrison-technology.net/

Port over existing MVC user authentication to Azure functions

I have an old web application which is using ASP.net with the build in cookie based authentication which has the standard ASP.net SQL tables for storing the users credentials.
This is currently running as an Azure web app, but I was toying with the idea of trying to go serverless as per this example creating a ReactJs SPA hosting on blob storage to try and keep costs down and also improve performance without breaking the bank.
https://learn.microsoft.com/en-us/azure/architecture/reference-architectures/serverless/web-app
I was wondering if it is possible to port over the existing ASP.net authentication to Azure functions, to instead return a JWT (JSON Web Token) which could be passed back in the headers to handle authenticated requests.
When I have tried this in the past I have failed misserably, so I was wondering if anyone knows if it is possible?
I've seen this article, which seems to talk about Azure functions doing authentication, but with Azure AD, which I don't think is right for what I need.
https://blogs.msdn.microsoft.com/stuartleeks/2018/02/19/azure-functions-and-app-service-authentication/
The answer is kind of. What I mean by this is that you can use your existing database and many of the same libraries, but you can't port over the code configuration. The default authentication for Functions is either 1) The default API tokens or 2) one of the EasyAuth providers baked into App Services which is in the guide you linked. Currently, any other solution you'll need to setup yourself.
Assuming you go with the JWT option, you'll need to turn off all of the built-in authentication for Functions. This includes setting your HttpRequest functions to AuthorizationLevel.Anonymous.
At a basic level You'll need to create two things. A function to issue tokens, and either a DI service or a custom input binding to check them.
Issuing tokens
The Functions 2.x+ runtime is on .NET Core so I'm gong to borrow some code from this blog post that describes using JWTs with Web API. It uses System.IdentityModel.Tokens.Jwt to generate a token, which we could then return from the Function.
public SecurityToken Authenticate(string username, string password)
{
//replace with your user validation
var user = _users.SingleOrDefault(x => x.Username == username && x.Password == password);
// return null if user not found
if (user == null)
return null;
// authentication successful so generate jwt token
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_appSettings.Secret);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.Name, user.Id.ToString())
}),
Expires = DateTime.UtcNow.AddDays(7),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
};
return tokenHandler.CreateToken(tokenDescriptor);
}
Validating Tokens
There are several guides out there for validating JWT within Azure Functions. I like this one from Ben Morris: https://www.ben-morris.com/custom-token-authentication-in-azure-functions-using-bindings/ (source code). It describes authenticating with either a custom input binding or with DI. Between the two, DI is the preferred option, unless there is a specific reason you need to use a binding. Here again, its the Microsoft.IdentityModel.JsonWebTokens and System.IdentityModel.Tokens.Jwt libraries that you'll need to do the bulk of the work.
public class ExampleHttpFunction
{
private readonly IAccessTokenProvider _tokenProvider;
public ExampleHttpFunction(IAccessTokenProvider tokenProvider)
{
_tokenProvider = tokenProvider;
}
[FunctionName("ExampleHttpFunction")]
public IActionResult Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "example")] HttpRequest req, ILogger log)
{
var result = _tokenProvider.ValidateToken(req);
if (result.Status == AccessTokenStatus.Valid)
{
log.LogInformation($"Request received for {result.Principal.Identity.Name}.");
return new OkResult();
}
else
{
return new UnauthorizedResult();
}
}
}

How to implement External Authentication with local claims in mvc 5

I am working on a mvc 5 application and have configured WS Federation to authenticate using an external IP. However based on the functionality of the application, the users's roles need to be managed by application itself. An administrator of the application will allow different level of access to the application from an admin area of the application. and since i am working with ASP.NET Identity for the first time i am lost on how to move forward from here.
Do I need to implement a custom ClaimsAuthenticationManager for this?
Do I also need to implement a UserManager to create local list of users to be able to manage their Claims?
Any direction/help is appreciated.
Thanks,
You can add external claims in your override of CreateUserIdentityAsync.
This will add just Roles from your Federated login:
public override async Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
{
var externalIdentity =
await AuthenticationManager.GetExternalIdentityAsync(DefaultAuthenticationTypes.ExternalCookie);
var localIdentity = await user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
foreach (var item in externalIdentity.Claims.Where(x => x.Type == ClaimTypes.Role))
localIdentity.AddClaim(new Claim(ClaimTypes.Role, item.Value));
return localIdentity;
}

Implementing active authentication using ADFS

I am working on the authentication with Active Directory using ADFS.
While searching, I got few articles to accomplish this requirement, but they are suggesting to redirect the Login page of application to Login page of ADFS and then come back.
Redirecting to ADFS Login page is not suggested as per user experience.
Can anyone help me to find out the solution to authenticate with active directory using ADFS behind the scene ? So, everything will be handled by application code, not by ADFS login page.
Please advise.
Please let me know if you have any concern or query or if you need more information.
The reason those articles suggest you redirect (using WS-Federation protocol) to the ADFS login page is because it allows you to set up federation to other identity providers (allow an external company' employees to use their own credentials to log in to your application).
What you want can be done using the WS-Trust protocol, but you'll give up (or have to implement yourself) the possibility to federate.
ADFS exposes endpoints like /adfs/services/trust/13/usernamemixed that you can talk to to get a security token. Something like below should get you going.
public class UserNameWSTrustBinding : WS2007HttpBinding
{
public UserNameWSTrustBinding()
{
Security.Mode = SecurityMode.TransportWithMessageCredential;
Security.Message.EstablishSecurityContext = false;
Security.Message.ClientCredentialType = MessageCredentialType.UserName;
}
}
private static SecurityToken GetSamlToken(string username, string password)
{
var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(), "https://yourdomain.com/adfs/services/trust/13/UsernameMixed")
{
TrustVersion = TrustVersion.WSTrust13
};
factory.Credentials.UserName.UserName = username;
factory.Credentials.UserName.Password = password;
var rst = new RequestSecurityToken
{
RequestType = RequestTypes.Issue,
AppliesTo = new EndpointReference("https://yourdomain.com/yourservice"),
KeyType = KeyTypes.Bearer
};
var channel = factory.CreateChannel();
return channel.Issue(rst);
}

asp.net - Unable to set Identity in owin after successful custom authentication

I am using wcf service for authentication and communication with database. After success authentication, in client web application, I am trying to set Identity for login user using following code.
private async Task SignIn(ApplicationUser user)
{
var identity = await UserManager.CreateIdentityAsync(
user, DefaultAuthenticationTypes.ApplicationCookie);
GetAuthenticationManager().SignIn(identity);
}
private IAuthenticationManager GetAuthenticationManager()
{
var ctx = Request.GetOwinContext();
return ctx.Authentication;
}
Even after execution of above code i.e. setting identity Request.IsAuthenticated still return false.
I have found above code is working fine in an online sample which is using Microsoft.AspNet.Identity.Core version 1.0.0 library.
Any idea what I am doing wrong?

Resources