本文整理汇总了C#中UserManager.GetClaimsAsync方法的典型用法代码示例。如果您正苦于以下问题:C# UserManager.GetClaimsAsync方法的具体用法?C# UserManager.GetClaimsAsync怎么用?C# UserManager.GetClaimsAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类UserManager
的用法示例。
在下文中一共展示了UserManager.GetClaimsAsync方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Index
public async Task<ActionResult> Index()
{
if (this.User.Identity.IsAuthenticated)
{
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());
IQueryable<Game> games = from membership in db.GameMemberships
where membership.ApplicationUserID == appUser.Id
join game in db.Games on membership.GameID equals game.ID
select game;
var adminRole = await db.Roles.FirstOrDefaultAsync(role => role.Name == "Admin");
this.ViewBag.Games = await games.ToListAsync();
this.ViewBag.Claims = await manager.GetClaimsAsync(appUser.Id);
this.ViewBag.Roles = await manager.GetRolesAsync(appUser.Id);
}
return View();
}
示例2: GetUserClaimTest
public async Task GetUserClaimTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var user = new IdentityUser("u1");
var result = await manager.CreateAsync(user);
UnitTestHelper.IsSuccess(result);
Assert.NotNull(user);
var claims = new[]
{
new Claim("c1", "v1"),
new Claim("c2", "v2"),
new Claim("c3", "v3")
};
foreach (Claim c in claims)
{
UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
}
var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
Assert.Equal(3, userClaims.Count);
foreach (Claim c in claims)
{
Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
}
}
示例3: CheckUserType
private async static Task<bool> CheckUserType(UserManager<ApplicationUser> userManager, ApplicationUser user, params string [] types)
{
var claims = await userManager.GetClaimsAsync(user);
if (claims.Count > 0)
{
var claimValue = claims.FirstOrDefault(c => c.Type.Equals("UserType")).Value;
foreach (string type in types)
{
if (claimValue.Equals(type))
{
return true;
}
}
}
return false;
}
示例4: DupeUserClaimTest
public async Task DupeUserClaimTest()
{
var db = UnitTestHelper.CreateDefaultDb();
var manager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(db));
var user = new IdentityUser("u1");
var result = await manager.CreateAsync(user);
Assert.NotNull(user);
var claims = new[]
{
new Claim("c1", "v1"),
new Claim("c2", "v2"),
new Claim("c3", "v3")
};
foreach (Claim c in claims)
{
// Add dupes
UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
UnitTestHelper.IsSuccess(await manager.AddClaimAsync(user.Id, c));
}
var userClaims = new List<Claim>(await manager.GetClaimsAsync(user.Id));
Assert.Equal(6, userClaims.Count);
var currentExpected = 6;
foreach (Claim c in claims)
{
Assert.True(userClaims.Exists(u => u.Type == c.Type && u.Value == c.Value));
UnitTestHelper.IsSuccess(await manager.RemoveClaimAsync(user.Id, c));
var cs = await manager.GetClaimsAsync(user.Id);
currentExpected -= 2;
Assert.Equal(currentExpected, cs.Count());
Assert.Equal(currentExpected, db.Set<IdentityUserClaim>().Count());
}
}
示例5: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataInitializer sampleData, UserManager<ApplicationUser> userManager)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// For more details on creating database during deployment see http://go.microsoft.com/fwlink/?LinkID=615859
try
{
using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
.CreateScope())
{
serviceScope.ServiceProvider.GetService<ApplicationDbContext>()
.Database.Migrate();
}
}
catch { }
}
app.UseIISPlatformHandler(options => options.AuthenticationDescriptions.Clear());
app.UseStaticFiles();
app.UseIdentity();
// Refactor this into a seperate class
// Remove hard coding of the password in the installDevices routine!
app.UseBasicAuthentication(o =>
{
o.Realm = $"j64 Alarm";
o.Events = new BasicAuthenticationEvents
{
OnSignIn = c =>
{
var x = userManager.FindByNameAsync(c.UserName);
x.Wait();
if (x.Result != null)
{
var y = userManager.CheckPasswordAsync(x.Result, c.Password);
y.Wait();
if (y.Result == true)
{
var z = userManager.GetClaimsAsync(x.Result);
z.Wait();
var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme);
c.Principal = new ClaimsPrincipal(identity);
}
}
return Task.FromResult(true);
}
};
});
// To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Seed some default entries into the database
var task = sampleData.CreateMasterUser();
}
示例6: StoreFacebookInfo
public async Task StoreFacebookInfo(ApplicationUser user)
{
var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
var claimsforUser = await userManager.GetClaimsAsync(user.Id);
var access_token = claimsforUser.FirstOrDefault(x => x.Type == "FacebookAccessToken").Value;
var fb = new FacebookClient(access_token);
dynamic myInfo = fb.Get("/me");
var curFbId = myInfo.id;
dynamic myFriends = fb.Get("/me/friends");
dynamic albums = fb.Get("/me/albums");
//Retrieve Facebook Friends
bool exists = db.FbInfoes.Any(row => row.UserId == user.Id);
if (exists != true)
{
var profileInfo = new FbInfo();
if (myFriends.data != null)
{
foreach (var item in myFriends.data)
{
var f = JsonConvert.DeserializeObject<friends>(item.ToString());
profileInfo.friendsList.Add(f);
}
}
if(albums.data !=null)
{
foreach (var item in albums.data)
{
albums c = new albums();
var f = JsonConvert.DeserializeObject<friends>(item.ToString());
c.friend_id = f.friend_id;
c.id = f.id;
c.name = f.name;
profileInfo.albumsList.Add(c);
}
}
//Retrieve Facebook Mutual Friends
dynamic myMutualFriends = fb.Get(curFbId + "?fields=context.fields(mutual_friends)");
if (myMutualFriends.context.mutual_friends.data != null)
{
foreach (var item in myMutualFriends.context.mutual_friends.data)
{
var f = JsonConvert.DeserializeObject<mutualFriends>(item.ToString());
profileInfo.mutualFriendsList.Add(f);
}
}
//Save all information retrieved from FB into a db
profileInfo.fbId = myInfo.id;
profileInfo.email = myInfo.email;
profileInfo.name = myInfo.name;
profileInfo.firstName = myInfo.first_name;
profileInfo.lastName = myInfo.last_name;
profileInfo.link = myInfo.link;
profileInfo.gender = myInfo.gender;
profileInfo.imageURL = "https://graph.facebook.com/" + myInfo.id + "/picture?type=large";
profileInfo.locale = myInfo.locale;
profileInfo.aboutMe = myInfo.bio;
profileInfo.birthday = myInfo.birthday;
// Need to get the year of the school from the educationList
if (myInfo.education != null)
{
foreach (var item in myInfo.education)
{
var f = JsonConvert.DeserializeObject<education>(item.school.ToString());
var x = JsonConvert.DeserializeObject<education>(item.year.ToString());
f.year = x.name;
profileInfo.educationList.Add(f);
}
}
if (myInfo.work != null)
{
foreach (var item in myInfo.work)
{
var f = JsonConvert.DeserializeObject<workHistory>(item.employer.ToString());
profileInfo.workHistoryList.Add(f);
}
}
profileInfo.UserId = user.Id;
db.FbInfoes.Add(profileInfo);
db.SaveChanges();
}
}
示例7: SyncMembershipsAndClaims
public async Task<int> SyncMembershipsAndClaims([FromBody]Fixit fixit)
{
var userName = fixit.UserName;
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
var query = db.GameMemberships.Include(mem => mem.Game).Include(mem => mem.ApplicationUser);
if (!string.IsNullOrEmpty(userName) && !userName.Equals("$all", StringComparison.InvariantCultureIgnoreCase))
{
query = query.Where(mem => mem.ApplicationUser.DisplayName == userName);
}
var memberships = await query.ToListAsync();
int membershipsFixed = 0;
foreach (var membershipGroup in memberships.GroupBy(m => m.ApplicationUser))
{
var user = membershipGroup.Key;
var claims = await manager.GetClaimsAsync(user.Id);
foreach (var membership in membershipGroup)
{
bool wasFixed = false;
if (!claims.Where(c => c.Type == "GameMembership").Any(c => c.Value == membership.GameID.ToString()))
{
var result = await manager.AddClaimAsync(user.Id, new Claim("GameMembership", membership.GameID.ToString()));
if (!result.Succeeded)
{
Trace.WriteLine(string.Format("Error creating GameMembership claim for user {0} for game {1}: errors {2}", user.Id, membership.GameID,
string.Join(", ", result.Errors)));
}
else
{
wasFixed = true;
}
}
if (membership.Roles.Contains("Owner"))
{
if (!claims.Where(c => c.Type == "GameOwnership").Any(c => c.Value == membership.GameID.ToString()))
{
var result = await manager.AddClaimAsync(user.Id, new Claim("GameOwnership", membership.GameID.ToString()));
if (!result.Succeeded)
{
Trace.WriteLine(string.Format("Error creating GameOwnership claim for user {0} for game {1}: errors {2}", user.Id, membership.GameID,
string.Join(", ", result.Errors)));
}
else
{
wasFixed = true;
}
}
}
if (membership.Roles.Contains("Gamemaster"))
{
if (!claims.Where(c => c.Type == "GameMaster").Any(c => c.Value == membership.GameID.ToString()))
{
var result = await manager.AddClaimAsync(user.Id, new Claim("GameMaster", membership.GameID.ToString()));
if (!result.Succeeded)
{
Trace.WriteLine(string.Format("Error creating GameMaster claim for user {0} for game {1}: errors {2}", user.Id, membership.GameID,
string.Join(", ", result.Errors)));
}
else
{
wasFixed = true;
}
}
}
if (wasFixed)
{
membershipsFixed++;
}
}
}
return membershipsFixed;
}
示例8: Delete
public async Task Delete(int? gameID)
{
if (gameID == null)
{
throw new ArgumentNullException("gameID");
}
var id = gameID.Value;
var game = await db.Games.FindAsync(id);
if (game == null)
{
throw new ArgumentException("Could not find game with id " + id);
}
var userID = this.User.Identity.GetUserId();
var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(this.db));
var appUser = await manager.FindByIdAsync(this.User.Identity.GetUserId());
if (!DoesUserOwnGame(appUser, id))
{
throw new ArgumentException("Could not delete game");
}
var memberships = await db.GameMemberships.Where(m => m.GameID == id).Include(m => m.ApplicationUser).ToListAsync();
var claims = await Task.WhenAll(memberships.Select(m => m.ApplicationUser).Select(user =>
manager.GetClaimsAsync(user.Id).ContinueWith(t => new { Claims = t.Result, User = user })));
var strId = id.ToString();
var removeTasks = from tuple in claims
from claim in tuple.Claims
where (claim.Type == "GameOwnership" || claim.Type == "GameOwnership" || claim.Type == "GameMaster") && claim.Value == strId
select manager.RemoveClaimAsync(tuple.User.Id, claim);
await Task.WhenAll(removeTasks);
db.GameMemberships.RemoveRange(memberships);
db.Games.Remove(game);
await db.SaveChangesAsync();
}
示例9: Configure
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, UserManager<ApplicationUser> userManager, ApplicationDbContext ctx)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
app.UseBrowserLink();
}
else
{
app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();
app.UseIdentity();
// Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715
// Refactor this into a seperate class
// Remove hard coding of the password in the installDevices routine!
app.UseBasicAuthentication(o =>
{
o.Realm = $"j64 Alarm";
o.Events = new BasicAuthenticationEvents
{
OnSignIn = c =>
{
var x = userManager.FindByNameAsync(c.UserName);
x.Wait();
if (x.Result != null)
{
var y = userManager.CheckPasswordAsync(x.Result, c.Password);
y.Wait();
if (y.Result == true)
{
var z = userManager.GetClaimsAsync(x.Result);
z.Wait();
var identity = new ClaimsIdentity(z.Result, c.Options.AuthenticationScheme);
c.Principal = new ClaimsPrincipal(identity);
}
}
return Task.FromResult(true);
}
};
});
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
// Seed some default entries into the database
var task = new Data.UserDataInitializer(ctx, userManager).CreateMasterUser();
}