IdentityServer3 - redirect to ADFS if client is on intranet - asp.net-mvc

We have a portal (mvc rdp) that is used by both internal users (employees) and external users (customers). We would like IdentityServer3 to automatically detect if the authentication request is done from within the corporate network, and redirect to ADFS. The local login should be shown if the user-agent is calling from the internet.
In short, we don't want to have buttons for the external idp as we want the IdSrv to automatically redirect to ADFS if client is on the internal network to provide true single sign on for our domain bound users.
If the portal was only used by internal users, then we would just configure the client to only use a particular identity provider but this portal is also used by external customers and those users are not stored in our AD ;)
I've looked at overriding PreAuthenticateAsync and using Dns.Dns.GetHostName() but that is related to the machine that IdentityServer is running on and not the client machine.
In an mvc controller, we would just use Request.UserHostName but this is not available in IdentityServer3 UserService.

I think you can get the client's IP address from the OwinContext; something like this:
public class UserService : UserServiceBase
{
OwinContext ctx;
public UserService(OwinEnvironmentService owinEnv)
{
ctx = new OwinContext(owinEnv.Environment);
}
public override Task PreAuthenticateAsync(PreAuthenticationContext context)
{
// The IP Address of the remote client
var ipAddress = ctx.Environment["server.RemoteIpAddress"].ToString();
if (BelongsToOurNetwork(ipAddress))
context.SignInMessage.IdP = "OurADFS";
else
context.SignInMessage.IdP = "idsrv"; // local login
return Task.FromResult(0);
}
}

Related

oauth 2.0 - Resource owner password flow, can use windows login user credentials

I am using Identity Server 3 and using InMemoryUsers to keep my user/password info,
factory.UseInMemoryUsers(Users.Get());
For one of my client I'am using ResourceOwner password flow,
Flow = Flows.ResourceOwner,
Now, I am able to get access token by below setting, sending user/pass which we store In-Memory,
Now question is,
can I use windows local users credential in place of in-memory users?
There's a service called IUserService which is responsible for getting user and its profile.
When you are using InMemory Users in fact you are using InMemoryUserService.
If you want to use windows local users, you need to implement your own IUserService and get users from windows and then register your service.
public CustomUserService : UserServiceBase
{
public override Task AuthenticateLocalAsync(LocalAuthenticationContext context)
{
// You need to implement `GetUserFromWindows` to get users from windows local
var user = GetUserFromWindows(context.UserName, context.Password);
if (user != null)
{
context.AuthenticateResult = new AuthenticateResult(user.Subject, userDisplayName);
}
return Task.FromResult(0);
}
}
factory.UserService = new Registration<IUserService, CustomUserService>();

ASP.Net MVC application access to other servers

We have an ASP.Net MVC application (website), just a straight web app. The URL it needs to connect to is an ASP.Net WebAPI2 web service on port 14015. The MVC application is calling the Web service anonymously using a WebClient class; the web service is secured by limiting which IPs can connect to it. There is no authorization mode to access except by IP.
using (WebClient client = new WebClient())
{
//****************************
// We make the web service call like this:
//****************************
string url = #"http://secure.example.com:14015/lms/SSOKey/1158341";
string key = client.DownloadString(url);
//****************************
// Then we append the returned key to build the full URL. This URL is used
// in the View to build a link button.
//****************************
string login_url = #"http://192.168.1.1/tc/login.do?uid=" + key;
login_url = login_url.Replace("\"", string.Empty);
//****************************
// Pass the URL to the view to build the link button
//****************************
ViewBag.LoginURL = login_url;
}
I can access the URL from a browser on the server where the MVC application is published, however, the call is unsuccessful. Any ideas how I may find out why this won't connect??
If you are calling the code inside of a controller and the users have to logon to your web app, than this code should give you what you need:
string currentUser = User.Identity.Name;
If your users use your web app anonymously currentUser will be blank.
Adding this code solved the problem.
System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
Since we limit access by IP Addresses, very low security risk.

RemoteTokenService for multiple client application

How can I use RemoteTokenService for more than one client application (with different client_id and secret )?
UPDATE
public ResourceServerTokenServices tokenService() {
RemoteTokenServices tokenServices = new RemoteTokenServices();
tokenServices.setClientId("sample_test_client_app_auth_code");
tokenServices.setClientSecret("secret");
tokenServices.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
return tokenServices;
}
That's how we configure instance of RemoteTokenService. and inject it to the OAuth2AuthenticationManager for separate Resource server and auth server. Is it correct?
so when some other client has to access this resource how can I configure RemoteTokenService for both of this client.can you provide some light on this. and tell me if I am wrong on something.
The client id in the RemoteTokenServices is not the client that is consuming the resource, it's the client associated with the resource itself (solely for the purpose of authentication of the /check_token endpoint). So once you have it working you can hit that resource from as many clients as you like.

How do I authorize access to ServiceStack resources using OAuth2 access tokens via DotNetOpenAuth?

I've created an OAuth2 authorization server using DotNetOpenAuth, which is working fine - I'm using the resource owner password flow, and successfully exchanging user credentials for an access token.
I now want to use that access token to retrieve data from secure endpoints in a ServiceStack API, and I can't work out how to do so. I've examined the Facebook, Google, etc. providers included with ServiceStack but it's not clear whether I should be following the same pattern or not.
What I'm trying to achieve (I think!) is
OAuth client (my app) asks resource owner ('Catherine Smith') for credentials
Client submits request to authorization server, receives an access token
Client requests a secure resource from the resource server (GET /users/csmith/photos)
The access token is included in an HTTP header, e.g. Authorization: Bearer 1234abcd...
The resource server decrypts the access token to verify the identity of the resource owner
The resource server checks that the resource owner has access to the requested resource
The resource server returns the resource to the client
Steps 1 and 2 are working, but I can't work out how to integrate the DotNetOpenAuth resource server code with the ServiceStack authorization framework.
Is there an example somewhere of how I would achieve this? I've found a similar StackOverflow post at How to build secured api using ServiceStack as resource server with OAuth2.0? but it isn't a complete solution and doesn't seem to use the ServiceStack authorization provider model.
EDIT: A little more detail. There's two different web apps in play here. One is the authentication/authorisation server - this doesn't host any customer data (i.e. no data API), but exposes the /oauth/token method that will accept a username/password and return an OAuth2 access token and refresh token, and also provides token-refresh capability. This is built on ASP.NET MVC because it's almost identical to the AuthorizationServer sample included with DotNetOpenAuth. This might be replaced later, but for now it's ASP.NET MVC.
For the actual data API, I'm using ServiceStack because I find it much better than WebAPI or MVC for exposing ReSTful data services.
So in the following example:
the Client is a desktop application running on a user's local machine, the Auth server is ASP.NET MVC + DotNetOpenAuth, and the Resource server is ServiceStack
The particular snippet of DotNetOpenAuth code that's required is:
// scopes is the specific OAuth2 scope associated with the current API call.
var scopes = new string[] { "some_scope", "some_other_scope" }
var analyzer = new StandardAccessTokenAnalyzer(authServerPublicKey, resourceServerPrivateKey);
var resourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(analyzer);
var wrappedRequest = System.Web.HttpRequestWrapper(HttpContext.Current.Request);
var principal = resourceServer.GetPrincipal(wrappedRequest, scopes);
if (principal != null) {
// We've verified that the OAuth2 access token grants this principal
// access to the requested scope.
}
So, assuming I'm on the right track, what I need to do is to run that code somewhere in the ServiceStack request pipeline, to verify that the Authorization header in the API request represents a valid principal who has granted access to the requested scope.
I'm starting to think the most logical place to implement this is in a custom attribute that I use to decorate my ServiceStack service implementations:
using ServiceStack.ServiceInterface;
using SpotAuth.Common.ServiceModel;
namespace SpotAuth.ResourceServer.Services {
[RequireScope("hello")]
public class HelloService : Service {
public object Any(Hello request) {
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
}
This approach would also allow specifying the scope(s) required for each service method. However, that seems to run rather contrary to the 'pluggable' principle behind OAuth2, and to the extensibility hooks built in to ServiceStack's AuthProvider model.
In other words - I'm worried I'm banging in a nail with a shoe because I can't find a hammer...
OK, after a lot of stepping through the various libraries with a debugger, I think you do it like this: https://github.com/dylanbeattie/OAuthStack
There's two key integration points. First, a custom filter attribute that's used on the server to decorate the resource endpoints that should be secured with OAuth2 authorization:
/// <summary>Restrict this service to clients with a valid OAuth2 access
/// token granting access to the specified scopes.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true)]
public class RequireOAuth2ScopeAttribute : RequestFilterAttribute {
private readonly string[] oauth2Scopes;
public RequireOAuth2ScopeAttribute(params string[] oauth2Scopes) {
this.oauth2Scopes = oauth2Scopes;
}
public override void Execute(IHttpRequest request, IHttpResponse response, object requestDto) {
try {
var authServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("authServer");
var dataServerKeys = AppHostBase.Instance.Container.ResolveNamed<ICryptoKeyPair>("dataServer");
var tokenAnalyzer = new StandardAccessTokenAnalyzer(authServerKeys.PublicSigningKey, dataServerKeys.PrivateEncryptionKey);
var oauth2ResourceServer = new DotNetOpenAuth.OAuth2.ResourceServer(tokenAnalyzer);
var wrappedRequest = new HttpRequestWrapper((HttpRequest)request.OriginalRequest);
HttpContext.Current.User = oauth2ResourceServer.GetPrincipal(wrappedRequest, oauth2Scopes);
} catch (ProtocolFaultResponseException x) {
// see the GitHub project for detailed error-handling code
throw;
}
}
}
Second, this is how you hook into the ServiceStack HTTP client pipeline and use DotNetOpenAuth to add the OAuth2 Authorization: Bearer {key} token to the outgoing request:
// Create the ServiceStack API client and the request DTO
var apiClient = new JsonServiceClient("http://api.mysite.com/");
var apiRequestDto = new Shortlists { Name = "dylan" };
// Wire up the ServiceStack client filter so that DotNetOpenAuth can
// add the authorization header before the request is sent
// to the API server
apiClient.LocalHttpWebRequestFilter = request => {
// This is the magic line that makes all the client-side magic work :)
ClientBase.AuthorizeRequest(request, accessTokenTextBox.Text);
}
// Send the API request and dump the response to our output TextBox
var helloResponseDto = apiClient.Get(apiRequestDto);
Console.WriteLine(helloResponseDto.Result);
Authorized requests will succeed; requests with a missing token, expired token or insufficient scope will raise a WebServiceException
This is still very much proof-of-concept stuff, but seems to work pretty well. I'd welcome feedback from anyone who knows ServiceStack or DotNetOpenAuth better than I do.
Update
On further reflection, your initial thought, to create a RequiredScope attribute would be a cleaner way to go. Adding it to the ServiceStack pipeline is as easy as adding the IHasRequestFilter interface, implementing a custom request filter, as documented here: https://github.com/ServiceStack/ServiceStack/wiki/Filter-attributes
public class RequireScopeAttribute : Attribute, IHasRequestFilter {
public void RequireScope(IHttpRequest req, IHttpResponse res, object requestDto)
{
//This code is executed before the service
//Close the request if user lacks required scope
}
...
}
Then decorate your DTO's or Services as you've outlined:
using ServiceStack.ServiceInterface;
using SpotAuth.Common.ServiceModel;
namespace SpotAuth.ResourceServer.Services {
[RequireScope("hello")]
public class HelloService : Service {
public object Any(Hello request) {
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
}
Your RequireScope custom filter would be almost identical to ServiceStack's RequiredRoleAttribute implementation., so use it as a starting point to code from.
Alternately, you could map scope to permission. Then decorate your DTO or service accordingly (see SS wiki for details) for example:
[Authenticate]
[RequiredPermission("Hello")]
public class HelloService : Service {
public object Any(Hello request) {
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
Normally ServiceStack calls the method bool HasPermission(string permission) in IAuthSession. This method checks if the list List Permissions in IAuthSession contains the required permission, so, in a custom IAuthSession you could override HasPermission and put your OAuth2 scopes checking there.

Need to pass additional value to UserNameSecurityToken in STS from client application

I have incorporate security into my wcf service using wif. Below my high level design.
Wif sts application - Here i have used custom username security token handler for validate the usename & passsword
Wcf service - list of services
Web application -> where i consumed the wcf service.
STS custom username security token handler as follows:
public class CustomUserNameSecurityTokenHandler : UserNameSecurityTokenHandler
{
public override Microsoft.IdentityModel.Claims.ClaimsIdentityCollection ValidateToken(System.IdentityModel.Tokens.SecurityToken token)
{
UserNameSecurityToken userNameToken = token as UserNameSecurityToken;
CredentialStore.AuthenticateUser(userNameToken.username, userNameToken.Password);
// ...
}
}
Code to consume the wcf service from web application
ClientCredentials oldCredentials = client.Endpoint.Behaviors.Remove<ClientCredentials>();
CachedClientCredentials newCredentials = new CachedClientCredentials(_tokenCache, oldCredentials);
client.Endpoint.Behaviors.Add(newCredentials);
client.ClientCredentials.UserName.UserName = "Admin"
client.ClientCredentials.UserName.Password = "password";
client.Authenticate();
While consume the wcf service i am able to send the username and password to STS validateToken method for authenticate and my scenario is like i want to send one more value (current web site address) to validatetoken method from consume part. i have workaround to send the additional value part of username but that is not the good idea to do that.
So could you please help me to resolve my issue?
An STS service that I have implemented requires a ClientID in addition to the username and password. I've solved this problem by adding custom elements into the security token request when initialising the service client. The STS service then reads out these values whilst authorizing the token and also passes back the ClientID in the claims.
// init client..
_serviceClient.ClientCredentials.UserName.UserName = Username;
_serviceClient.ClientCredentials.UserName.Password = Password;
var doc = new XmlDocument();
XmlElement customElement = doc.CreateElement("ExtraAuthData", Name, "http://localhost/STS/identity");
customElement.InnerText = Value;
(_serviceClient.Endpoint.Binding as WS2007FederationHttpBinding).Security.Message.TokenRequestParameters.Add(customElement);
Not sure if this is a recommended approach or not, I couldn't find any other way of doing this.

Resources