AngularJS and URL Rewrite to HTTPS - angularjs

So I have ui-router in my application and everything has been working fine.
I was asked to make the account area of the site forced HTTPS so I set up this rule:
I have a link on the main "view" that takes you to the login page and the link looks just like this:
<a class="link-primary" ui-sref="login" ng-switch-default>Sign in</a>
The state rule set up looks like this:
.state('login', {
url: '/account/signin',
params: {
returnState: null,
returnParams: null
},
templateUrl: '/assets/tpl/account/signin.tpl.html',
controller: 'LoginController',
controllerAs: 'controller',
resolve: {
pageTitle: ['PageHead', function (service) {
service.setTitle('Kudos Sports - Login');
}]
}
})
When I click the link I get an error message:
XMLHttpRequest cannot load https://kudos-topspindigital.azurewebsites.net/assets/tpl/account/signin.tpl.html. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://kudos-topspindigital.azurewebsites.net' is therefore not allowed access.
I can type the url (https://kudos-topspindigital.azurewebsites.net/account/signin) and this works without any issues. I can even do it by omitting the https protocol and it will redirect with no issues, so I can only assume there is something wrong with angularJS.
Can someone help me fix my issue?

Try add HTTP header in your server response by:
"Access-Control-Allow-Origin", "*"
This time, use server side script to return HTML instead pure html, for example, in PHP
<?php
header("Access-Control-Allow-Origin: *");

Tbh the best way for me to do this was to set up a rule that pushed everything to HTTPS, not just the account stuff.
<rule name="Redirect .com to www" patternSyntax="Wildcard" stopProcessing="true">
<match url="*" />
<conditions logicalGrouping="MatchAny">
<add input="{HTTP_HOST}" pattern="kudos-sports.co.uk" />
<add input="{HTTP_HOST}" pattern="kudos-sports.com" />
<add input="{HTTP_HOST}" pattern="kudos-sportswear.co.uk" />
<add input="{HTTP_HOST}" pattern="kudos-sportswear.com" />
<add input="{HTTP_HOST}" pattern="www.kudos-sports.co.uk" />
<add input="{HTTP_HOST}" pattern="www.kudos-sportswear.co.uk" />
<add input="{HTTP_HOST}" pattern="www.kudos-sportswear.com" />
<add input="{HTTP_HOST}" pattern="kudos-sports.azurewebsites.net" />
</conditions>
<action type="Redirect" url="https://www.kudos-sports.com{REQUEST_URI}" />
</rule>

Related

OIDC-Connect technical profile only works under a self-asserted validation reference (but need it not to require a self-asserted profile)

I am hoping to create an endpoint that allows me to pass in a password as a query param (for the purpose of issuing a JWT for internal M2M usage between microservices. The password is only aimed at preventing services who should be able to have the M2M rather than being super secure as such etc.
I am stuck however with a bug or feature of b2c where I can call the login-NonInteractive profile but it only works if being called from a self-asserted technical profile via a ValidationTechnicalProfile. See working code below (but has a UI because its self asserted):
<TechnicalProfile Id="SelfAsserted-LocalAccountSignin-Username">
<DisplayName>Local Account Signin</DisplayName>
<Protocol Name="Proprietary" Handler="Web.TPEngine.Providers.SelfAssertedAttributeProvider, Web.TPEngine, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
<Metadata>
<Item Key="ContentDefinitionReferenceId">api.selfasserted</Item>
<Item Key="UserMessageIfClaimsTransformationStringsAreNotEqual">The last names you provided are not the same</Item>
<Item Key="AllowGenerationOfClaimsWithNullValues">true</Item>
</Metadata>
<IncludeInSso>false</IncludeInSso>
<!-- <InputClaims>
<InputClaim ClaimTypeReferenceId="signInName" />
</InputClaims> -->
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="signInName" Required="true" />
<OutputClaim ClaimTypeReferenceId="password" Required="true" />
<OutputClaim ClaimTypeReferenceId="objectId" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" />
</OutputClaims>
<ValidationTechnicalProfiles>
<ValidationTechnicalProfile ReferenceId="login-NonInteractive" />
</ValidationTechnicalProfiles>
<UseTechnicalProfileForSessionManagement ReferenceId="SM-AAD" />
</TechnicalProfile>
When I directly call login-NonInteractive (from an orchestration step; to skip the UI that is shown the a self-asserted step), I get an error indicating that the request it sends is sent as a GET HTTP verb; but it only accepts OPTIONS and POST verbs. It seems like the POST metadata key is being ignored in this case. Below is that metadata key:
<Item Key="HttpBinding">POST</Item>
This works as said above when doing via a ValidationTechnicalProfile but not when direct called via an orchestration step.
My question is:
Is there any work around to get login-NonInteractive to POST as it should (without requiring a self-asserted technical profile)?
If not; how would I go about using REST technical profiles (or an OAuth2 profile) to achieve the same thing? If I understand the ODIC calls that would be made; I can probably work through this myself I think. I read the docs here: https://learn.microsoft.com/en-us/azure/active-directory-b2c/openid-connect-technical-profile and here: https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-protocols-oidc but the last link doesn't feel like it applies; as I am trying to login as a particular user (for the purpose of validating the password mainly). That approach doesn't cover that specifically. I would also prefer to avoid ROPC if possible since its deprecated.
Here is the code for the login-NonInteractive:
<TechnicalProfile Id="login-NonInteractive">
<DisplayName>Local Account SignIn</DisplayName>
<Protocol Name="OpenIdConnect" />
<Metadata>
<Item Key="ProviderName">https://sts.windows.net/</Item>
<Item Key="METADATA">https://login.microsoftonline.com/{tenant}/.well-known/openid-configuration</Item>
<Item Key="authorization_endpoint">https://login.microsoftonline.com/{tenant}/oauth2/token</Item>
<Item Key="response_types">id_token</Item>
<Item Key="response_mode">query</Item>
<Item Key="scope">email openid</Item>
<!-- <Item Key="grant_type">password</Item> -->
<!-- Policy Engine Clients -->
<Item Key="UsePolicyInRedirectUri">false</Item>
<Item Key="HttpBinding">POST</Item>
</Metadata>
<InputClaims>
<InputClaim ClaimTypeReferenceId="signInName" PartnerClaimType="username" Required="true" />
<InputClaim ClaimTypeReferenceId="password" Required="true" />
<InputClaim ClaimTypeReferenceId="grant_type" DefaultValue="password" AlwaysUseDefaultValue="true" />
<InputClaim ClaimTypeReferenceId="scope" DefaultValue="openid" AlwaysUseDefaultValue="true" />
<InputClaim ClaimTypeReferenceId="nca" PartnerClaimType="nca" DefaultValue="1" />
</InputClaims>
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="oid" />
<OutputClaim ClaimTypeReferenceId="tenantId" PartnerClaimType="tid" />
<OutputClaim ClaimTypeReferenceId="givenName" PartnerClaimType="given_name" />
<OutputClaim ClaimTypeReferenceId="surName" PartnerClaimType="family_name" />
<OutputClaim ClaimTypeReferenceId="displayName" PartnerClaimType="name" />
<OutputClaim ClaimTypeReferenceId="userPrincipalName" PartnerClaimType="upn" />
<OutputClaim ClaimTypeReferenceId="authenticationSource" DefaultValue="localAccountAuthentication" />
</OutputClaims>
</TechnicalProfile>
```
I have worked out what these guides (https://learn.microsoft.com/en-us/azure/active-directory-b2c/client-credentials-grant-flow?pivots=b2c-custom-policy) etc are advocating now so am posting my answer here.
My confusion came from:
The client credentials are calling into the policy directly in the guides example. I had wrongly assumed that a JWT was being generically issued and then later passed into the custom policy in a second step (ie with similar url format that is used in the portal when hitting an endpoint directly). This confusion was probably fostered too by the fact my custom policy didn't work in a way that works with client credentials. It worked when calling it via the portal; but didn't when using client credentials with it strangely. To solve this I recommend just having a basic replying party JWT issuer and not much else (the code sample here helps somewhat but isn't in a working state as such https://github.com/azure-ad-b2c/samples/tree/master/policies/client_credentials_flow):
<RelyingParty>
<DefaultUserJourney ReferenceId="ClientJourney" />
<TechnicalProfile Id="PolicyProfile">
<DisplayName>PolicyProfile</DisplayName>
<Protocol Name="OpenIdConnect" />
<OutputClaims>
<OutputClaim ClaimTypeReferenceId="objectId" PartnerClaimType="sub" AlwaysUseDefaultValue="true" DefaultValue="myApp" />
<OutputClaim ClaimTypeReferenceId="issuingChannel" AlwaysUseDefaultValue="true" DefaultValue="myAdditionalProperty" />
</OutputClaims>
<SubjectNamingInfo ClaimType="sub" />
</TechnicalProfile>
</RelyingParty>
Essentially the flow is that the client_secret etc being used on the {policy}/oauth2/v2.0/token in step 3 of the first link where you perform the following action:
curl --location --request POST 'https://<your-tenant>.b2clogin.com/<your-tenant>.onmicrosoft.com/<policy>/oauth2/v2.0/token' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--form 'grant_type="client_credentials"' \
--form 'client_id="<client ID>"' \
--form 'client_secret="<client secret>"' \
--form 'scope="<Your API id uri>/.default"'
is hitting the policy directly (where as through the portal you use endpoints to hit your policy like this: https://{tenantName}.b2clogin.com/{tenantName}.onmicrosoft.com/oauth2/v2.0/authorize which had me thinking that I needed two calls when I only needed the one in the example.

Azure Redirect URI showing directory path

I Created web application using azure authentication. I created app registration with secrets key.
Its working fine while debugging but After publish the project in localhost its won't working. its showing folder dir path only.
My Code
if (Request.IsAuthenticated)
{
Response.Redirect("default.aspx",false);
}
else
{
HttpContext.Current.GetOwinContext().Authentication.Challenge(new
AuthenticationProperties { RedirectUri = "/" }, OpenIdConnectAuthenticationDefaults.AuthenticationType);
}
Web Config
<add key="ida:GraphResourceId" value="https://graph.microsoft.com" />
<add key="ida:GraphUserUrl" value="https://graph.microsoft.com/{0}/me?api-version=2013-11-08" />
<add key="todo:TodoListResourceid" value="api://xxxxxxxxxxx" />
<add key="todo:TodoListBaseAddress" value="http://localhost/Test/" />
<add key="ida:ClientId" value="xxxxxxx" />
<add key="ida:AppKey" value="xxxxxxxxx" />
<add key="ida:Tenant" value="aaaaaaaaaaa" />
<add key="ida:AADInstance" value="https://login.microsoftonline.com/{0}" />
<add key="ida:RedirectUri" value="http://localhost/Test" />
Error Image :

log4net logger logging unexpected levels based on config

I have been trying to understand the config of the log4net library and I think I have it except for some unexpected behavior.
I have a root logger that has a level set to INFO and another logger for a specific class that has level set to ERROR.
What I expected from this was that the class logger would only log at error and ignore the roots level since I had additivity set to false for the class logger. Here is the log4net.config I have at the moment:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="log.txt" />
<appendToFile value="true" />
<rollingStyle value="Size" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="100KB" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
</layout>
</appender>
<logger name="EveStatic.Config.ViewModel" additivity="false">
<level value="error"/>
<appender-ref ref="ConsoleAppender"/>
<appender-ref ref="RollingFileAppender"/>
</logger>
<root>
<level value="debug" />
<appender-ref ref="ConsoleAppender" />
<appender-ref ref="RollingFileAppender" />
</root>
</log4net>
</configuration>
In my AssemblyInfo.cs:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]
And in the class that loads the configuration:
log4net.Config.XmlConfigurator.Configure(new FileInfo("log4net.config"));
These two seem redundant but the configuration wont load unless I have the code part. Everything here is in a class library being used by another project.
Is this behavior expected and I don't understand the configuration and level overrides or am I forgetting something?
EDIT:
Here is how I instantiate and call the ILog. The the full class name is the name of the logger in the config plus the ConfiInfoViewModel:
private static readonly ILog LOG = LogManager.GetLogger(typeof(ConfigInfoViewModel));
...
LOG.Debug("Something buggy");
Also note that when testing the logging levels I had a log statement for each level in a series.
Your problem lays here
LogManager.GetLogger(typeof(ConfigInfoViewModel));
Internally this get resolved to
LogManager.GetLogger(typeof(ConfigInfoViewModel).FullName);
Now log4net is looking for a Logger named "EveStatic.Config.ConfigInfoViewModel" (result of typeof(ConfigInfoViewModel).FullName)
Because no Logger with that name is specified a new one with your default settings is used.
Also note that level specify a threshold, not a single level.
Example: level=warn means log warn an all levels above (error and fatal)

How to get google adwords reports in salesforce?

Hi I am developing application in salesforce for accessing the google adwords reports data for e.g. ADGROUP_PERFORMANCE_REPORT. I am sending http post request to https://adwords.google.com/api/adwords/reportdownload/v201302, and I am using apex(java like language in salesforce) below is my request.
Http h = new Http();
HttpRequest req = new HttpRequest();
GoogleAuthorization auth=new GoogleAuthorization();
req.setHeader('Authorization', 'GoogleLogin ' + auth.token);
req.setHeader('UserAgent', 'XXXXX');
req.setHeader('developerToken','XXXXXXXX');
req.setHeader('clientCustomerId','XXXXXXXX');
req.setEndPoint('https://adwords.google.com/api/adwords/reportdownload/v201302');
req.setHeader('Content-Type', 'application/x-www-form-urlencoded');
req.setMethod('POST');
string xml='<reportDefinition xmlns="https://adwords.google.com/api/adwords/cm/v201302">'+
'<selector>'+
'<fields>CampaignId</fields>'+
'<fields>Id</fields>'+
'<fields>Impressions</fields>'+
'<fields>Clicks</fields>'+
'<fields>Cost</fields>'+
'<predicates>'+
'<field>Status</field>'+
'<operator>IN</operator>'+
'<values>ENABLED</values>'+
'<values>PAUSED</values>'+
'</predicates>'+
'</selector>'+
'<reportName>Custom Adgroup Performance Report</reportName>'+
'<reportType>ADGROUP_PERFORMANCE_REPORT</reportType>'+
'<dateRangeType>LAST_7_DAYS</dateRangeType>'+
'<downloadFormat>XML</downloadFormat>'+
'</reportDefinition>';
req.setBody('__rdxml='+EncodingUtil.urlEncode(xml, 'UTF-8'));
HttpResponse res=h.send(req);
After requesting i am getting the AuthenticationError System.HttpResponse[Status=Bad Request, StatusCode=400].
<?xml version="1.0" encoding="UTF-8" standalone="yes"?><reportDownloadError><ApiError><type>AuthenticationError.USER_ID_INVALID</type><trigger><null></trigger><fieldPath></fieldPath></ApiError></reportDownloadError>
However my loginid and password is correct. What i am doing wrong can anybody please help!
Check your app's configuration.
You must have there something like this :
<AdWordsApi>
<add key="MaskCredentials" value="true" />
<add key="EnableGzipCompression" value="true" />
<add key="ProxyServer" value="" />
<add key="ProxyUser" value="" />
<add key="ProxyPassword" value="" />
<add key="ProxyDomain" value="" />
<add key="UserAgent" value="*******" />
<add key="DeveloperToken" value="*******" />
<add key="ClientCustomerId" value="*******" />
<add key="SkipReportHeader" value="false" />
<add key="SkipReportSummary" value="false" />
<add key="OAuth2ClientId" value="*******" />
<add key="OAuth2ClientSecret" value="*******" />
<add key="OAuth2Mode" value="APPLICATION" />
<add key="OAuth2RefreshToken" value="1/*******" />
</AdWordsApi>
fill all required values *****.

After successful LDAP authentication takes to login

I am new spring-security I did spring authentication with ActiveDirectory, It was working after adding
<beans:bean id="myauthenticationrpovider" class="com.holcim.acl.rm.security.MyAuthoritySupplementingProvider">
<beans:constructor-arg ref="ldapActiveDirectoryAuthProvider" />
and bean code as follows
public class MyAuthoritySupplementingProvider implements AuthenticationProvider {
private AuthenticationProvider delegate;
public MyAuthoritySupplementingProvider(AuthenticationProvider delegate) {
this.delegate = delegate;
}
public Authentication authenticate(Authentication authentication) {
final Authentication a = delegate.authenticate(authentication);
//get first username and full User Name from a i.e Authentication.
Object auth = a.getPrincipal();
String username;
String userFullName;
if(auth instanceof LdapUserDetailsImpl){
LdapUserDetailsImpl userDetails = (LdapUserDetailsImpl) auth;
String[] dn = userDetails.getDn().split(",");
String[] temp = dn[0].split("=");
userFullName = temp[1];
username = ((LdapUserDetailsImpl) auth).getUsername();
logger.debug("AD Authentication done ");
logger.debug(userDetails.getDn());
logger.debug("User Full Name " + temp[1]);
logger.debug("UserName is :: "+ username);
}
// Load additional authorities and create an Authentication object
//final List<GrantedAuthority> authorities = loadRolesFromDatabaseHere();
List<AclAuthority> authorities = new ArrayList<AclAuthority>();
authorities.add(AclAuthority.ROLE_ADMIN);
return new AbstractAuthenticationToken(authorities) {
public Object getCredentials() {
throw new UnsupportedOperationException();
}
public Object getPrincipal() {
return a.getPrincipal();
}
};
}
#Override
public boolean supports(Class<?> authentication) {
return delegate.supports(authentication);
}
}
application-security.xml as follows
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd">
<!-- HTTP security configurations -->
<http auto-config="true" use-expressions="true">
<form-login login-processing-url="/static/j_spring_security_check" login-page="/login" authentication-failure-url="/login?login_error=t" />
<logout logout-url="/static/j_spring_security_logout" />
<!-- Configure these elements to secure URIs in your application -->
<intercept-url pattern="/choices/**" access="hasRole('ROLE_ADMIN')" />
<intercept-url pattern="/member/**" access="isAuthenticated()" />
<intercept-url pattern="/resources/**" access="permitAll" />
<intercept-url pattern="/static/**" access="permitAll" />
<intercept-url pattern="/login/**" access="permitAll" />
<intercept-url pattern="/**" access="isAuthenticated()" />
</http>
<!-- Active directory authentication added by Kamlesh A. -->
<!-- LDAP server details -->
<authentication-manager>
<authentication-provider ref="myauthenticationrpovider" />
</authentication-manager>
<beans:bean id="ldapActiveDirectoryAuthProvider" class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
<beans:constructor-arg value="in.mycompany.net" />
<beans:constructor-arg value="ldap://XXX.XXX.XXX.XXX:PPP" />
<!--<beans:property name="authoritiesMapper" ref="grantedAuthoritiesMapper" />-->
<beans:property name="useAuthenticationRequestCredentials" value="true" />
<beans:property name="convertSubErrorCodesToExceptions" value="true" />
</beans:bean>
<beans:bean id="myauthenticationrpovider" class="com.holcim.acl.rm.security.MyAuthoritySupplementingProvider">
<beans:constructor-arg ref="ldapActiveDirectoryAuthProvider" />
</beans:bean>
</beans:beans>
I have gone through so questions
Spring Security redirect to previous page after successful login
as well as
Unexpected redirect to login page after successful login
after successfull login it takes to
http://localhost:8080/static/j_spring_security_check
But if I try to open anyother url it again take to login

Resources