Passing a parameter to Identity Server 4 Login Page - asp.net-mvc

I have a client application that is using IDSVR4 for authentication. I need to store the user's username(in a different process from the login through IDSVR) on the client in a session or whatevr other client-side data storage mech so the user doesn't have to enter the details everytime he logs in from that specific browser.
How can i pass the username from the client to identity server?

You can add the username to the request parameters. If you're using asp.net in the client, you may use the notification event RedirectToIdentityProvider then add your username to the ProtocolMessage. Something like this:
RedirectToIdentityProvider = context =>
{
context.ProtocolMessage.Parameters['username'] = "John";
return Task.CompletedTask;
}
Any value you add to the parameters will be accessible in IdentityServer through the IIdentityServerInteractionService method GetAuthorizationContextAsync
Like this, in your IdentityServer controller:
public async Task<IActionResult> Login(string returnUrl){
var context = await _interaction.GetAuthorizationContextAsync(returnUrl);
var username = context.Parameters['username'];
...
}

You can pass custom parameter to the authorize endpoint , for code sample you can refer to my reply here .
If you are not using the OpenID Connect OWIN Middleware , you can directly put the custom parameter into the authorize request :
http://localhost:xxxx/account/login?returnUrl=/connect/authorize/callback?client_id=mvc2&redirect_uri=http%3A%2F%2Flocalhost%3A49459%2Fsignin-oidc&response_type=code%20id_token&scope=openid%20profile%20api1%20offline_access&response_mode=form_post&nonce=xxxx&state=xxxx
On identity server side you can parse returnUrl and easily get the parameter .

Related

Initiate and store multiple OAuth2 external authentication challenges in a ASP.NET Core MVC application?

I can authenticate against two separate OAuth authentication schemes but it seems only one can be active at a time. I'd like to compare data from two separate SaaS applications and therefore I need two separate Bearer tokens. How can I initiate multiple OAuth challenges when the user loads the application and then store the Bearer Tokens for each? (e.g. in the Context.User cookie?)
My Startup.cs is as follows:
public void ConfigureServices(IServiceCollection services)
{
services.AddRouting();
services.AddAuthentication(options =>
{
options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme;
})
.AddCookie(options =>
{
options.LoginPath = "/signin";
options.LogoutPath = "/signout";
})
.AddScheme1 (options =>
{
options.ClientId = Configuration["Scheme1:ClientId"];
options.ClientSecret = Configuration["Scheme1:ClientSecret"];
options.Scope.Add("scope1");
options.SaveTokens = true;
})
.AddScheme2(options =>
{
options.ClientId = Configuration["Scheme2:ClientId"];
options.ClientSecret = Configuration["Scheme2:ClientSecret"];
options.Scope.Add("scope1");
options.SaveTokens = true;
});...
}
The AuthenticationController calls the Challenge overloaded method from the Microsoft.AspNetCore.Mvc.Core assembly that takes a single provider/scheme (passing multiple schemes in the overloaded method seems to be ignored).
[HttpGet("~/signin")]
public async Task<IActionResult> SignIn() => View("SignIn", await HttpContext.GetExternalProvidersAsync());
[HttpPost("~/signin")]
public async Task<IActionResult> SignIn([FromForm] string provider)
{
...
return Challenge(new AuthenticationProperties { RedirectUri = "/" }, provider);
}
Presumably, you'd prompt the user to sign-into one external application, redirect back to the home page, and then prompt them to sign-into the second one, and then allow them to start using the application proper.
If this is possible - e.g. using a "multiple" Auth cookie - how then would I fetch the correct Bearer token and User values for the given scheme? Currently you just seem to fetch the token with a generic "access_token" name and unique user values:
string accessToken = await HttpContext.GetTokenAsync("access_token");
string userID = User.FindFirstValue(ClaimTypes.NameIdentifier);
There does seem to be some information here regarding using a SignInManager but I'm unable to determine if this is applicable to this problem.
I would aim to start with a standard architecture where the user authenticates with the one and only app, and gets only one set of tokens, issued by your own Authorization Server.
SaaS DATA - OPTION 1
Does the user need to get involved in these connections or can you use a back end to back end flow here?
Your C# code could connect to the SaaS provider with the client credentials grant, using the client ID and secret that you reference above. Provider tokens would then be cached in memory, then used by the back end code to return provider data to the UI. This is a simple option to code.
SaaS DATA - OPTION 2
If the user needs to get involved, because the data is owned by them, you might offer UI options like this. After each click the user is redirected again, to get a token for that provider.
View provider 1 data
View provider 2 data
Aim to emulate the embedded token pattern, where the provider tokens are available as a secondary credential. How you represent this could vary, eg you might prefer to store provider tokens in an encrypted cookie.
CODING AND SIMPLICITY
I would not mix up provider tokens with the primary OAuth mechanism of signing into the app and getting tokens via the .NET security framework, which typically implements OpenID Connect. Instead I would aim to code the SaaS connections on demand.
I think you will find it easier to code the SaaS connections with a library approach, such as Identity Model. This will also help you to deal with SaaS provider differences more easily.
I assume you use OIDC schemes.
First, you need to add two cookie schemes, one for each OIDC authentication scheme as their sign in scheme and set their callback path to different values to stop them competing:
services.AddAuthentication()
.AddCookie("Cookie1")
.AddCookie("Cookie2")
.AddOpenIdConnect("OidcScheme1", opt =>
{
opt.SignInScheme = "Cookie1";
opt.CallbackPath = "/signin-oidc-scheme1";
opt.SaveTokens = true;
})
.AddOpenIdConnect("OidcScheme2", opt =>
{
opt.SignInScheme = "Cookie2";
opt.CallbackPath = "/signin-oidc-scheme2";
opt.SaveTokens = true;
});
This will instruct the OIDC handler to authenticate the user from corresponding cookie.
Second, you need a controller action to challenge the user against each OIDC scheme:
[HttpGet]
[Route("login")]
[AllowAnonymous]
public IActionResult Login([FromQuery]string scheme,
[FromQuery]string? returnUrl)
{
return Challenge(new AuthenticationProperties
{
RedirectUri = returnUrl ?? "/"
}, scheme);
}
From your web app, you need to send the user to the Login endpoint twice with different scheme values:
GET /login?scheme=OidcScheme1
GET /login?scheme=OidcScheme2
Or chain them together using the returnUrl:
GET /login?scheme=OidcScheme1&returnUrl=%2Flogin%3Fscheme%3DOidcScheme2
Once signed in, there should be two cookies in the browser window, for example:
To authenticate the user and restore both identities from two cookies, you can use authorization policy:
[HttpGet]
[Authorize(AuthenticationSchemes = "OidcScheme1,OidcScheme2")]
public async Task<IActionResult> SomeOperation()
{
// Two identities, one from each cookie
var userIdentities = User.Identities;
...
}
To get access token from each authentication scheme, use the method you discovered (GetTokenAsync) and specify authentication scheme:
var token1 = await HttpContext.GetTokenAsync("OidcScheme1", "access_token");
var token2 = await HttpContext.GetTokenAsync("OidcScheme2", "access_token");
It is possible that the access token is not returned from the token endpoint depends on the response_type you used. If this is the case, try set the OpenIdConnectionOptions.ResponseType to OpenIdConnectResponseType.Code and make sure the scope is correct.
I encountered a similar problem where we had microservices that are/were shared across multiple products with each product having a separate IDP tenant (essentially a different token issuer). Perhaps a similar approach might work for your scenario...
The following link helped me with a solution - see here.
Basically I defined a smart authentication scheme
var builder = services.AddAuthentication(o =>
{
o.DefaultAuthenticateScheme = "smart";
//...
});
Then in the smart policy scheme definition, I decode the JWT coming in to work out the issuer from the iss claim in the JWT, so that I can forward to the correct location for JWT bearer authentication.
builder.AddPolicyScheme("smart", "smart", options =>
{
options.ForwardDefaultSelector = context =>
{
var jwtEncodedString = context.Request.Headers["Authorization"].FirstOrDefault()?.Substring(7);
if (string.IsNullOrEmpty(jwtEncodedString))
return settings.Tenants.First().Key; // There's no authorization header, so just return any.
var token = new JwtSecurityToken(jwtEncodedString: jwtEncodedString);
var issuer = token.Claims.First(c => c.Type == "iss").Value?.TrimEnd('/');
var tenant = settings.Tenants
.Where(pair => pair.Value.Issuer.TrimEnd('/') == issuer)
.Select(pair => pair.Key).FirstOrDefault();
if (tenant == null)
throw new AuthorizationException($"Failed to locate authorization tenant with issuer '{issuer}'.");
return tenant;
};
});
Note: settings.Tenants is just an array of whitelisted tenants (from appsettings) that I configure as follows:
foreach (var tenant in settings.Tenants)
builder.AddJwtBearer(tenant.Key, options => Configure(options, tenant.Value, defaultJwtBearerEvents));

Missing scope in access token - code flow

I am trying to execute Oauth2 code flow to get access token but not able to fetch built-in email scope.
Below is my setup.
I have registered an application in Azure Active Directory. Lets say app id is - APP1
I am using V2 endpoint to access 'code' from 'authorize'endpoint.
Below is piece of code
[HttpPost]
public IActionResult Index(MyModel myModel)
{
HttpClient client = new HttpClient();
var authEndpoint = "https://login.microsoftonline.com/{my-tenant-id}/oauth2/v2.0/authorize?client_id=APP1&response_type=code&scope=openid+email";
return Redirect(authEndpoint);
}
public IActionResult Callback(string code, string error)
{
Console.WriteLine("callback");
AuthenticationContext context = new AuthenticationContext("https://login.microsoftonline.com/9e8754b6-f9cd-4aed-974d-a0ec0f3ed703");
ClientCredential cc = new ClientCredential("APP1", "xxxxxxx/_");
var resource = "c4887ff4-f750-4f1b-9781-744affe6fee2";
var r = context.AcquireTokenAsync(resource,cc).Result;
var tokenEndpoint = "https://login.microsoftonline.com/9e8754b6-f9cd-4aed-974d-a0ec0f3ed703/oauth2/v2.0/token";
return Ok("");
}
Note that I am requesting two scopes openid and email
I am getting callback with appropriate code which I am trading further to retrieve access token using ADAL library.
I am getting back the access token but scope is missing in the access token . Please see below snap.
You are using the wrong method on the confidential client app object. You aren't using the code value.
So you are acquiring a token through client credentials flow, which never has scopes since it is an app-only flow.
Use the method/overload that accepts an authorisation code :)

MVC sign in to IdentityServer4 without redirect

So I'm trying to sign in users from my ASP.NET Core 2.2 MVC app without redirecting them to IdentityServer4. So far I'm able to use IS4's ResourceOwnerPassword flow to get a token and get a token with RequestPasswordTokenAsync, but even after I set my client with the access token it's not authenticating my app.
Controller:
public async Task<IActionResult> Login()
{
var client = new HttpClient();
var response = await client.RequestPasswordTokenAsync(new PasswordTokenRequest
{
Address = "http://localhost:5000/connect/token",
ClientId = "mvc3",
ClientSecret = "secret",
UserName = "LegitUsername",
Password = "VeryLegitamitePassword",
Scope = "api1"
});
client.SetBearerToken(response.AccessToken);
return Redirect("/");
}
Current behavior: Token is granted, but my header still has the "Login" button
Expected behavior: Token is granted, "Logout" button is displayed
The current behavior suggests that I haven't been authenticated even though I'm holding the token. I know I'm missing something to pass the token to the HttpContext to authenticate my app, but can't figure out what. Any help would be appreciated.
Well, you do not log in the user. You request an access token from id4. Normally you request an access token to add it to a request (as you did) to access a resource.
Please refer to the examples: https://github.com/IdentityServer/IdentityServer4.Samples/tree/master/Clients/src
There are several examples implementations for mvc.

Cross platform authentication using ASP.NET Web API

How do I even begin coding authentication using ASP.NET Web API so it is cross-platform to support desktop, mobile and web? I'd read of some methods of doing RESTful authentication, such as using tokens in the header.
Are there any example projects out there that utilizes this method?
Questions:
If not how do I fix the [Authorize] attribute to read the token?
How do I generate this token? I dont think i can use formsauthentication because that uses cookies.
How do I handle the actual authorization, do the client send raw password and username then I generate the token or is there some other way?
How do I handle when my website is using it? I heard this is handled differently than when an app is using it, such as getting the domain and authorizing it.
I think tokens would be a solid way to go. Forms authentication is based on cookies for the web. Not the most idea situation for all non browser clients though.
What I'd suggest is creating a custom AuthorizationFilterAttribute and overriding the OnAuthorization method. In that method, you could check for the existence of a token that you've issued to the client after they've supplied valid credentials. You can use this attribute on any method or controller you want validated. Here's a sample you might reference
public class AuthorizeTokenAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext != null)
{
if (!AuthorizeRequest(actionContext.ControllerContext.Request))
{
actionContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized) { RequestMessage = actionContext.ControllerContext.Request };
}
return;
}
}
private bool AuthorizeRequest(System.Net.Http.HttpRequestMessage request)
{
bool authorized = false;
if (request.Headers.Contains(Constants.TOKEN_HEADER))
{
var tokenValue = request.Headers.GetValues("TOKEN_HEADER");
if (tokenValue.Count() == 1) {
var value = tokenValue.FirstOrDefault();
//Token validation logic here
//set authorized variable accordingly
}
}
return authorized;
} }
TOKEN_HEADER is just a string representing an HTTP header that the client should pass back for authenticated requests.
So let's walk through it
Client requests secure data
Client is not authorized, return a response with an Unauthorized status code
Client sends credentials to authenticate, which should be secured via HTTPS
Once validated, client receives a token via an HTTP header, or whatever works for you
Client tries requesting secure data again, this time attached the token to the request
The AuthorizeTokenAttribute will validate the token and allow the action to execute.
Also, check this post by John Petersen. Making your ASP.NET Web API’s secure
There are lots of ways to authenticate users for a REST service. Using tokens is possible but just using Basic Authentication is even simpler and about as standard and cross platform as you can go.
Don't confuse authorization with authentication. The [Authorize] attribute is all about authorization but only after a user has been authenticated using some other mechanism. Authorization is completely useless without doing proper authentication first.
The best resource to check is Dominick Baier who is an expert on the subject.
I use a very simple approach:
define an access profile with its unique accessId and accessKey (e.g. MD5 hashed GUID value)
store such access profile in database
every request (GET/POST/etc.) must supply accessId, queryHash (MD5 hash value represents the query) and signature (MD5 hash value of queryHash + accessKey). Of course the client needs keep the accessKey in a secure place!!!
server gets the request will check the accessId and the signature using the same calculation algorithm to reject or grant the access (authenticate)
further authorization can be done on request type basis utilizing the access profile
the service with this approach using the new ASP.NET MVC web API can serve whatever type of client: browser/javascript and native(desktop or mobile) etc.
U can use ActionFilterAttribute and override the OnActionExecuting method.
Later on register this filter in global.cs to apply this filter for all the actions like this in Application Start method
var config = GlobalConfiguration.Configuration;
config.Filters.Add(new CustomAuthAttribute ());
{
namespace Customss
{
Public class CustomAuthAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
// To inforce HTTPS if desired , else comment out the code
if (!String.Equals(actionContext.Request.RequestUri.Scheme, "https", StringComparison.OrdinalIgnoreCase))
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.BadRequest)
{
Content = new StringContent("HTTPS Required")
};
return;
}
// get toekn from the header
var userToken = actionContext.Request.Headers.GetValues("UserToken");
// Customer Logic to check the validity of the token.
// U can have some DB logic to check , custom STS behind or some loca cache used to compare the values
}
}
}
}

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