IdentityServer4 Quickstart for IdentityServer as Identity/api endpoints and MVC client - c#

I'm running asp.net core 3.1 and IdentityServer4 following the quick start and guides.
I'm a bit lost when implementing IS end points and api endpoints in the same project. I want the server to host IS authentication/login urls, apis and mvc client. I want to issue bearer tokens which will be used by the IS host/mvc client and client credential clients.
I have gone through the quick starts and gotten the MVC client and the console client to authenticate with my identity server host, but when I try to use my identity server host to authenticate and then go to one of the view controllers, I just get a circular workflow back through authentication.
I believe it's because my account controller login post method isn't issuing the bearer token. I'm thinking there's a call I need make to identity server during login to get it to set the bearer cookie. (It's also possible I'm just missing something on my view controller to tell it it's part of the group to allow access?)
I have this in which allows the client credentials from the console app to work:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = Constants.HostUrl;
options.RequireHttpsMetadata = false;
options.Audience = "api";
});
But if I remove it, then the login workflow through the host identity server works and I can access my view and api controllers.
Is there a quick start that I'm missing that shows the identity server also being the mvc client?
Thanks

when I try to use my identity server host to authenticate to itself, I just get a circular workflow back through authentication.
Well, what does it mean for itself?
Do you try to ask for token for the service that is used to host the REST API ?
It looks like you have some kind of client (like background service whatever) and is trying to get token for that client.
Is it so?
Seems that you can use the client credentials flow However this requires clientid and secret to be stored somewhere. Here is some documentation.
You can use Identity server's Windows Authentication feature also

Related

Server to Server authentication in dotnet

I have a web api server on lets say, api.app.com which serves data for my app and i have a separate web server on www.app.com which serves users the pages for the app. I am using a JWT created on the webapi to Authorize the user. The token is created when the client logs in from the login page served on www.app.com with a username and a password. I want www.app.com (web server) to send a request to api.app.com (web api) to authenticate the user and then store the token gotten from the web api inside a cookie on the client.
Then i want only api authenticated clients to have access to pages on the web server, while the web server gets data from the web api on the behalf of the client per request.
I have checked everywhere online, without a clear solution to this
Web apis are usually consumers of JWT tokens. Once received they validate the token, and check claims and proceed based on the result. Your environment is a little confusing to me.
It seems your api app is used as an identity server as well as data provider. It is best to separate these concerns.

Identity disappears from bearer token after an hour

I am working on a multi-tenant solution with Azure AD with web apps and a web api. The web app uses OpenIdConnect to retrieve a bearer token (which is cached in Azure Redis Cache), which is used in Angular to get JSON from the web api. User impersonation is used between the web app and web api (set up in Azure AD applications).
Problem:
This works fine for about an hour, then the Identity suddenly disappears on the web api side. If I refresh the web app, I see that the page is redirected to the Microsoft login page, but no action is required since the user is just redirected back to the web app and everything works again. As far as I can see, the web app uses the same bearer token when it fails and after the refresh (same expire time) when it works again. AuthenticationContext.AcquireTokenSilent works in both scenarios.
I have tried to increase a lot of different timeouts, but nothing has helped. I have also disabled all but bearer token authentication on the web api. I do not understand why the identity disapears and why it helps to refresh the client. Any ideas? :)
Additional info
This is how the RequestContext.Principal.Identity looks for about an hour after login or a refresh (on the web api):
And this is after about an hour, which causes authentication to fail:
Some of the code changes I have tried out:
In web api HttpConfiguration:
config.SuppressDefaultHostAuthentication();
config.Filters.Add(
new HostAuthenticationFilter(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions().AuthenticationType));
This changed the unauthenticated principal from WindowsPrincipal to ClaimsPrincipal, but it still fails after an hour.
WindowsAzureActiveDirectoryBearerAuthenticationOptions BackChannelTimeout set to 5 days. Still fails
In the web app web.config:
sessionState timeout="525600" for RedisSessionStateProvider. Still fails
In the web app owin auth process, increased timespan and added sliding expiration. Still fails:
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
CookieSecure = CookieSecureOption.Always,
ExpireTimeSpan = TimeSpan.FromDays(5),
SlidingExpiration = true,
CookieHttpOnly = true
});
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = ClientId,
Authority = Constants.CommonAuthority,
UseTokenLifetime = false
Update:
To flesh out some details: We have a hybrid MVC Angular web application. Many MVC menu items which each lead to an Angular "single page application" for that menu item. MVC is used for routing, authentication and authorization. In addition, additional claims is retrieved and appended to the current principal server side. The menu items are MVC controllers that are protected with the Authorized and ClaimsPrincipalPermission attributes. Since the web page will run in Azure, we changed the default sessionProvider to Microsoft.Web.Redis.RedisSessionStateProvider. Only the MVC server side talks to this redis session cache. The bearer token (not refresh token) is shared with Angular through an Authorized protected MVC controller, which is then stored in the browser session storage (similar to adal.js use of localstorage?) Angular gets JSON content from a CORS enabled API that lives in a separate domain from the MVC app. The API and MVC app also belong to two different Azure AD applications.
you seem to be crossing flows here. If you are making calls from JavaScript, you should obtain the token in the client - something like http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/.
Redirect based authentication flows in which the outcome is a cookie are not well suited for scenarios in which you call API via JavaScript. Furthermore, if I understood correctly you are obtaining a token as a private client and then sharing it out of band (redis cache) with a public client running inside a user agent. That's a no-no from the security perspective.
That said: if you are really really set in keeping up with your current route, I suggest taking a look at http://www.cloudidentity.com/blog/2014/04/28/use-owin-azure-ad-to-secure-both-mvc-ux-and-web-api-in-the-same-project/ for achieving full separation between your web UX and web API routes.

How to create an MVC 5 app with login on a different domain (OWIN OAuth2)

I would like to create a Client application in MVC 5 with a log in page on a different domain.
What I want to achieve is a centralized authentication domain for all of my applications (MVC 5 web applications, Web Api's and Desktop applications as well).
I tried to use the example below:
http://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
I can use the token to get resources from Web Api with both client type (website and desktop application), but I would like to use the claims and properties in the website as well and reach the web api with the token provided by the authorization server.
The only problem I have is that I can't set up and MVC 5 project to redirect to authorization server domain when the user is not authorized and after a successfully authorization redirect back to original domain and use the claims and properties which are encrypted into the token provided by the authorization server.
Can you provide me a sample or some articles with which I can start implementing the upper things by usin OWIN OAuth2? Thanks in advance!

Azure Mobile Services and Web API authentication

I'm developing a Web API and was looking to use Azure Mobile Services to authenticate users before allowing calls made to the Web API.
So the user would navigate to a website, choose to log in using their Google/Facebook/etc account and the user would be authenticated using the Mobile Services JavaScript client. From what I understand Mobile Services will then return a authentication token in the form of a JSON Web Token.
What I would like to do is when website calls the Web API it would pass along the authentication token, the Web API would check that it's a valid token issued by Mobile Services and if all is good, then allow the call to be executed.
So my question is...is this possible? If so, could the JSON Web Token Handler for .NET be used to perform the validation on the Web API side?
Yes, that is possible.
If you perform a login using the MobileServiceClient, you will get a token that you can pass along with every request to a Web Api endpoint.
var client = new WindowsAzure.MobileServiceClient('https://yourservice.azure-mobile.net', 'your-client-key');
client.login('facebook').then(success);
function success(result) {
alert('login ok');
}
So when making a request, set the value of header 'X-ZUMO-AUTH' to the current users token you find in client.currentUser.mobileServiceAuthenticationToken after a successful login.
On the server side, add the attribute [AuthorizeLevel(AuthorizationLevel.User)] to Web Api methods that require the user to be authenticated. Thats all.
But make sure, that identity is configured properly on WAMS, and also at the provider side you want to integrate (client id's, client secrets, callback urls, etc.).

Client Application Services - Authentication from WPF client

I'm using the Client Application Services for Client (WPF) authentication with ASP.Net membership, which is working just fine. However, on the server I have additional MVC queries that I must authenticate when calling them from the client. When looking at the available Membership.ValidateUser call, I fail to see how this helps me in any way, as I need to validate every single call.
I assume sticking [Authorize] on each MVC call is the first step.
Can I get a security token, or extract a cookie for the CookieContainer, or am I simply misunderstanding something here?
I am assuming you ASP.Net MVC site, WCF services are hosted in same virtual application and ASP.Net compatibility mode is on.
If you are using WPF to authenticate your user by calling a web service do the following
On Server side
Implement code to do authentication
Once authentication is successful
create a form authentication cookie
and add it to response cookie
collection.
On the client side
The client class that you are using
to connect to authentication service
should contain a static CookieContainer class instance.
Once authentication is
successful add the cookie received to
this cookie container and pass it along every subsequent request.
Hence forth all request to ASP.Net MVC application or any service would contain the cookie and the user would get authorize automatically. Check this blog post for sample
Hope this helps.

Categories

Resources