I am using spring cloud GCP logging and trace in my GCP cloud run application
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<include resource="org/springframework/cloud/gcp/logging/logback-appender.xml"/>
<root level="INFO">
<appender-ref ref="STACKDRIVER"/>
</root>
</configuration>
After adding this I can see that logs are grouped
Now I have two questions
Can we have the trace ID and and span ID printed in the request log it self.
After adding stack driver, the spring default console pattern is not shown. All the logs are printed in raw format. They do not have thread-name, span id, appName etc.
Can these two be achieved?
Update
Trying to enhance the log
#Component
public class NukTraceIdLoggingEnhancer extends TraceIdLoggingEnhancer {
#Override
public void enhanceLogEntry(LogEntry.Builder builder) {
super.enhanceLogEntry(builder);
LogEntry.Builder newDummyBuilder = builder;
LogEntry logEntry = newDummyBuilder.build();
Payload<?> payload = logEntry.getPayload();
if (logEntry.getPayload() instanceof JsonPayload) {
JsonPayload jsonPayload = (JsonPayload) payload;
String content = (String) ((JsonPayload) payload).getDataAsMap().get("message");
content = "abc" + logEntry.getSpanId() + ", " + logEntry.getTrace() + content;
jsonPayload.getDataAsMap().replace("message", content);
builder.setPayload(jsonPayload);
}
}
#Override
public void enhanceLogEntry(LogEntry.Builder builder, ILoggingEvent e) {
super.enhanceLogEntry(builder, e);
LogEntry.Builder newDummyBuilder = builder;
LogEntry logEntry = newDummyBuilder.build();
Payload<?> payload = logEntry.getPayload();
if (logEntry.getPayload() instanceof JsonPayload) {
JsonPayload jsonPayload = (JsonPayload) payload;
String content = (String) ((JsonPayload) payload).getDataAsMap().get("message");
content = "XYZ" + logEntry.getSpanId() + ", " + logEntry.getTrace() + content;
jsonPayload.getDataAsMap().replace("message", content);
builder.setPayload(jsonPayload);
}
}
}
logback-spring.xml
<configuration>
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml"/>
<property name="STACKDRIVER_LOG_NAME" value="${STACKDRIVER_LOG_NAME:-spring.log}"/>
<property name="STACKDRIVER_LOG_FLUSH_LEVEL" value="${STACKDRIVER_LOG_FLUSH_LEVEL:-WARN}"/>
<appender name="MY_STACKDRIVER" class="com.google.cloud.spring.logging.LoggingAppender">
<log>${STACKDRIVER_LOG_NAME}</log> <!-- Optional : default spring.log -->
<loggingEventEnhancer>abc.configuration.NukTraceIdLoggingEnhancer</loggingEventEnhancer>
<flushLevel>INFO</flushLevel> <!-- Optional : default ERROR -->
</appender>
<root level="INFO">
<appender-ref ref="MY_STACKDRIVER"/>
</root>
</configuration>
I seem to be stuck at developing a custom Key/Value pair provider for Amazon's System Manager Parameter Store (SSM) using NETFramework 4.7.1 that utilizes Microsoft.Configuration.ConfigurationBuilders.
The implementation:
using System;
using System.Collections.Generic;
using Amazon.SimpleSystemsManagement;
using Amazon.SimpleSystemsManagement.Model;
using Microsoft.Configuration.ConfigurationBuilders;
using System.Linq;
using System.Diagnostics;
using System.Collections.Specialized;
using Amazon.Runtime;
using Amazon.Runtime.CredentialManagement;
using System.Configuration;
using System.Threading.Tasks;
namespace AXS.Configurations
{
public class ParameterStoreConfigBuilder : KeyValueConfigBuilder
{
public const string envTag = "Environment";
public const string appNameTag = "AppName";
private IAmazonSimpleSystemsManagement client;
/// <summary>
/// Gets or sets an environment (dev|qa|staging|production)
/// </summary>
public string Environment { get; set; }
/// <summary>
/// Gets or sets a AppName
/// </summary>
public string AppName { get; set; }
public ParameterStoreConfigBuilder(IAmazonSimpleSystemsManagement client,
string appName,
string environment)
{
this.client = client;
Environment = environment.ToLower();
AppName = appName;
}
public ParameterStoreConfigBuilder()
{
client = new AmazonSimpleSystemsManagementClient();
}
public override string Description => "Parameter Store";
public override string Name => "SSM";
protected override void LazyInitialize(string name, NameValueCollection config)
{
Optional = false;
base.LazyInitialize(name, config);
string env = UpdateConfigSettingWithAppSettings(envTag);
if (string.IsNullOrWhiteSpace(env))
throw new ArgumentException($"environment must be specified with the '{envTag}' attribute.");
Environment = env;
string appName = UpdateConfigSettingWithAppSettings(appNameTag);
if (string.IsNullOrWhiteSpace(appName))
throw new ArgumentException($"appName must be specified with the '{appNameTag}' attribute.");
AppName = appName;
client = new AmazonSimpleSystemsManagementClient("","", Amazon.RegionEndpoint.USWest2);
}
public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix)
{
Trace.TraceInformation($"return values prefix {prefix}");
if (client == null)
return null;
var parameters = new List<Parameter>();
string nextToken = null;
do
{
var response = client.GetParametersByPath(new GetParametersByPathRequest { Path = prefix, Recursive = true, WithDecryption = true, NextToken = nextToken });
nextToken = response.NextToken;
parameters.AddRange(response.Parameters);
} while (!string.IsNullOrEmpty(nextToken));
return parameters.Select(p => new
{
Key = p.Name,
p.Value
}).ToDictionary(parameter => parameter.Key, parameter => parameter.Value, StringComparer.OrdinalIgnoreCase);
}
public override string GetValue(string key)
{
return Task.Run(async () => { return await GetValueAsync(key); }).Result;
}
private async Task<string> GetValueAsync(string key)
{
var name = $"/{Environment}/{AppName}/{key.Replace(':', '/')}";
Trace.WriteLine($"get value async:{name}");
if (client == null)
return null;
try
{
Trace.TraceInformation($"fetch key {name}");
var request = new GetParameterRequest
{
Name = name,
WithDecryption = true
};
var response = await client.GetParameterAsync(request);
var parameter = response.Parameter;
var value = parameter.Type == ParameterType.SecureString ? "*****" : parameter.Value;
Trace.TraceInformation($"fetched name={name} value={value}");
return value;
}
catch (Exception e) when (Optional && ((e.InnerException is System.Net.Http.HttpRequestException) || (e.InnerException is UnauthorizedAccessException))) { }
return null;
}
}
}
The problem seems to be that AWS SSM client never gets created.
If I change the code and try to instantiate in the constructor I get a stack overflow exception due to recursion.
Any ideas on how to force to get AmazonSimpleSystemsManagementClient created?
The code uses guidance from https://github.com/aspnet/MicrosoftConfigurationBuilders
The App.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection,
System.Configuration, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"
restartOnExternalChanges="false"
requirePermission="true" />
</configSections>
<configBuilders>
<builders>
<add name="ParameterStore" Environment="development" AppName="myAppNameforParmStore" type="AXS.Configurations.ParameterStoreConfigBuilder, AXS.Configurations" />
<add name="Env" prefix="appsettings_" stripPrefix="true" type="Microsoft.Configuration.ConfigurationBuilders.EnvironmentConfigBuilder, Microsoft.Configuration.ConfigurationBuilders.Environment, Version=2.0.0.0, Culture=neutral" />
</builders>
</configBuilders>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.1" />
</startup>
<appSettings configBuilders="Env,ParameterStore">
<add key="Url" value="URL Value for from paramter Store" />
<add key="Secret" value="Some Secret value decrypted" />
</appSettings>
</configuration>
Thanks
UPDATE
I posted an updated version of the AwsSsmConfigurationBuilder, and a sample ASP.NET Web Forms project that uses it, on my GitHub:
https://github.com/Kirkaiya/AwsSsmConfigBuilderPoC/
Disclaimer: This is a proof-of-concept (POC) for a custom ConfigurationBuilder for ASP.NET 4.7.1 or higher (running on .NET Framework obviously). It's a POC, so it doesn't do anything besides allow you store Configuration AppSettings in AWS Parameter Store (a feature of Simple Systems Manager). So, clearly, don't use this in production without productizing and testing it!
Prerequisites:
Your project must target .NET Framework 4.7.1 or higher
Include NuGet package Microsoft.Configuration.ConfigurationBuilders.Base
Have parameters in AWS SSM Parameter Store that have the same name (not counting the prefix) as parameters in your web.config file, and vice-versa.
Notes
In order to avoid recursively calling a concrete constructor or Initialize, I used a static constructor to instantiate the AmazonSimpleSystemsManagementClient, which is held in a static member.
Web.Config additions
Note: change the assembly/class-name of your builder to match yours, etc.
<configSections>
<section name="configBuilders" type="System.Configuration.ConfigurationBuildersSection, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" restartOnExternalChanges="false" requirePermission="false" />
</configSections>
<configBuilders>
<builders>
<add name="ParameterStore" ssmPrefix="/padnugapp/ApiKeys" type="Microsoft.Configuration.ConfigurationBuilders.AwsSsmConfigBuilder, AspNetWebFormsSample" />
</builders>
</configBuilders>
<appSettings configBuilders="ParameterStore">
<add key="TestKey" value="TestKey Value from web.config" />
<add key="TwitterKey" value="TwitterKey value from web.config" />
</appSettings>
And the AwsSsmConfigBuilder.cs file:
namespace Microsoft.Configuration.ConfigurationBuilders
{
public class AwsSsmConfigBuilder : KeyValueConfigBuilder
{
private string BaseParameterPath = "/padnugapp/ApiKeys";
private static IAmazonSimpleSystemsManagement _client;
static AwsSsmConfigBuilder()
{
_client = new AmazonSimpleSystemsManagementClient();
}
public override void Initialize(string name, NameValueCollection config)
{
base.Initialize(name, config);
if (config["ssmPrefix"] == null)
return;
BaseParameterPath = config["ssmPrefix"];
}
public override ICollection<KeyValuePair<string, string>> GetAllValues(string prefix)
{
if (_client == null)
return null;
var request = new GetParametersByPathRequest
{
Path = $"{BaseParameterPath}/{prefix}",
WithDecryption = true,
};
var response = _client.GetParametersByPathAsync(request).Result;
var result = response.Parameters.ToDictionary(param => param.Name, param => param.Value, StringComparer.OrdinalIgnoreCase);
return result;
}
public override string GetValue(string key)
{
if (_client == null)
return null;
var request = new GetParameterRequest
{
Name = $"{BaseParameterPath}/{key}",
WithDecryption = true,
};
var response = _client.GetParameterAsync(request).Result;
return response.Parameter.Value;
}
}
}
The code I put into a web-forms (.aspx) page that renders the two appSettings items in HTML:
TestKey =
<%=(System.Configuration.ConfigurationManager.AppSettings["TestKey"]) %>
<br />
TwitterKey =
<%=(System.Configuration.ConfigurationManager.AppSettings["TwitterKey"]) %>
I can't stress enough that this is just for a demo I'm doing, and not tested in any way, shape or form except on my laptop ;-)
I am using the default configuration of uCommerce and see that uCommerce nice URLs are not language aware: http://sitename/catalogname/productname/c-XX/p-YY.
What should I do to have language in those URLs like this: http://sitename/en/catalogname/productname/c-XX/p-YY ?
Here is the configuration:
<linkManager defaultProvider="sitecore">
<providers>
<clear />
<add name="sitecore" type="Sitecore.Links.LinkProvider, Sitecore.Kernel" addAspxExtension="false" alwaysIncludeServerUrl="false" encodeNames="true" languageEmbedding="always" languageLocation="filePath" lowercaseUrls="true" shortenUrls="true" useDisplayName="true" />
</providers>
</linkManager>
Here is how I use it:
public WebshopProduct Map(UCommerceProduct uProduct)
{
ProductCatalog catalog = CatalogLibrary.GetCatalog(25);
IUrlService urlService = ObjectFactory.Instance.Resolve<IUrlService>();
...
var url = urlService.GetUrl(catalog, uProduct) // this returns "/catalogname/productname/c-XX/p-YY"
//And I would like to have "/en/catalogname/productname/c-XX/p-YY"
}
Adding language to URL depends on how you are rendered links. If you don't pass specific parameters than Sitecore (and uCommerce as part of Sitecore) uses LinkManager configuration sitecore>linkManager>providers: languageEmbedding adn languageLocation attributes. You should have languageEmbedding="always" and languageLocation="filePath"
P.S.
But, be aware if you using their demo or something based on their demo(e.g. from certification courses): they uses regular ASP.Net MVC(not Sitecore MVC). And links are not rendered via LinkManager and you should put language to URL by youself. Register routed with language code that is embedded to them.
Here is what I have come up with:
public static class TemplateIDs
{
// sitecore/ucommerce item's template id
public static ID UCommerce => new ID("{AABC1CFA-9CDB-4AE5-8257-799D84A8EE23}");
}
public static class ItemExtensions
{
public static bool IsUCommerceItem(this Item item)
{
var items = item.Axes.GetAncestors();
return items.Any(x => x.TemplateID.Equals(TemplateIDs.UCommerce));
}
}
public static string GetItemUrlByLanguage(Sitecore.Globalization.Language language)
{
if (Context.Item.IsUCommerceItem() && SiteContext.Current.CatalogContext.CurrentProduct != null && SiteContext.Current.CatalogContext.CurrentProduct.Guid == Context.Item.ID.Guid)
{
ProductCatalog catalog = CatalogLibrary.GetCatalog(25);
IUrlService urlService = ObjectFactory.Instance.Resolve<IUrlService>();
var url = "/" + language.CultureInfo.TwoLetterISOLanguageName + urlService.GetUrl(catalog, SiteContext.Current.CatalogContext.CurrentProduct);
return url;
}
else
{
//Normal URL creation
using (new LanguageSwitcher(language))
{
var options = new UrlOptions
{
AlwaysIncludeServerUrl = true,
LanguageEmbedding = LanguageEmbedding.Always,
LowercaseUrls = true
};
var url = LinkManager.GetItemUrl(Context.Item, options);
url = StringUtil.EnsurePostfix('/', url).ToLower();
return url;
}
}
}
I want to hide quick info section through code instead of unchecking the check box in Application Options dialog box. Can someone help in this?
The following code does exactly what your looking for.
Add this code below:
namespace Custom.Framework.SC.Extensions.Pipelines
{
using Sitecore.Pipelines.LoggedIn;
using SC = Sitecore;
/// <summary>The default quick info.</summary>
public class DefaultQuickInfo : SC.Pipelines.LoggedIn.LoggedInProcessor
{
/// <summary>The process.</summary>
/// <param name="args">The args.</param>
public override void Process(LoggedInArgs args)
{
const string DefaultToVisible = "false";
SC.Diagnostics.Assert.ArgumentNotNull(args, "args");
SC.Diagnostics.Assert.IsTrue(
SC.Security.Accounts.User.Exists(args.Username),
args.Username);
var user = SC.Security.Accounts.User.FromName(
args.Username,
true);
SC.Diagnostics.Assert.IsNotNull(user, "user");
var sitecoreDomain = SC.SecurityModel.DomainManager.GetDomain(
"sitecore");
SC.Diagnostics.Assert.IsNotNull(sitecoreDomain, "sitecoreDomain");
if (user.Domain != sitecoreDomain
|| user.Name.ToLower().EndsWith("\\" + sitecoreDomain.AnonymousUserName))
{
SC.Diagnostics.Log.Warn(this + " : unexpected security domain or user : " + user.Name, this);
return;
}
var key = "/" + args.Username + "/UserOptions.ContentEditor.ShowQuickInfo";
if (string.IsNullOrEmpty(user.Profile[key]))
{
user.Profile[key] = DefaultToVisible;
user.Profile.Save();
}
}
}
}
Then patch in this configuration change to add the processor to the appropriate place:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
<sitecore>
<processors>
<loggedin>
<processor patch:after="processor[position()=last()]" type="Custom.Framework.SC.Extensions.Pipelines.DefaultQuickInfo, Custom.Framework.SC.Extensions" />
</loggedin>
</processors>
</sitecore>
</configuration>
(The original post is here:https://social.technet.microsoft.com/Forums/sharepoint/en-US/6b02dfe8-5594-4d25-991a-51ac9a0528b7/sharepoint-2013-fba-errorcould-not-retrieve-the-iis-settingsparameter-name-context?forum=sharepointadminprevious)
I am trying to use windows live to login sharepoint 2013. From some posts, I could get windows live token(aouth 2.0) and windows live user profile. It will redirect to my sharepoint site.
I follow some articles to develop my custom login page:
also I defined my membership provider and role provider
public class LiveMembershipProvider : MembershipProvider
{
private MembershipUserCollection employees;
private void generateUsers()
{
//Mock Data
employees = new MembershipUserCollection();
employees.Add(new MembershipUser(this.Name, "Jack Chen", "JackChen", "Jack#Chen.com", "What your Name?", "I am Jack", true, false, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today));
employees.Add(new MembershipUser(this.Name, "Bruce Li", "BruceLi", "BruceLi#Li.com", "How are u?", "How old are u", true, false, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today));
employees.Add(new MembershipUser(this.Name, "Eyes Wang", "EyesWang", "EyesWang#Mintcode.com", "What the hell?", "what the fuck", true, false, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today));
}
public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
if (employees == null) generateUsers();
MembershipUserCollection returnFoundUsers = new MembershipUserCollection();
(employees.Cast<MembershipUser>().
Where(membershipUser => membershipUser.UserName.ToLowerInvariant().Contains(usernameToMatch.ToLowerInvariant())))
.ToList().ForEach(returnFoundUsers.Add);
totalRecords = returnFoundUsers.Count;
return returnFoundUsers;
}
public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
{
if (employees == null) generateUsers();
totalRecords = employees.Count;
return employees;
}
public override MembershipUser GetUser(string username, bool userIsOnline)
{
if (employees == null) generateUsers();
IEnumerable<MembershipUser> usersFound = employees.Cast<MembershipUser>().Where(membershipUser => membershipUser.UserName == username);
return usersFound.FirstOrDefault();
}
public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
{
if (employees == null) generateUsers();
IEnumerable<MembershipUser> usersFound = employees.Cast<MembershipUser>().Where(membershipUser => membershipUser.ProviderUserKey.ToString() == providerUserKey.ToString());
return usersFound.FirstOrDefault();
}
public override string GetUserNameByEmail(string email)
{
if (employees == null) generateUsers();
IEnumerable<MembershipUser> usersFound = employees.Cast<MembershipUser>().Where(membershipUser => membershipUser.Email.ToLowerInvariant() == email.ToLowerInvariant());
MembershipUser user = usersFound.FirstOrDefault();
if (user != null)
return user.UserName;
else
return null;
}
public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
{
if (employees == null) generateUsers();
MembershipUserCollection returnFoundUsers = new MembershipUserCollection();
(employees.Cast<MembershipUser>().
Where(membershipUser => membershipUser.Email.ToLowerInvariant().Contains(emailToMatch.ToLowerInvariant())))
.ToList().ForEach(returnFoundUsers.Add);
totalRecords = returnFoundUsers.Count;
return returnFoundUsers;
}
public override bool ValidateUser(string username, string password)
{
//return true;
if (employees == null) generateUsers();
IEnumerable<MembershipUser> usersFound = employees.Cast<MembershipUser>().Where(membershipUser => membershipUser.UserName == username);
MembershipUser user = usersFound.FirstOrDefault();
if (user != null)
{
if (string.IsNullOrEmpty(password))
{
return false;
}
else
{
return true;
}
}
else
return false;
}
}
public class LiveRoleProvider : RoleProvider
{
public override string ApplicationName { get; set; }
private string[] m_AllRoles = { "Vendor" };
private string[,] m_RolesForUser = new string[,] {
{"Eyes Wang", "Vendor"},
{"Bruce Li","Vendor"},
{"Jack Chen","Vendor"}
};
public override string[] GetAllRoles()
{
return m_AllRoles;
}
public override string[] GetRolesForUser(string username)
{
List<string> roles = new List<string>();
for (int i = 0; i <= m_RolesForUser.GetUpperBound(0); i++)
{
if (m_RolesForUser[i, 0] == username)
{
roles = m_RolesForUser[i, 1].Split(',').ToList<string>();
}
}
return roles.ToArray();
}
public override string[] GetUsersInRole(string rolename)
{
List<string> users = new List<string>();
for (int i = 0; i <= m_RolesForUser.GetUpperBound(0); i++)
{
List<string> userRoles = m_RolesForUser[i, 1].Split(',').ToList<string>();
if (userRoles.Where(userRole => userRole == rolename).Count() > 0)
{
users.Add(m_RolesForUser[i, 0]);
}
}
return users.ToArray();
}
public override bool IsUserInRole(string username, string rolename)
{
List<string> usersForRole = GetUsersInRole(rolename).ToList();
if (usersForRole.Where(userName => userName == username).Count() > 0)
{
return true;
}
else
{
return false;
}
}
public override bool RoleExists(string rolename)
{
bool roleExsists = m_AllRoles.ToList().Where(roleName => roleName == rolename).Count() > 0;
return roleExsists;
}
public override string[] FindUsersInRole(string rolename, string usernameToMatch)
{
List<string> users = GetUsersInRole(rolename).ToList<string>();
List<string> foundUsers = users.Where(userName => userName.ToLowerInvariant().Contains(usernameToMatch.ToLowerInvariant())).ToList<string>();
return foundUsers.ToArray();
}
}
In the Central Application web.config
I add
<roleManager>
<providers>
<add name="LiveRoleProvider" type="SPLiveWebForm.LiveRoleProvider,SPLiveWebForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34a64026791bbfa4" />
</providers>
</roleManager>
<membership>
<providers>
<add name="LiveMembershipProvider" type="SPLiveWebForm.LiveMembershipProvider,SPLiveWebForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34a64026791bbfa4" />
</providers>
</membership>
<PeoplePickerWildcards>
<clear />
<add key="AspNetSqlMembershipProvider" value="%" />
<add key="LiveMembershipProvider" value="%" />
</PeoplePickerWildcards>
In the WA web.config
<membership defaultProvider="i">
<providers>
<add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="LiveMembershipProvider" type="SPLiveWebForm.LiveMembershipProvider,SPLiveWebForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34a64026791bbfa4" />
</providers>
</membership>
<roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
<providers>
<add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="LiveRoleProvider" type="SPLiveWebForm.LiveRoleProvider,SPLiveWebForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34a64026791bbfa4" />
</providers>
</roleManager>
<PeoplePickerWildcards>
<clear />
<add key="AspNetSqlMembershipProvider" value="%" />
<add key="LiveMembershipProvider" value="%" />
</PeoplePickerWildcards>
In the STS web.config
<system.web>
<membership defaultProvider="i">
<providers>
<add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="LiveMembershipProvider" type="SPLiveWebForm.LiveMembershipProvider,SPLiveWebForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34a64026791bbfa4" />
</providers>
</membership>
<roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
<providers>
<add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
<add name="LiveRoleProvider" type="SPLiveWebForm.LiveRoleProvider,SPLiveWebForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=34a64026791bbfa4" />
</providers>
</roleManager>
</system.web>
I could successfully login to share point by using the default login page (http://www.akmii.com/_forms/default.aspx)
But using my customize page (when I get windows live user profile then try to use the follow method to login sharepoint)
private void SPUserLogin(string usrName)
{
string userProviderName = string.Empty;
string roleProviderName = string.Empty;
foreach (MembershipProvider p in Membership.Providers)
{
if (p.GetType().Equals(typeof(LiveMembershipProvider)))
{
userProviderName = p.Name;
break;
}
}
foreach (RoleProvider rp in System.Web.Security.Roles.Providers)
{
if (rp.GetType().Equals(typeof(LiveRoleProvider)))
{
roleProviderName = rp.Name;
break;
}
}
SecurityToken tk = null;
try
{
tk = SPSecurityContext.SecurityTokenForFormsAuthentication(
new Uri(SPContext.Current.Web.Url), userProviderName, roleProviderName,
"Jack Chen", "123", SPFormsAuthenticationOption.PersistentSignInRequest);
}
catch (Exception e)
{
Response.Write(e.Message);
}
if (tk != null)
{
//try setting the authentication cookie
SPFederationAuthenticationModule fam = SPFederationAuthenticationModule.Current;
fam.SetPrincipalAndWriteSessionToken(tk);
//look for the Source query string parameter and use that as the redirection
//string src = Request.QueryString["Source"];
string src = "http://www.akmii.com/_layouts/15/start.aspx#/SitePages/Home.aspx";
if (!string.IsNullOrEmpty(src))
Response.Redirect(src);
}
else
{
}
}
}
There is an exception throwing out in the catch section:
Could not retrieve the IIS Settings.Parameter name: context
The error stack as follows:
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.ReadResponse(Message response)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst, RequestSecurityTokenResponse& rstr)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustChannel.Issue(RequestSecurityToken rst)
at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForContext(Uri context, Boolean bearerToken, SecurityToken onBehalfOf, SecurityToken actAs, SecurityToken delegateTo, SPRequestSecurityTokenProperties properties)
at Microsoft.SharePoint.SPSecurityContext.SecurityTokenForFormsAuthentication(Uri context, String membershipProviderName, String roleProviderName, String username, String password, SPFormsAuthenticationOption options)
at SPLiveWebForm.Layouts.SPLiveWebForm.Login.SPUserLogin(String usrName)
If I use
bool status = SPClaimsUtility.AuthenticateFormsUser(
new Uri(SPContext.Current.Web.Url),
usrName,
"123");
The same exception throw out.
at Microsoft.SharePoint.IdentityModel.SPFormsOriginalIssuerBuilder.GetFormsAuthenticationProviderFromContext(Uri context)
at Microsoft.SharePoint.IdentityModel.SPFormsOriginalIssuerBuilder.ValidateFormsAuthProviderNames(Uri context, String membershipProvider, String roleProvider)
at Microsoft.SharePoint.IdentityModel.SPFormsOriginalIssuerBuilder.SetProviderNames()
at Microsoft.SharePoint.IdentityModel.SPSecurityTokenService.SPRequestInfo.InitializeForForms(SPRequestSecurityToken request)
at Microsoft.SharePoint.IdentityModel.SPSecurityTokenService.GetTokenLifetime(Lifetime requestLifetime)
at Microsoft.IdentityModel.SecurityTokenService.SecurityTokenService.Issue(IClaimsPrincipal principal, RequestSecurityToken request)
at Microsoft.SharePoint.IdentityModel.SPSecurityTokenService.Issue(IClaimsPrincipal principal, RequestSecurityToken request)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.DispatchRequest(DispatchContext dispatchContext)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.ProcessCore(Message requestMessage, WSTrustRequestSerializer requestSerializer, WSTrustResponseSerializer responseSerializer, String requestAction, String responseAction, String trustNamespace)
at Microsoft.IdentityModel.Protocols.WSTrust.WSTrustServiceContract.ProcessTrust13Issue(Message message)
at SyncInvokeProcessTrust13Issue(Object , Object[] , Object[] )
at System.ServiceModel.Dispatcher.SyncMethodInvoker.Invoke(Object instance, Object[] inputs, Object[]& outputs)
at System.ServiceModel.Dispatcher.DispatchOperationRuntime.InvokeBegin(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage5(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.ImmutableDispatchRuntime.ProcessMessage31(MessageRpc& rpc)
at System.ServiceModel.Dispatcher.MessageRpc.Process(Boolean isOperationContextSet)
I spend whole day to dig this issue but failed.
Is there any solution to resolve this?
Many Thanks!
Vincent
I had the same problem.
In my case I had to go to the Central Administartion => System Settings => Configure alternate access mappings.
Click on "Edit Public URLs", select Your app in "Alternate access mappings collection" and then fill up "Internet" textbox.
I am not sure what value is correct, but I filled it with my sharepoint URL with default (80) port.
Hope it help You.