Get email administrators using wss 3.0 - visual-studio-2010

How could obtain all e-mail from site collection's administrators using wss 3.0?

Try:
private string[] GetEmails(SPWeb web)
{
List<string> emails = new List<string>();
Guid siteID = web.Site.ID;
Guid webID = web.ID;
using (SPSite site = new SPSite(siteID, SPUserToken.SystemAccount))
{
using (SPWeb web1 = site.OpenWeb(webID))
{
SPUserCollection admins = web1.SiteAdministrators;
foreach (SPUser admin in admins)
{
emails.Add(admin.Email);
}
}
}
return emails.ToArray();
}
Note that SiteAdministrators requires that the context user is a site collection auditor.

Related

How to automatically retrieve roles from ASP.NET Core identity?

I'm moving my steps to OpenIDDict and I made my application based on Velusia example.
Everything works fine but I have a question: My access token doesn't include roles.
There's a way to automate the retrieving of .NET Core identity user roles and append them to the User property as Claim before accessing the action in my controller?
The purpose of all is being able to use (for example)
User.IsInRole("MyRole");
Thanks to everyone!
Reading this post gets me in the right direction: Is there a way to dynamically load claims in OpenIddict?
public class MyClaimTransformation : IClaimsTransformation
{
private readonly UserManager<UserInfo> _userManager;
public MyClaimTransformation(UserManager<UserInfo> userManager)
{
_userManager = userManager;
}
public async Task<ClaimsPrincipal> TransformAsync(ClaimsPrincipal principal)
{
ClaimsIdentity claimsIdentity = new ClaimsIdentity();
//claimsIdentity.RoleClaimType = OpenIddict.Abstractions.OpenIddictConstants.Claims.Role;
//claimsIdentity.NameClaimType = OpenIddict.Abstractions.OpenIddictConstants.Claims.Name;
var claimType = ClaimTypes.Role;
if (principal.Identity != null && principal.Identity.IsAuthenticated)
{
//Do I already have roles in the claim?
var roleClaimsAvailable = principal.Claims.Any(x => x.Type == claimType);
if (!roleClaimsAvailable)
{
//Roles not found, adding:
var userProfile = await _userManager.GetUserAsync(principal);
if (userProfile != null)
{
var roles = await _userManager.GetRolesAsync(userProfile);
foreach (var role in roles)
{
claimsIdentity.AddClaim(new Claim(claimType, role));
}
principal.AddIdentity(claimsIdentity);
}
}
}
return principal;
}
}
Than we need to register in the Startup.cs as a service:
//Adding roles on access token incoming
builder.Services.AddTransient<IClaimsTransformation, MyClaimTransformation>();

Why Cant List Users or Groups with .NET Google Admin SDK Client Library

I am trying to call the AdminService API to manage my domain's groups such adding new group members, create new groups etc. , but I'm stuck with the request to get all the users' of my domain. Here is the code:
public static class MembersSample
{
static void Main(string[] args)
{
String serviceAccountEmail = "*****#*****.iam.gserviceaccount.com";
var certificate = new X509Certificate2(#"pathofthefile.p12", "secret", X509KeyStorageFlags.Exportable);
ServiceAccountCredential credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(serviceAccountEmail)
{
Scopes = new[] {
DirectoryService.Scope.AdminDirectoryUser,
DirectoryService.Scope.AdminDirectoryGroup,
DirectoryService.Scope.AdminDirectoryDomain,
DirectoryService.Scope.AdminDirectoryGroupMember },
User = "domainmanageremail"
}.FromCertificate(certificate));
var dirservice = new DirectoryService(new Google.Apis.Services.BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = "my application name",
});
var listReq = dirservice.Users.List();
listReq.Domain = "my domain address";
Users allUsers = listReq.Execute();
int counter = 0;
foreach (User myUser in allUsers.UsersValue)
{
Console.WriteLine("*" + myUser.PrimaryEmail);
counter++;
}
Console.WriteLine(counter);
Console.ReadKey();
}
I am getting this error ;
Unhandled Exception: Google.Apis.Auth.OAuth2.Responses.TokenResponseException: Error:"unauthorized_client", Description:"Client is unauthorized to retrieve access tokens using this method.", Uri:""
My service account role is Service Account User, and my role is Service Account Admin in this project. Also, I did authorization part for the service account with the DirectoryService.Scope.AdminDirectoryUser scope (Domain Wide Delegation).
-Is this scope is wrong or do I need additional one to manage groups and members?
Thanks for any help!

How to allow specific roles to access API using identityserver3.accesstokenvalidation

I have an Identityserver4 that is providing access tokens to clients.
On my API, I want to be sure that client is allowed to access specific scope and that User belongs to a specific role before I give this user access to API.
To do that I am using Identityserver3.accesstokenvalidation package.
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = "Authority",
RequiredScopes = new[] { "MyScope" },
});
This is blocking users that do not have access token from accessing my API, also it is checking if the provided scope is "MyScope".
My question is how do I also check that user has a specific role before allowing access to API.
You could put attribute [Authorize(Roles = "Admin")] for specific controller. If you need more advanced logic with claims you need to specify your own attribute e.g. AuthorizePermissionAttribute and use it with controller [AuthorizePermission("Preview")]:
public class AuthorizePermissionAttribute : AuthorizeAttribute
{
private readonly string grantedPermission;
public AuthorizePermissionAttribute(string permission)
{
this.grantedPermission = permission ?? throw new ArgumentNullException(nameof(permission));
}
protected override bool IsAuthorized(HttpActionContext actionContext)
{
var claims = actionContext.ControllerContext.RequestContext.Principal as ClaimsPrincipal;
var permission = claims?.FindFirst(this.grantedPermission);
return permission != null && Convert.ToBoolean(permission.Value);
}
protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
{
var response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Forbidden, "insufficient_permissions");
actionContext.Response = response;
}
}
Also you need to put in Startup.cs:
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseIdentityServerBearerTokenAuthentication(new IdentityServerBearerTokenAuthenticationOptions
{
Authority = ConfigurationManager.AppSettings["IdentityProviderApi"],
PreserveAccessToken = true
});
Without JwtSecurityTokenHandler.InboundClaimTypeMap it will return always Unauthorized status code.

How to create roles and add users to roles in ASP.NET MVC Web API

I have a .NET Web API project that users the individual accounts. I can register users fine using the standard template AccountController. However, I now want to set up roles and add users to roles depending on the type of user.
There are no roles automatically set up in the DB. How do I set up the roles and how do I add users to the roles?
The only information I can find on this is based on the old ASP.NET Membership, so it fails on the fact that the stored procedures are not set up for it.
Have scoured forums and tutorials on MSDN and can't seem to find an example for Web API.
You can add roles using the RoleManager...
using (var context = new ApplicationDbContext())
{
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
await roleManager.CreateAsync(new IdentityRole { Name = "Administrator" });
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser { UserName = "admin" };
await userManager.CreateAsync(user);
await userManager.AddToRoleAsync(user.Id, "Administrator");
}
You're right that documentation is a bit light right now. But I find that once you've worked with the RoleManager and the UserManager a bit, the API's are pretty discoverable (but perhaps not always intuitive and sometimes you have to run queries directly against the store or even the db context).
It took me awhile to figure out but I finally got it. Anthony please excuse me but going to repost a lot of your code so that dumb developers like me can understand.
In the latest WebAPI2 (Visual Studio 2013 Update 2) the registration method will look like so:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
What you want to do is replace it with this:
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(RegisterBindingModel model)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
IdentityResult result;
using (var context = new ApplicationDbContext())
{
var roleStore = new RoleStore<IdentityRole>(context);
var roleManager = new RoleManager<IdentityRole>(roleStore);
await roleManager.CreateAsync(new IdentityRole() { Name = "Admin" });
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new UserManager<ApplicationUser>(userStore);
var user = new ApplicationUser() { UserName = model.Email, Email = model.Email };
result = await UserManager.CreateAsync(user, model.Password);
await userManager.AddToRoleAsync(user.Id, "Admin");
}
if (!result.Succeeded)
{
return GetErrorResult(result);
}
return Ok();
}
Now when you post it should correctly work, but you may run into a further problem. After I did this my response complained about the DB.
The model backing the <Database> context has changed since the database was created
To fix this error I had to go into the Package Manager Console and enable Migrations.
Enable-Migrations –EnableAutomaticMigrations
Then:
Add Migration
Finally:
Update-Database
A good post on enabling migrations here:
http://msdn.microsoft.com/en-us/data/jj554735.aspx

How to know the download link of a windows phone 8 application

I'm developing windows phone 8 application. In which I have to share the application's download link on Facebook and Twitter.
Before publishing the application on to the windows phone store, How could I know the download link of the application.
Because we have to implement the share functionality before publishing the application.
I'm looking forward for your responses.
Thanks & Regards,
Suresh
Basically your application download link format is as follow :
http://windowsphone.com/s?appid=<ApplicationId>
with <ApplicationId> is value of ProductID attribute of App element in WMAppManifest.xml file. That ProductID in WMAppManifest.xml will be overridden when you submit the Apps to Marketplace, so avoid hardcoding it. This post demonstrates how to get <ApplicationId> from manifest file as well as how to share it using Microsoft.Phone.Tasks.ShareLinkTask.
UPDATE :
To summarize, create a helper class to read ApplicationID from WMAppManifest.xml file :
public class DeepLinkHelper
{
private const string AppManifestName = "WMAppManifest.xml";
private const string AppNodeName = "App";
private const string AppProductIDAttributeName = "ProductID";
public static string BuildApplicationDeepLink()
{
var applicationId = Guid.Parse(GetManifestAttributeValue(AppProductIDAttributeName));
return BuildApplicationDeepLink(applicationId.ToString());
}
public static string BuildApplicationDeepLink(string applicationId)
{
return #"http://windowsphone.com/s?appid=" + applicationId;
}
public static string GetManifestAttributeValue(string attributeName)
{
var xmlReaderSettings = new XmlReaderSettings
{
XmlResolver = new XmlXapResolver()
};
using (var xmlReader = XmlReader.Create(AppManifestName, xmlReaderSettings))
{
xmlReader.ReadToDescendant(AppNodeName);
if (!xmlReader.IsStartElement())
{
throw new FormatException(AppManifestName + " is missing " + AppNodeName);
}
return xmlReader.GetAttribute(attributeName);
}
}
}
Then you can get/share download link this way :
new Microsoft.Phone.Tasks.ShareLinkTask()
{
Title = "My Application Deep Link",
Message = "My Application Deep Link",
LinkUri = new Uri(DeepLinkHelper.BuildApplicationDeepLink())
}.Show();
Credit to Pedro Lamas for all above codes.

Resources