PHP authentication integration with WOS2 Identity Server - wso2

Actually, I have a CakePHP application that authenticates with SimpleSAML using WSO2 Identity Server (it redirects to WSO2IS login page). I need to create a page in my application and send the informations to WSO2IS to authenticate the user. How can I do it? I didn't found any example/documentation about it.
I followed this tutorial.
Files in simplesaml:
config/authsources.php
<?php
$config = array(
'wso2-sp' => array(
'saml:SP',
'entityID' => 'IntranetSP', // I supposed that it is the ID of my Service Provider
'idp' => 'https://soa.rw1.local:9443/samlsso'
)
);
?>
metadata/saml20-idp-remote.php
<?php
$metadata['https://soa.rw1.local:9443/samlsso'] = array(
'name' => array(
'en' => 'WSO2 IS',
'no' => 'WSO2 IS',
),
'description' => 'Login with WSO2 IS SAML2 IdP.',
'SingleSignOnService' => 'https://soa.rw1.local:9443/samlsso',
'SingleLogoutService' => 'https://soa.rw1.local:9443/samlsso',
'certFingerprint' => '6bf8e136eb36d4a56ea05c7ae4b9a45b63bf975d'
);
?>
In my Wso2 IS:
Service provider Configuration:
Service Provider Name: IntranetSP
Local & Outbound Authentication Configuration/Request Path Authentication Configuration: basic-auth

In your service provider configuration, under local and outbound authentication configuration, configure SP to use request path authentication.For more information about doing this, please follow this.
Following is a java code where you can send the request from a client.
#Test(alwaysRun = true, description = "Test login success")
public void testLoginSuccess() throws Exception {
HttpPost request = new HttpPost(TRAVELOCITY_SAMPLE_APP_URL + "/samlsso?SAML2.HTTPBinding=HTTP-POST");
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("username", adminUsername));
urlParameters.add(new BasicNameValuePair("password", adminPassword));
request.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(request);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String line;
String samlRequest = "";
String secToken = "";
while ((line = rd.readLine()) != null) {
if (line.contains("name='SAMLRequest'")) {
String[] tokens = line.split("'");
samlRequest = tokens[5];
}
if (line.contains("name='sectoken'")) {
String[] tokens = line.split("'");
secToken = tokens[5];
}
}
EntityUtils.consume(response.getEntity());
request = new HttpPost(isURL + "samlsso");
urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("sectoken", secToken));
urlParameters.add(new BasicNameValuePair("SAMLRequest", samlRequest));
request.setEntity(new UrlEncodedFormEntity(urlParameters));
response = client.execute(request);
String samlResponse = "";
rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null) {
if (line.contains("name='SAMLResponse'")) {
String[] tokens = line.split("'");
samlResponse = tokens[5];
}
}
Base64 base64Decoder = new Base64();
samlResponse = new String(base64Decoder.decode(samlResponse))
EntityUtils.consume(response.getEntity());
}
You should be able to achieve this in PHP by sending the same requests.
But if your requirement is to change the login page, you can customize wso2 IS login page as mentioned here without using your own page. If your requirement is this, I recommend you to do this as this will make your life much easier.

Related

Amazon Cognito Identity with API Gateway

I'm develop app IOS and Android with Xamarin cross-platform.
I'm trying hard to use credentials receiving from Cognito Identity to authorize app invoking API Gateway.
My user flow is:
Authenticate on Cognito User Pool and get tokens
Exchange tokens for credentials on Cognito Identity Pools
Access API Gateway using credentials retrieved in the previous step.
Step 1 and 2 seems to works fine. But when app try to connect to api gateway it's getting error 403 (Forbidden).
My code:
Authenticate on Cognito User Pool and get tokens
**
public async Task<AppUser> Login(string username, string password)
{
CognitoUser cognitoUser = new CognitoUser(username, Aws.COGNITO_CLIENT_ID, CognitoUserPool, CognitoIdentityProviderClient);
AppUser appUser = new AppUser() { Email = username };
// Send a login request and wait for the response from Amazon
try
{
AuthFlowResponse response = await cognitoUser.StartWithSrpAuthAsync(new InitiateSrpAuthRequest()
{
Password = password
});
;
appUser.IsAuthenticated = true;
}
catch (NotAuthorizedException e)
{
appUser.IsAuthenticated = false;
appUser.ErrorMessage = e.Message;
}
await _tokenManagement.SaveTokens(cognitoUser.SessionTokens) ;
return appUser;
}
Exchange tokens for credentials on Cognito Identity Pools
**
public async Task<ImmutableCredentials> GetAppCredentialsAsync()
{
CognitoAWSCredentials cac;
if (_tokenManagement.CheckIsAnonymous())
{
//Anonymous credentials
cac = new CognitoAWSCredentials(Aws.COGINITO_IDENTITY_POLL_ID, RegionEndpoint.USEast1);
}
else
{
//Retrieve saved tokens from previous authentication
var tm = await _tokenManagement.RetrieveTokens();
CognitoUser user = new CognitoUser(null, Aws.COGNITO_CLIENT_ID, CognitoUserPool, CognitoIdentityProviderClient)
{
SessionTokens = new CognitoUserSession(tm.IdToken, tm.AccessToken, tm.RefreshToken, tm.IssuedTime, tm.ExpirationTime)
};
//Retrieve authenticated credentials
cac = user.GetCognitoAWSCredentials(Aws.COGINITO_IDENTITY_POLL_ID, RegionEndpoint.USEast1);
}
}
return await cac.GetCredentialsAsync();
}
Access API Gateway using credentials retrieved in the previous step:
**
public async Task<IList<MediaImage>> GetCoversAWSAsync()
{
// Getting credentials and sign request
var request = await BuildRequestAsync("/listMedia");
var client = new HttpClient();
var response = await client.SendAsync(request);
response.EnsureSuccessStatusCode();
IList<MediaImage> covers = JsonConvert.DeserializeObject<IList<MediaImage>>(await response.Content.ReadAsStringAsync());
return covers;
}
private async Task<HttpRequestMessage> BuildRequestAsync(string service)
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri(baseURL + service)
};
ImmutableCredentials awsCredential = await _loginService.GetAppCredentialsAsync( );
var signer = new AWS4RequestSigner(awsCredential.AccessKey, awsCredential.SecretKey);
request = await signer.Sign(request, "execute-api", awsRegion);
return request;
}
This code works fine when I hard code credentials from one IAM user. But credentials retrieved from Cognito Identities its getting Forbidden error.
I did a test using SDK for S3 and I was able to successfully list the buckets with the same credentials received from Cognito Identities, but it is not possible to make requests on the API Gateway.
Can you help me? Where did I get lost?
I figure out what was going on.
After ensuring that the permissions settings were correct on AWS.
I found in the documentation that it is necessary to include in the HTTP header the token returned by the cognito (header name x-amz-security-token). So I changed the code to the following:
private async Task<HttpRequestMessage> BuildRequestAsync(string service)
{
var request = new HttpRequestMessage()
{
Method = HttpMethod.Get,
RequestUri = new Uri(baseURL + service)
};
ImmutableCredentials awsCredential = await _loginService.GetAppCredentialsAsync( );
//This where I add header to the HTTP request
request.Headers.Add("x-amz-security-token", awsCredential.Token);
var signer = new AWS4RequestSigner(awsCredential.AccessKey, awsCredential.SecretKey);
request = await signer.Sign(request, "execute-api", awsRegion);
return request;
}

AWS Cognito TOKEN endpoint fails to convert authorization code to token

My app first uses the Cognito LOGIN endpoint to obtain an Authorization Code. It then uses the TOKEN endpoint to try and obtain tokens (id_token, access_token, refresh_token) but that fails with unauthorized_client.
I do not understand why, the same client is used to access the LOGIN, and that succeeded in returning an authorization code. I'm following the documentation for the TOKEN endpoint
string clientId = ...
string clientSecret = ...
Uri redirectUri = new Uri("myapp://myhost");
string authorization_code = ... // obtained via HTTP GET on LOGIN endpoint
string accessTokenUrl = "https://<domain>.auth.<region>.amazoncognito.com/oauth2/token";
var queryValues = new Dictionary<string, string>
{
{ "grant_type", "authorization_code" },
{ "code", authorization_code },
{ "redirect_uri", redirectUri.AbsoluteUri },
{ "client_id", clientId},
};
using (HttpClient client = new HttpClient())
{
// Authorization Basic header with Base64Encoded (clientId::clientSecret)
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(
"Basic",
Convert.ToBase64String(System.Text.ASCIIEncoding.ASCII.GetBytes(
string.Format("{0}:{1}",
clientId,
clientSecret))));
// Url Encoded Content
var content = new FormUrlEncodedContent(queryValues);
// HTTPS POST
HttpResponseMessage response = await client.PostAsync(accessTokenUrl, content).ConfigureAwait(false);
string text = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
// test = {"error" : "unauthorized_client"}
}
The problem is two-fold:
1- System.Uri.AbsoluteUri adds a trailing / in the returned string so that my redirectUri becomes myapp://myhost/ instead of myapp://myhost
2- AWS Cognito TOKEN endpoint does not accept trailing / in a redirectURI.
The solution:
I now call redirectUri.OriginalUri instead of redirectUri.AbsoluteUri where I build the query to preserve the redirectUri as it was when I built it.
(I don't really have control over this since in my case Xamarin.Auth.OAuthAuthenticator2 calls Uri.AbsoluteUri on my behalf and transforms the redirectUri string I gave it, so I'm going to have to fix Xamarin.Auth).

Adding custom message header to a WCF service which is consumed from Windows Mobile 6 client

I have a WCF Service Application which server to different type of clients. While calling the service methods I want to send some spesific information within the service header.
While using a newer version of .NET Framework I can handle the situation using MessageHeader. Since the consumer can see the service as WCF Service there is no problem.
[DataContract]
public class AuthToken
{
[DataMember]
public string Username { get; set; }
[DataMember]
public string Password { get; set; }
}
Client-side:
AuthWCFSvc.Service1Client client = new AuthWCFSvc.Service1Client();
using (OperationContextScope scope = new OperationContextScope(client.InnerChannel))
{
SvcAuthClient.AuthWCFSvc.AuthToken token = new AuthWCFSvc.AuthToken();
token.Username = "wcfuser";
token.Password = "wcfpass";
MessageHeader<SvcAuthClient.AuthWCFSvc.AuthToken> header = new MessageHeader<SvcAuthClient.AuthWCFSvc.AuthToken>(token);
var untyped = header.GetUntypedHeader("Identity", "http://www.my-website.com");
OperationContext.Current.OutgoingMessageHeaders.Add(untyped);
client.TestHeader();
}
Server-side :
MessageHeaders headers = OperationContext.Current.IncomingMessageHeaders;
AuthToken token = headers.GetHeader<AuthToken>("Identity", "http://www.my-website.com");
But there are Windows Mobile 6 devices with .NET Framework 3.5 Compact Edition, using these services as well. Due to technological restrictions, they only can process the WCF services as Web Services.
If a client is consuming a WCF service as Web Service how can add spesific header information and resolve the header information at the service method?
As you know, on .NET CF 3.5 you can only use WCF as standard webservice on SOAP way. Therefore, you can't use any of WCF native security resources.
I figured out how to use Basic Http Authentication, configuring client and server sides and I can explain it as follows:
Client Side
On client side (on your device with .Net CF 3.5), its easy. Just inform your credentials configuring your clientServiceProxy by using:
var service = new YourServiceNamespace.YourService();
service.Credentials = new NetworkCredential("login", "12345");
service.PreAuthenticate = true;
This will make your client deal with the "WWW-Authenticate" header from the server response and pass your credentials automatically via the response header "Authorization: Basic".
Server Side
On the WCF configuration on your web.config, you should configure security just for Transport, and use HTTPS (this is enough to protect your message from sniffers).
<basicHttpBinding>
<binding>
<security mode="Transport">
<transport clientCredentialType="None" />
</security>
</binding>
</basicHttpBinding>
Now, as WCF doesn't has native support for Basic Http Authentication, we have to use a custom HTTP module to deal with it.
public class BasicHttpAuthentication : IHttpModule
{
public delegate bool AuthenticateDelegate( string username, string password );
public static AuthenticateDelegate AuthenticateMethod;
public void Dispose() { }
public void Init( HttpApplication application )
{
application.AuthenticateRequest += this.OnAuthenticateRequest;
application.EndRequest += this.OnEndRequest;
}
private void DenyAccess( HttpApplication app )
{
app.Response.StatusCode = 401;
app.Response.StatusDescription = "Access Denied";
// Write to response stream as well, to give user visual
// indication of error during development
app.Response.Write( "401 Access Denied" );
app.CompleteRequest();
}
private void OnAuthenticateRequest( object source, EventArgs eventArgs )
{
if ( AuthenticateMethod == null )
return;
var app = ( HttpApplication )source;
//the Authorization header is checked if present
string authHeader = app.Request.Headers["Authorization"];
if ( !string.IsNullOrEmpty( authHeader ) )
{
string authStr = app.Request.Headers["Authorization"];
if ( string.IsNullOrEmpty( authStr ) )
return; // No credentials; anonymous request
authStr = authStr.Trim();
if ( authStr.IndexOf( "Basic", 0 ) != 0 )
// header is not correct...we'll pass it along and
// assume someone else will handle it
return;
authStr = authStr.Trim();
string encodedCredentials = authStr.Substring( 6 );
byte[] decodedBytes = Convert.FromBase64String( encodedCredentials );
string s = new ASCIIEncoding().GetString( decodedBytes );
string[] userPass = s.Split( new[] { ':' } );
string username = userPass[0];
string password = userPass[1];
if ( !AuthenticateMethod( username, password ) )
this.DenyAccess( app );
}
else
{
app.Response.StatusCode = 401;
app.Response.End();
}
}
private void OnEndRequest( object source, EventArgs eventArgs )
{
//the authorization header is not present
//the status of response is set to 401 and it ended
//the end request will check if it is 401 and add
//the authentication header so the client knows
//it needs to send credentials to authenticate
if ( HttpContext.Current.Response.StatusCode == 401 )
{
HttpContext context = HttpContext.Current;
context.Response.StatusCode = 401;
context.Response.AddHeader( "WWW-Authenticate", "Basic Realm=\"Please inform your credentials\"" );
}
}
}
To enable the HTTP module, add the following to your web.config file in the system.webServer section:
<system.webServer>
<modules>
<add name="BasicHttpAuthentication"
type="BasicHttpAuthentication, YourAssemblyName"/>
</modules>
Now you have to inform to the module a Function to use for validating the credentials from the client. You can see that there's a static delegate inside the module called "AuthenticateMethod", so you can inform a function on your Application_Start of your global.asax:
BasicHttpAuthentication.AuthenticateMethod = ( username, password ) => username == "login" && password == "12345";

API Manager OAuth Token Revoke is Problematic

I am using SAML2 Bearer assertion profile to obtain OAuth Tokens form WSO2 API Manager. I have two client applications. In the OAuth Token Revoking process I am using following code,
public static boolean revokeToken(Token token) throws IOException {
//Create connection to the Token endpoint of API manger
URL url = new URL(Config.apiMangerOAuthRevokeURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
String userCredentials = Config.apiMangerClientID+":"+ Config.apiMangerClientSecret;
String basicAuth = "Basic " + new String(Base64.encodeBytes(userCredentials.getBytes()));
basicAuth = basicAuth.replaceAll("\\r|\\n", "");
// Set the consumer-key and Consumer-secret
connection.setRequestProperty("Authorization", basicAuth);
connection.setUseCaches(false);
connection.setDoInput(true);
connection.setDoOutput(true);
//Send request
DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
wr.writeBytes("token="+token.getAccess_token());
wr.flush();
wr.close();
//Get Response
InputStream iss = connection.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(iss));
String line;
StringBuffer responseString = new StringBuffer();
while ((line = rd.readLine()) != null) {
responseString.append(line);
responseString.append('\r');
}
rd.close();
System.out.println("Revoking Token Mobile-"+token.getAccess_token());
System.out.println("Revoking Response Mobile -"+responseString.toString());
return true
;
}
One client application do the revoking process OK. I tried to invoke API using CURL after revoking, it fails as expected. But the other client application which use same above logic to revoke tokens return well. But the token is valid after revoking. I can use CURL to query the API. What has gone wrong here?
API Manager has caching enabled by default and is set to 15 min. Try disabling it.

Facebook API - saving OAuth access token in session

I am trying to find a way to keep connected with the Facebook API once authorised using OAuth but am having problems. I dont want the users of my App to have to login via Facebook every time they want to use my app.
I store the oauth access toekn in a database after the user authenticates with facebook and I have "offline_access" permissions set, so in theory, this should be possible.
However, I get "Uncaught OAuthException: An active access token must be used to query information about the current user." when trying to connect to Facebook API using a saved Oauth token stored in a database.
header("p3p: CP=\"ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV\""); // hack to stop facebook wierd cookie problems
//instantiate the Facebook library with the APP ID and APP SECRET
$facebook = new Facebook(array(
'appId' => 'appid',
'secret' => 'secretid',
'cookie' => true
));
//Get the FB UID of the currently logged in user
$user = $facebook->getUser();
//if the user has already allowed the application, you'll be able to get his/her FB UID
if($user) {
//get the user's access token
$access_token = $facebook->getAccessToken();
} else {
//see if authorisation already set up in DB
$query = mysql_query("SELECT oauth_token FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND clientID = '$clientID'");
$result = mysql_fetch_row($query);
$access_token = $result[0];
}
if($access_token) {
//check permissions list
$permissions_list = $facebook->api(
'/me/permissions',
'GET',
array(
'access_token' => $access_token
)
);
//check if the permissions we need have been allowed by the user
//if not then redirect them again to facebook's permissions page
$permissions_needed = array('publish_stream', 'read_stream', 'offline_access');
foreach($permissions_needed as $perm) {
if( !isset($permissions_list['data'][0][$perm]) || $permissions_list['data'][0][$perm] != 1 ) {
$login_url_params = array(
'scope' => 'publish_stream,read_stream,offline_access',
'fbconnect' => 1,
'display' => "page",
'next' => 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']
);
$login_url = $facebook->getLoginUrl($login_url_params);
header("Location: {$login_url}");
exit();
}
}
//if the user has allowed all the permissions we need,
//get the information about the pages that he or she managers
$accounts = $facebook->api(
'/me',
'GET',
array(
'access_token' => $access_token
)
);
//add to details database
//find the user by ID
if ($user != ''){
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");
$result = mysql_fetch_array($query);
// If does not exist add to database
if(empty($result)){
$query = mysql_query("INSERT INTO PingSocialMediaUsers (oauth_provider, clientID, oauth_uid, username, oauth_token, oauth_secret) VALUES ('facebook', $clientID, $user, '{$accounts['name']}', '$access_token', '')");
$query = mysql_query("SELECT * FROM PingSocialMediaUsers WHERE id = " . mysql_insert_id());
$result = mysql_fetch_array($query);
} else {
//update the tokens
$query = mysql_query("UPDATE PingSocialMediaUsers SET oauth_token = '$access_token', oauth_secret = '' WHERE oauth_provider = 'facebook' AND oauth_uid = '$user'");
}
//save the information inside the session
$_SESSION['_token'] = $access_token;
$_SESSION['accounts'] = $accounts['data'];
}
$facebookAuth = TRUE;
Facebook pass an expires field when it pass your application the access token and default as per the Facebook is 2hours.
there are other factors why which a access_token can expire and here are the complete details for you
Ankur Pansari
How-To: Handle expired access tokens
Now next we can talk about offline_access which means
It Enables your app to perform authorized requests
on behalf of the user at any time. By default,
most access tokens expire after a short time period to ensure applications
only make requests on behalf of the user when the are actively
using the application. This permission makes the
access token returned by our OAuth endpoint long-lived.
So it all means you have to make sure you always using valid access_token.For details about various permission here is a reference link
Facebook Permissions