I'm using IdentityServer4 and trying to connect an MVC app up for authentication. I currently have things working by using the implicit flow, but I have run into the problem that my access tokens are expiring and there is no refresh token support for implicit. I also read today that implicit was designed for js apps before browsers got good, and that it is not as secure as authorization code flow.
SO. I would like to get my app working with the authorization code flow. I can't find any one simple solution for this using owin. I assume there is a nice and widely automated way to have owin take care of swapping the code for an access token and all that. After extensive research online I found this snippet of code that seems to be talking about what I'm doing:
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
...
TokenValidationParameters = new TokenValidationParameters
{
NameClaimType = "name",
RoleClaimType = "https://schemas.quickstarts.com/roles"
}
...
});
Does anyone have any examples or other info about getting owin to do all this?
Relevant info:
IdentityServer4
Client is .Net Framework 4.6
Related
We are currently writing a Xamarin Forms Azure Mobile application, using client flow, AAD authentication, refresh tokens etc.
Most of this is working as expected. However, logging out of the application does not work properly. It completes the logout process for both Android and iOS - but upon redirection to the login screen, hitting sign in will never prompt the user with the Microsoft login as expected, it will sign them straight back into the app.
To add a little bit of background, this app has been implemented as per Adrian Hall's book,
current link: https://adrianhall.github.io/develop-mobile-apps-with-csharp-and-azure/
with the above described options and configurations.
I have also read through the 30 days of Zumo (also by Adrian Hall) blog on this, and every single post I can find on here relating to this.
My current logout code is as follows:
public async Task LogoutAsync()
{
var loginProvider = DependencyService.Get<ILoginProvider>();
client.CurrentUser = loginProvider.RetrieveTokenFromSecureStore();
var authUri = new Uri($"{client.MobileAppUri}/.auth/logout");
using (var httpClient = new HttpClient())
{
if (IsTokenExpired(client.CurrentUser.MobileServiceAuthenticationToken))
{
var refreshed = await client.RefreshUserAsync();
}
httpClient.DefaultRequestHeaders.Add("X-ZUMO-AUTH", client.CurrentUser.MobileServiceAuthenticationToken);
await httpClient.GetAsync(authUri);
}
// Remove the token from the cache
loginProvider.RemoveTokenFromSecureStore();
//Remove the cookies from the device - so that the webview does not hold on to the originals
DependencyService.Get<ICookieService>().ClearCookies();
// Remove the token from the MobileServiceClient
await client.LogoutAsync();
}
As far as I can tell, this includes everything I have found so far - i.e. calling the /.auth/logout endpoint, removing the token locally, clearing the cookies from the device (as we log in inside a webview) and lastly calling the LogoutAsync() method from the MobileServiceClient.
Am I missing anything? Or is there a way we can force log out from this environment? As I know you can't "invalidate" an OAuth token, you have to wait until it expires - but to my mind, the /.auth/logout endpoint is supposed to handle this within the Azure environment? Though I'm just not sure to what extent.
Any help is appreciated.
We are currently writing a Xamarin Forms Azure Mobile application, using client flow, AAD authentication, refresh tokens etc. Most of this is working as expected. However, logging out of the application does not work properly.
I assumed that if you use the server flow for logging with AAD, the logout processing may works as expected. As you described that you used client flow, since you have clear the client cache for token, I assumed that the issue may caused by the LoginAsync related (ADAL part) logic code, you need to check your code, or you could provide the logging related code for us to narrow this issue.
I built a REST API using ASP.NET Web API 2, so I could deliver data from a backend database to my applications running on any platform (mobile, web, desktop etc) However up until now, I simply call the website with the controller I need data from and that's it, it sends back the JSON string in the response.
But, the data is kind of special, and there is nothing to prevent another developer from simply calling the controllers and getting back the exact same data and building their own application around it.
My question is - is there anyway to restrict access to the API so that only my applications can get valid response from the server. (i.e. prevent other developers from using my REST API)
I already read these documentation Security, Authentication, and Authorization in ASP.NET Web API I'm just not sure which of these scenarios apply to me, or if any will do what I am asking.
EDIT - Another piece of info, my web service is running on Azure in case it is relevant.
Did you happen to check token based authentication?Please go through https://stackoverflow.com/a/38670221/4868839 and https://www.youtube.com/watch?v=rMA69bVv0U8 must be a good to start with.
there are different way to validate your web api.
Authentication Filters in ASP.NET Web API 2
using you can customise your authentication filter
you can refer sample Reference link
Token Based Authentication using ASP.NET Web API 2, Owin, and Identity
//App_Start/Startup class
public void ConfigureAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/v1/accesstoken"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(AppConfiguration.AccessTokenExpireDuration),
Provider = new SampleOAuthProvider() // class that override your method
};
// Token Generation
app.UseOAuthBearerTokens(OAuthServerOptions);
}
You can find reference from inherits Default implementation of IOAuthAuthorizationServerProvider used by Authorization
i hope it sholud helps you thanks.
I have a c# console application that references the ADAL.net library (Microsoft.IdentityModel.Clients.ActiveDirectory version 2.19.208020213)
The purpose of the console app is to consume a HTTP endpoint which is protected with ADFS.
The implementation of the ADFS auth is as follows....
var uc = new UserCredential("user", "password");
var ctx = new AuthenticationContext("https://sts.example.com/adfs", false);
var token = ctx.AcquireToken(ClientResourceUri, ClientId, uc);
The call to AcquireToken throws an exception...
This method overload is not supported by
'https://sts.example.com/adfs/'
Calling AcquireToken without the UserCredential object, and instead providing a redirectUri works, but throws up a dialog prompting for username and password, which is unsuitable as the console app will be executed in a non user environment...
var redirect = new Uri("https://example.com/arbitaryRedirect");
var token = ctx.AcquireToken(ClientResourceUri, ClientId, redirect);
//dialog is shown
If i switch to the latest alpha release of the adal.net library (3.6.212041202-alpha)
the error is more revealing...
MSIS9611: The authorization server does not support the requested
'grant_type'. The authorization server only supports
'authorization_code' or 'refresh_token' as the grant type.
However, mining google yields very little.
Is it actually possible to authenticate silently against ADFS?
Would i be correct in assuming (based upon answers in other posts) that the correct approach is to use WsTrustChannelFactory instead?
If not, what is the best approach?
It is possible using ADAL 3.x and ADFS in Windows Server 2016, with pretty much the same code you posted. Combinations of older versions of either ADAL or ADFS won't work.
Alternatively, you can use WS-Trust - which is significantly harder to handle, but can get the job done.
I have two different web projects on Microsoft Azure. One project is a .NET MVC web application and the other project is a .NET Web API.
Both projects are configured to use Azure AD. The MVC web application is able to get a token and use it to make requests against the Web API. Here's sample code from the MVC web app.
string userObjectID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
AuthenticationContext authContext = new AuthenticationContext(Startup.Authority, new NaiveSessionCache(userObjectID));
ClientCredential credential = new ClientCredential(clientId, appKey);
result = authContext.AcquireTokenSilent(todoListResourceId, credential, new UserIdentifier(userObjectID, UserIdentifierType.UniqueId));
// Make a call against the Web Api
HttpClient client = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, webApiBaseAddress + "/api/list");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
HttpResponseMessage response = await client.SendAsync(request);
So this code works just fine. However, what I need to do now is call the Web API directly from an AngularJS application. When I try to do that, I get a 401 unauthorized error.
The way I am doing this is by adding a header to the HTTP GET request sent by AngularJS. I'm setting "Bearer" to the result.AccessToken value that I am passing to the page from my MVC application (code above).
Obviously this doesn't work. I suppose now my question is what are my options? Is there an official or better way to do this? Let's say I wanted to make calls to the Web API from standard JavaScript (lets forget the complexities of AngularJS). Is there a way to authenticate with Azure AD?
the canonical way of obtaining a token for an in-browser JS application would be to use the OAuth2 implicit flow. Azure AD does not currently expose that flow, but stay tuned: we are working on enabling the scenario. No dates to share yet.
HTH!
V.
The work I mentioned in the older answer finally hit the preview stage. Please take a look at http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ - that should solve precisely the scenario you described. If you have feedback on the library please do let us know!
Thanks
V.
I'm trying to set up OWIN OpenIdConnect to authorize with google provider.
I have used:
http://blogs.msdn.com/b/webdev/archive/2014/03/28/owin-security-components-in-asp-net-openid-connect.aspx
as a tutorial for that, but it's designed for Azure AD provider, so i changed necessary information to google:
Startup.Auth:
public void ConfigureAuth(IAppBuilder app)
{
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(
new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = "xxx.apps.googleusercontent.com",
Authority = "https://accounts.google.com",
RedirectUri = "https://localhost:44300/"
});
}
This causes redirect loop error in my browser.
To be sure, I have changed provider to Azure and it works perfectly.
Do you have idea how to fix that? In perfect I would like to integrate it with default membership provider, but for now I'm trying to get it work somehow.
EDIT:
I have found out that problem is in response_mode. Azure returns with POST, and google is returning GET.
Do you have any idea how to:
Make google returns with POST
Make OWIN OpenIdConnect read GET value property? Its separated from a url by '#', not '?'.
OWIN OpenIdConnectHandler only supports POST.
https://accounts.google.com/.well-known/openid-configuration
Doesn't specify response modes, so I am not sure if google+ signin does.
I followed an alternative approch without OWIN, as I tried to avoid using a lot of different libraries.
I basically bult a lightweight implementation especially for authentication against google (see description / documentation):
http://www.dominikamon.com/articles/3091/oidc-lightweight-library-for-aspnet.html
I've uploaded the code to Github:
https://github.com/DominikAmon/Amon.cc.OIDC