Url.Content not working when using under .net core 3.1 & - asp.net-core-3.1

I am trying to follow below article for SAML implementation & i am very new to the .net core and SAML
https://developer.okta.com/blog/2020/10/23/how-to-authenticate-with-saml-in-aspnet-core-and-csharp
When added code into AuthController.cs , i am getting error for Login method. In below code Url.Content giving error 'The name url does not exist in current context'. Also package 'using Okta_SAML_Example.Identity;' is giving error regarding assembly as its not there.
var binding = new Saml2RedirectBinding();
binding.SetRelayStateQuery(new Dictionary<string, string> { { relayStateReturnUrl, returnUrl ?? Url.Content("~/") } });
Want to set the context : my idp will be internal organization idp [it will be configured by different team in org and for now they want me to provide attributes which i want in response] so where exactly in code it will be referred as i dont see IDP reference url in the code & xml sample too. please help me as need guidance at earlist.

I'm in doubt why you are seeing the error, it is not an error I have experienced.
You can try to download the ITfoxtec.Identity SAML 2.0 code and run the TestIdPCore and TestWebAppCore samples in the test folder.
The library documentation.
The IdP can be configured in the appsettings.json file, here an example from the TestWebAppCore sample. The easiest way is to configure the IdP metadata, which will establish the trust without further configuration.

Related

buji-pac4j integartion with Apache Shiro and identityServer3

I am trying to learn integration of buji-pac4j. I already tried demo version which is provided on following URL https://github.com/pac4j/buji-pac4j-demo but it is seem to be working for me partially. (there is some issue from ops side to give me correct call back url).
So far I can notice handshake is happening using demo code.
I’m now trying other way as it is been provided in the documentation that is client.
As per documentation:
A Client represents an authentication mechanism. It performs the login process and returns (if successful) a user profile.
My class has now following details
OidcConfiguration oidcConfiguration = new OidcConfiguration();
oidcConfiguration.setClientId("someClientIDString");
oidcConfiguration.setSecret("someClientSecretString");
oidcConfiguration.setDiscoveryURI("https://development.domainName.com/projectName/idp/.well-known/openid-configuration");
oidcConfiguration.setScope("openid email hrauser hrainfo");
oidcConfiguration.setCallbackUrl("http://localhost:8080/callback");
OidcClient oidcClient = new OidcClient(oidcConfiguration);
Config config = new Config(oidcClient);
config.addAuthorizer("admin", new RequireAnyRoleAuthorizer("ROLE_ADMIN"));
OidcAuthenticator OidcAuthenticator = new OidcAuthenticator(oidcConfiguration);
Above is mostly setting variable in the class,
What am not able to figure is out how above will actually go and talk to openID server.
What all part I am missing.
I am going through the documentation provided on https://github.com/bujiio/buji-pac4j but it is not clear to me on the flow.
Any kind of help or direction will be appreciated.
PS: I am quite new in this area so request to bear with me.

Throwing 404 error with the authoriseUrl generated from GetRefreshToken

I am trying to create a sample project which consumes DFP services.
Till now :
Still in authentication part :
a) Successfully created clientId, while creating new Client Id have checked installed apps options in the Google developer console.
b) Added the clientId, clientSecret to ads.properties .
Note : Took dfp-axis-jars-and-examples-2.2.0.tar and making my changes in it[by importing project in IDE].
c) I ran into trouble while trying to paste the authoriseUrl in the browser after running GetRefreshToken.
Please find below the error :
"The redirect URI in the request: urn:ietf:wg:oauth:2.0:oob can only
be used by a Client ID for native application. It is not allowed for
the 'WEB' client type. You can create a Client ID for native
application in the Credentials section of the Google Developers
Console."
I believe I have selected the wrong applicationType while creating new ClientId .
Appreciate inputs .
The above answer did not make much sense at first glance but, I have resolved this issue by simply setting a value for redirectUri. So inside of my GetRefreshToken.php file
$redirectUri = "http://same_url_as_the_one_listed_in_console";
After closing looking at the authoriseUrl, it seemed I was sending the wrong redirectUrl.
I forgot to copy paste the redirectUrl generated from the creation of client id in the GetRefreshToken callback property:
private static final String CALLBACK_URL = "https://www.example.com/oauth2callback";//"urn:ietf:wg:oauth:2.0:oob";
No error now :).

App with no DB: You must call the "WebSecurity.InitializeDatabaseConnection" method before you call any other method of the "WebSecurity" class

First things first. I'm a complete OAuth newbie. This will be my first stab at it, and things are getting hairy...
I'm writing a single page application using Durandal & Web API.
The user needs to be able to login using any social network.
I don't have access to a database whatsoever, I have to call an unprotected 3rd party web service which I consume server-side, and need to protect using OAuth.
So I've managed to add the files to my solution which generates the login using facebook contol/button (created a new MVC4 web application, and did a manual copy and paste of all the auth related files, updated bootstrappers etc..), and the code seems to work for the most part.
When facebook redirects back to
[AllowAnonymous]
public ActionResult ExternalLoginCallback(string returnUrl)
{
AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(this.Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
if (!result.IsSuccessful)
{
return this.RedirectToAction("ExternalLoginFailure");
}
if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
{
return this.RedirectToLocal(returnUrl);
}
//code removed for brevity ....
}
I get the error specified once the following line tries to execute.
OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false)
I've removed the [InitializeSimpleMembership] attribute from the controller, as I don't have a database.
Please forgive me if this is the dumbest question ever, but...
Why does the login fail? I mean at that point, isn't the app trying to log into facebook, why does it need a databse? Or am I correct in saying I can remove/replace that code section, with a login/authorise call on the web-service I'm using?
Not the dumbest question ever. Not by a long shot. But you are getting the error because your membership provider is still set to use the SimpleMembershipProvider and OAuthWebSecurity will use the default membership provider. If you don't want to use a database you will have to create or find a different membership provider to use.
EDIT:
I know you said you don't have access to a DB but if you can use SQL Compact you can just stick with the default SimpleMembershipProvider(check out Hanselman's blog) or DevArt has a SQLLite provider. Also the MemFlex Project has a RavenDb provider. If none of those work I think you might just have to write your own.

Custom URL parameters lost after OpenAM login redirection

I'm using OpenAM for authentication on my application. I access to my app using such URL:
http://my.company.com/appfolder/appservlet?lang=EN&user=test
On first access, OpenAM agent catches the URL and redirect my browser to the authentication page using this redirection URL:
...openam/UI/Login?goto=http%3A%2F%2Fmy.company.com%3A8080%2Fappfolder
After correct authentication, I'm finally redirected to the following URL:
http://my.company.com/appfolder
This is logic since this is the URL referenced in goto param. But it's not the same than original one: the servlet and custom params (lang and user) are missing.
Any idea how to configure my agent to make it keep servlet and params after redirection ?
take a look at this step of the tutorial "Add Authentication to a Website using OpenAM".
In section "Creating An Access Policy" -> "Wildcard matching" is your answer:
The wildcard * in policy URLs does not match '?'. As such if you
wish to allow GET parameters to be submitted then a second policy for
http://webserver.example.com/*?* is required.
Thanks for your answer. As mentionned in my previous comment, the adding of new policy does not resolve my issue. Actually, I'm not sure to understand how the policies can solve the issue since the goto parameter is generated by the J2EE agent, which acts before policies are applied (as far as I know... I'm maybe wrong).
Anyway, I could solve my problem by re-compiling the J2EE Agent: I've build a new agent.jar based on v3.0.3 available at forgerock. Then I replaced the AmFilterRequestContext.class by a new one, build on source available here:
http://www.docjar.com/html/api/com/sun/identity/agents/filter/AmFilterRequestContext.java.html
With this new agent, my goto is now correct, and redirection works well (and I don't have to define any policy).
The strange thing is that I don't understand why it works now ! I couldn't find any difference between java source mentionned above and uncompiled version of original class! I just added some System.out.println to get variables values and functions results, and built the jar. After restaring my jboss, the goto was correct. I'll try to understand why this finally work now when I've time.

ASP.NET Web API Authorization with AuthorizeAttribute

Using the new ASP.NET Web API beta. I can not seem to get the suggested method of authenticating users, to work. Where the suggested approach seems to be, to add the [Authorize] filter to the API controllers. For example:
[Authorize]
public IEnumerable<Item> Get()
{
return itemsService.GetItems();
}
This does not work as intended though. When requesting the resource, you get redirected to a login form. Which is not very suitable for a RESTful webapi.
How should I proceed with this? Will it work differently in future versions?, or should I fall back to implementing my own action filter?
Double check that you are using the System.Web.Http.AuthorizeAttribute and not the System.Web.Mvc.AuthorizeAttribute. This bit me before. I know the WebAPI team is trying to pull everything together so that it is familiar to MVC users, but I think somethings are needlessly confusing.
Set your authentication mode to None:
<authentication mode="None" />
None Specifies no authentication. Your application expects only anonymous users or the application provides its own authentication.
http://msdn.microsoft.com/en-us/library/532aee0e.aspx
Of course then you have to provide some sort of authentication via headers or tokens or something. You could also specify Windows and use the built in auth via headers.
If this site is mixed between API and actual pages that do need the Forms setting, then you will need to write your own handling.
All the attribute does is return an HttpUnauthorizedResult instance, the redirection is done outside of the attribute, so its not the problem, its your authentication provider.
Finally, I've found a solution at:
ASP.NET MVC 4 WebAPI authorization
This article shows how you can fix this issue.
You are being redirected to login page because forms authentication module does this automatically. To get rid of that behavior disable forms authentication as suggested by Paul.
If you want to use more REST friendly approach you should consider implementing HTTP authorization support.
Take a look at this blog post http://www.piotrwalat.net/basic-http-authentication-in-asp-net-web-api-using-membership-provider/
ASP.NET 5 Introduced the new Microsoft.AspNet.Authorization System which can secure both MVC and Web API controllers.
For more see my related answer here.
Update:
At that time 2 years ago it was Microsoft.AspNetCore.Authorization.
As #Chris Haines pointed out. now it resides on
Microsoft.AspNetCore.Authorization.
From .NET core 1.0 to 2.0 many namespaces have been moved i think.
And spread functionality between .net classic and core was obscure.
That's why Microsoft introduced the .net standard.
.net standard
Also, look at my answer for:
How to secure an ASP.NET Web API
There is a NuGet package I have created which you can use for convenience.
If you're using a Role, make sure you have it spelled correctly :
If your role is called 'Administrator' then this - for instance will not work :
[System.Web.Http.Authorize(Roles = "Administator")]
Neither will this :
[System.Web.Http.Authorize(Roles = "Administrators")]
Oops...
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Produces("application/json")]
[Route("api/[controller]")]
public class CitiesController : Controller
{
[HttpGet("[action]")]
public IActionResult Get(long cityId) => Ok(Mapper.Map<City, CityDTO>(director.UnitOfWork.Cities.Get(cityId)));
}
Use
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
Filter with authentication type