Securing Babaganoush Web Api - babaganoush-sitefinity

Loving the Web API and have created some custom ones for our dynamic module. Is there a way we can secure all the web services rather than just the custom ones we have created?
Thanks.

When inheriting from BaseDynamicController<YouCustomModel>, you can override any of the services like this:
public override IEnumerable<YouCustomModel> Get(int take = 0)
{
if (/* Not Authenticated */)
throw new System.Security.SecurityException("Not authorized to access content");
return base.Get(take);
}
In a future release, we are looking to allow this to be controlled from a virtual method: https://babaganoush.uservoice.com/forums/259241-general/suggestions/6255143-secured-web-services-option-for-dynamic-content

Related

How to obtain a JWT token in Blazor code using OpenID Connect

Create a default Blazor server (not webassembly) application using windows identity platform as authorisation (I've used VS2022 / .net 6).
Is it possible to get hold of a JWT token in a code section of a blazor component (e.g. the LoginDisplay)?
For instance - I can get hold of the claims from the authentication state as follows (for my example in LoginDisplay.razor)
#code
{
[CascadingParameter] private Task<AuthenticationState> authenticationStateTask { get; set; }
protected override async Task OnInitializedAsync()
{
var authState = await authenticationStateTask;
var user = authState.User;
var identity = user.Identity as ClaimsIdentity;
if (identity != null)
{
IEnumerable<Claim> claims = identity.Claims;
// Can I get the a JWT Token signed by Azure B2C here?
}
}
}
Can I also get a JWT Token from the Azure service (I don't want to regenerate my own - I want an original one signed by microsoft).
As clarification - when using the MSAL javascript libraries on a different project (for a Single Page Application) I could do calls such as MSAL.acquireTokenSilent to get a token from the Azure B2C service for this purpose.
UPDATE - If HttpContext.GetTokenAsync returns null
In addition enets answer below. If you find that you can't access the JWT token using HttpContext.GetTokenAsync then see this question
You can access the access token and the refresh tokenas describe below, provided that you've set your app to use Jwt Token authentication (OpenID Connect). See this answer how to do that. Note: There is also a second answer related to that question by the same user. Search for it. This answer can also be useful. See this answer, which contains links to useful answers. Note: You can Google search string such as this: "enet stackoverflow blazor jwt token", and such like to find answers by me. If you want to see answers about the AuthenticationStateProvider, just search "enet stackoverflow blazor AuthenticationStateProvider"
Getting the access token
in _Host.cshtml you can code something like this:
#using Microsoft.AspNetCore.Authentication
#{
var tokens = new InitialApplicationState
{
AccessToken = await HttpContext.GetTokenAsync("access_token"),
RefreshToken = await HttpContext.GetTokenAsync("refresh_token")
};
}
And then pass the tokens object to your Blazor app like this:
<component type="typeof(App)" render-mode="ServerPrerendered" param-
InitialState="tokens"/>
Note that the tokens object is passed as a parameter to the App component, something like this:
#code{
[Parameter]
public InitialApplicationState InitialState { get; set; }
protected override Task OnInitializedAsync()
{
TokenProvider.AccessToken = InitialState.AccessToken;
TokenProvider.RefreshToken = InitialState.RefreshToken;
return base.OnInitializedAsync();
}
}
Note: TokenProvider is a singleton service instance that hold the JWT tokens, and make it available to other parts of your app. You can save the JWT tokens in the local storage or better the the session storage and read them when needed, etc.
Note: If you don't use Web Api, then you don't need Jwt token (authentication). Use Microsoft Identity authentication
To quote MS:
The built-in AuthenticationStateProvider service for Blazor Server apps obtains authentication state data from ASP.NET Core's HttpContext.User. This is how authentication state integrates with existing ASP.NET Core authentication mechanisms.
The Jwt token is in there as bearer.
To get the header there's a Question/Answer here by #enet that shows you how to access the HttpRequest from a Blazor Server App. - How to use the HttpContext object in server-side Blazor to retrieve information about the user, user agent.
I don't have a handy project which has JWT tokens to russle up some code for you. Someone else may be able to add another answer with code or add some to this.

IdentityServer SSO - Trusted application

I need to SSO (single sign on) a user coming from an application of mine (identity provider using ASPNET Session State) and redirect them to another application of mine (service provider) that is configured to use implicit flow with IdentityServer4. I need to achieve this without requiring the user to log back in and without providing the user's password.
My initial thought was that I could use a client secret for the identity provider to redirect the user to the IdentityServer4 authentication end point with the access token as a query parameter and then use a custom validator or extension grant to issue an identity token for use with the service provider application without needing to also provide the user's password.
I've managed to issue an access token to the identity provider and then redirect the user to IdentityServer4, but issuing an identity token has proven difficult for me. I've poured over the samples and documentation and I'm confused to say the least.
I'm looking for direction on the appropriate approach to this scenario and perhaps a comprehensive example in C#. I've come to understand I can use a hybrid flow to issue an access token as well as an identity token. I think my biggest struggle is how to redirect the user and, based on the access token, issue the user an identity token (and if this is even an acceptable approach).
Simply put: I'd like to redirect the user from Application A to IdentityServer4 to Application B based on trust with the identity provider (via client secret?).
Note: I understand this could be considered an opinion-based question, but based on my research I believe there is one single best practice and that's what I'm asking for.
I managed to get this working by the following flow:
Authorize the user in Application A (Identity Provider)
Obtain Access Token from Identity Server 4 via Token Endpoint and shared secret.
Add access token as a query string parameter since headers are not preserved on redirect.
Redirect the user to an Account controller method that accepts identifying information such as username. This method is protected by a custom middleware class that checks the query string for an access token parameter. If the token exists, it is added to the authentication header; this authorizes the user to hit this controller method.
The controller method will then sign the user in and redirect them to the /connect/authorize/login endpoint.
Finally, the login endpoint sets the cookie and redirects the user to Application B (Service Provider), whose URL is specified via the redirect_uri query parameter.
Configuration for shared secret:
Add appropriate grant type, secret and new scope name to the client. The new scope will help in debugging Access token issues in your logs (especially if you have multiple applications hitting your ID4 server). Also make sure to add the Service Provider's URL to the client RedirectUris, otherwise you'll receive an "invalid redirect" error.
AllowedGrantTypes = new List<string> { GrantType.Implicit, GrantType.ClientCredentials },
ClientSecrets = new List<Secret> {
new Secret(_clientSecrets.ExternalIdpSecret.Sha256(), clientID)
},
AllowedScopes = new List<string>
{
"newScopeName"
},
RedirectUris = new List<string>
{
$"http://localhost:<portnumber>"
}
Next, add your custom middleware.
public class QueryStringOAuthBearerMiddleware
{
private readonly RequestDelegate next;
public QueryStringOAuthBearerMiddleware(RequestDelegate next)
{
this.next = next;
}
public async Task Invoke(HttpContext context)
{
this.BeginInvoke(context);
await this.next.Invoke(context);
this.EndInvoke(context);
}
private void BeginInvoke(HttpContext context)
{
if (context.Request.Query.ContainsKey("accesstokenparametername"))
{
var accessToken = context.Request.Query.First(p => p.Key == "accesstokenparametername");
if (!string.IsNullOrEmpty(accessToken.Value))
{
context.Request.Headers.Add("Authorization", "Bearer " + accessToken.Value);
}
}
}
private void EndInvoke(HttpContext context)
{
}
}
And add the middleware to your configuration.
app.UseMiddleware<QueryStringOAuthBearerMiddleware>();
Create your login method.
[HttpGet]
[Authorize]
public async Task<IActionResult> Login2(string userName, string returnURL)
{
await _httpContextWrapper.SignInAsync(userName);
return Redirect(returnURL);
}
Configuration for Client application (IDP):
Your client side code should look like this:
var disco = await DiscoveryClient.GetAsync("http://localhost:<portnumber>");
var tokenClient = new TokenClient(disco.TokenEndpoint, "clientIdentifier", "IUsedAGuidHere");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("newScopeName");
var redirectURL = string.Format("http://localhost:2228/account/Login2?userName=<UserIDValue>&returnURL={1}&accesstokenparametername={0}",
tokenResponse.AccessToken,
Server.UrlEncode(
string.Format("/connect/authorize/login?client_id={3}&redirect_uri={2}&response_type=id_token%20token&scope=<ImplicitFlowScopes>&state={0}&nonce={1}",
CryptoRandom.CreateUniqueId(),
CryptoRandom.CreateUniqueId(),
Server.UrlEncode("http://localhost:<PortNumber>"),
"ClientIdentifier")));
Response.Redirect(redirectURL, false);
Note: Please understand you won't be able to take this code AS-IS and make it work. I've heavily modified it to protect the security of my resources.
I think I might take care of the Authentication with Application A first, then forward on to the next app...
Application A --> IdentityServer --> Application A --> Application B.
You could include some custom parameters in your returnUrl which Application A could read upon return from IdentityServer that would trigger the redirect to Application B.

How to work with Identity in ASP.NET MVC

How to work with Identity in asp.net mvc. How does Identity work with membership provider, and role provider? Thank you!
There really are two problems you are looking at:
Authentication, easily solved by the built - in membership provider or open auth or LDAP or whatever. Standard ASP.NET backings are in effect.
Authorization, the interesting part. Depending on what is going in it might not matter or it could be insanely finely grained. Default would be to ride the rails of the ASP.NET RoleProviders.
At the end of the day, authentication ins ASP.NET MVC2 isn't much different from authentication ASP.NET. Standard fares apply.
I don't think there's anything special. It should "just work". The default template in MVC in fcat creates a bunch of boiler-plate code for you.
It works pretty much the same as in ASP.NET WebForms, but you control access to different parts of your site by decorating actions or controllers with attributes.
Example:
public class HomeController
{
// Does not require any authentication
public ActionResult Index(int id)
{
return View();
}
// Requires login, and that the logged in user is in the "Users"-Role
[Authorize(Roles="Users")]
public ActionResult SemiSecret(int id)
{
return View();
}
// Same as above, but requires user to be in "Admin" Role
[Authorize(Roles="Admin")]
public ActionResult TopSecret(int id)
{
return View();
}
}
on a controller:
// All actions in this controller requires users to log in and be in "Admin" role
[Authorize(Roles="Admin")]
public class AdminController
{
// Controller code goes here ...
}
You can also limit this on a userlevel by using [Authorize(Users="UserName")]
Hope this helps!

Best practice for dual-use iFrame + External authentication for Facebook enabled app

Okay, if cookies are a no-no, then I need a little guidance as to the best way to implement the application(s) that I'm creating.
The scenario is that I'm trying to create a single Asp.Net MVC application that can authenticate a user regardless of whether the user visits a site directly or via an iFrame in Facebook. There are separate actions (in separate controllers, actually) for getting INTO the app depending on whether the user enters via Facebook or not, but there are also places in the Facebook app where I'm opening up a new window to "extended" functionality in other areas of the application that can't really work well within the iFrame. It is supposed to transition seamlessly. It's currently working quite well using cookies, but I've from multiple sources that this is not a good thing for iFrame apps. However, I'm not sure exactly what this means.
Without cookies, can you still somehow get server-side access to the authentication token? If not, then what is the "right" way to handle this. Do I need to resort to manually parsing the token using the JS API and sending an AJAX notification to the server of the fact that the user is authenticated and create a forms auth token? Will the CanvasAuthorize attribute work without cookies? Right now I have added code to the FormsAuthentication_OnAuthenticate event in Global.asax to create the forms auth token if the user is logged in via Facebook (and properly associated with a valid user in the external app) as follows:
protected void FormsAuthentication_OnAuthenticate(Object sender, FormsAuthenticationEventArgs args)
{
if (FormsAuthentication.CookiesSupported)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] == null)
{
// Attempt to authenticate using Facebook
try
{
FacebookApp fbApp = new FacebookApp();
if (fbApp.Session != null)
{
dynamic me = fbApp.Get("me");
String fbID = "" + me.id;
MembershipUser mUser = AppMembershipProvider.GetUserByFacebookID(fbID);
if (mUser != null)
{
FormsAuthentication.SetAuthCookie(mUser.UserName, false);
AppMembershipProvider.UpdateLastLogin(mUser.UserName);
Session["FacebookLogin"] = true;
}
}
}
catch (Exception e)
{
Elmah.ErrorSignal.FromCurrentContext().Raise(e);
}
}
}
else
{
throw new HttpException("Cookieless Forms Authentication is not " +
"supported for this application.");
}
}
Will I need to change this?
Sorry if this is basic knowledge, but I'm confused as to how best to implement this. Thanks!
First, let me address the issue with the cookies. So, when I say to not use cookies in iFrames I am saying that for a couple reasons. First in IE, there are some security issues. You need to add the following header to your app to make cookies work correctly inside iframes:
P3P: CP="CAO PSA OUR"
The second big issue with cookies in iframe apps is Safari. Due to security settings in Safari, cookies cannot be created by iframes. As such, you will not be able to rely on cookies for authentication inside of iframes.
Give that you are using the app inside and outside of the iframe, you should have cookie support turned on. However, your app must be designed in a way that will work around the iframe issues. That is going to be the hard part.
The most reliable authentication inside iframe apps is the signed request method. What happens is facebook will append a query parameter to your url when the url is rendered inside the iframe. This query parameter contains the user's session. The Facebook C# SDK handles reading this for you, so you dont need to parse it etc. But you need to be aware that it is there. If you view the incoming request url of your iframe app in facebook you will see something like http://www.mysite.com/page/?signed_request={blahblahblah}.
So the key is that you need to make sure that if you are in the iframe you keep that ?signed_request value on the url.
You can do this several ways. First, you can use the CanvasRedirect methods. These are extension methods on System.Web.Mvc.Controller in the Facebook.Web.Mvc namespace. The canvas redirect uses javascript to redirect your page in the top url. This way Facebook is actually handling the redirects and will always add the signed_request to your iframe url. The problem for you is that this method of redirecting will only work in the iframe, not outside.
The second way would be to manually add the ?signed_request to the url when you redirect. You would do something like:
public ActionResult Something() {
return RedirectToAction("something", new { signed_request = Request.Querystring["signed_requets"]);
}
There are other ways also, like storing data in the session or something, but I wouldn't recommend going down that path.
What you are doing is definitely an advanced senario, but hopefully the above will help you get going in the right direction. Feel free to contact me directly if you have any questions. nathan#ntotten.com or #ntotten on twitter.
I am in a similar situation to you. What I do to handle the various situations that can arise is:
Enable cookies in both the C# and
JavaScript SDK.
Create a custom actionfilter that
inherits from
FacebookAuthorizeAttribute and
overrides the
HandleUnauthorizedRequest method to
redirect to either a connect
authorization page or an action
decorated with the
CanvasAuthorizeAttribute.
Pass either the signed_request
(canvas app) or auth_token (connect
app) as a querystring parameter to
everything.
Check for null sessions and oauth
tokens that don't match what has been
passed in the querystring.
The main point is to ensure that both the session and oauth tokens are valid. When inside Facebook the signed_request will ensure this is true. By passing the token from your connect auth page you can ensure you have a valid token to inject into the FacebookApp constructor.
public class FbAuthenticateAttribute : FacebookAuthorizeAttribute
{
private FacebookApp _fbApp;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
var accessToken = filterContext.HttpContext.Request.Params["access_token"];
if (FacebookApp.AccessToken != accessToken && !string.IsNullOrEmpty(accessToken))
{
_fbApp = new FacebookApp(accessToken);
}
else
{
_fbApp = FacebookApp;
}
filterContext.Controller.ViewBag.Context = GetContext().ToString();
filterContext.RequestContext.HttpContext.Response.AppendHeader("p3p", "CP=\"CAO PSA OUR\"");
try
{
dynamic user = _fbApp.Get("me");
var signedRequest = filterContext.HttpContext.Request.Params["signed_request"];
filterContext.Controller.ViewBag.QueryString = string.IsNullOrEmpty(signedRequest)
? "?access_token=" + _fbApp.AccessToken
: "?signed_request=" + signedRequest;
}
catch (Exception ex)
{
string url = GetRedirectUrl(filterContext);
filterContext.Result = new RedirectResult(url);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
string url = GetRedirectUrl(filterContext);
filterContext.Result = new RedirectResult(url);
}
private string GetRedirectUrl(ControllerContext filterContext)
{
return new UrlHelper(filterContext.RequestContext).Action(GetRedirectAction(GetContext()), "Authentication");
}
private Enums.AppContext GetContext()
{
//Note: can't rely on this alone - find something more robust
return FacebookApp.SignedRequest == null ? Enums.AppContext.FBWeb : Enums.AppContext.FBApp;
}
private string GetRedirectAction(Enums.AppContext context)
{
return context == Enums.AppContext.FBWeb ? "ConnectAuthenticate" : "Authenticate";
}
}
It could definitely do with a refactor and still has problems but is the best solution I have found so far.

How to eliminate ReturnUrl from the browser address

Now on unauthorized attempt to access an action my ASP.NET MVC app redirects user to the login page and generates URL shown below:
http://www.mysite.com/Account/Log?ReturnUrl=%2Ftest%2Fsampleaction
So, is there a way to eliminate this string from the URL, but to save it somewhere to be able to redirect user back after login?
I wonder why you would want to do that. Maybe you are sick of misused, excessive URL parameter orgies, and you like the clean RESTful URL style and the elegant way it can be implemented using the new ASP.NET Routing feature.
However, in this case, this is exactly what URL parameters are intended for. It's not bad practice or bad style at all. And there is absolutely no reason to apply SEO witchery to your login page. So why should you make this process less reliable for the user by requiring the session state directly (or indirectly via TempData), or any other workaround?
I would consider to implement my own AuthorizationFilter and do the redirect.
public class AuthorizationFilter : IFilter
{
public bool Perform(ExecuteWhen exec, IEngineContext context,
IController controller, IControllerContext controllerContext)
{
if (context.CurrentUser.IsInRole("Administrator"))
{
return true;
}
context.Response.Redirect("home", "index");
return false;
}
}
Before redirecting to login action store url
TempData["redirect-url"] = "/requested/page/url";
on login action read that value and pass it to login view and put to a hidden field.
I would implement a AuthorizationAttribute
public class MyAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (filterContext.Result is HttpUnauthorizedResult)
{
filterContext.HttpContext.Session["ReturnUrl"] = filterContext.HttpContext.Request.UrlReferrer.AbsoluteUri
filterContext.Result = // Your login page controller;
}
}
}
This is not tested but might help you find the answer
Good luck to you, please provide your solution when found.