简体   繁体   中英

Adding Claims in the MVC 5 app with Owin and windows authentication

I am developing an mvc 5 web application with authentication being implemented by owin and forms authentication.

It works pretty fine with the claims which it provides out of the box. Now i am trying to use the windows authentication in order to login into the system

public void ConfigureAuth(IAppBuilder app)
{
// Configure the db context and user manager to use a single instance per request
//  app.CreatePerOwinContext(ApplicationDbContext.Create);
//  app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

// Enable the application to use a cookie to store information for the signed in user
// and to use a cookie to temporarily store information about a user logging in with a third         party login provider
// Configure the sign in cookie
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
    AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
    LoginPath = new PathString("/Account/Login"),
    Provider = new CookieAuthenticationProvider
    {
        OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    }
});

app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

// Uncomment the following lines to enable logging in with third party login providers
//app.UseMicrosoftAccountAuthentication(
//    clientId: "",
//    clientSecret: "");

//app.UseTwitterAuthentication(
//   consumerKey: "",
//   consumerSecret: "");

//app.UseFacebookAuthentication(
//   appId: "",
//   appSecret: "");

////  app.UseGoogleAuthentication(
//       clientId: "000-000.apps.googleusercontent.com",
//     clientSecret: "00000000000");
}

I have commented all the providers.

I am trying to push the claims during the sign in process but the user ( window.identity.principal ) is already authenticated which I can check via authenticationmanger.current.user.Isauthenticated .

I am trying to sign in but the claims aren't getting pushed but i can see a list of claims being present in the Claims of the user even thought the sign command is not fired. It's like the owin in windows authentication already knows who is the current user and its name and also claim. But i want some custom one time claims to be pushed into the existing list which i am unable to achieve.

All the existing claims are of the type system claim which makes me doubt whether I can modify the claim.

How can I modify or update or extend the existing claim list?

I tried the revoke method for the claims, it works fine for forms authentication.

   private async Task SignInAsync(ApplicationUser user, bool isPersistent)
    {
        var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);

        // Add more custom claims here if you want. 
        var claims = new Collection<Claim>
        {
            new Claim("Surname",user.ApplicantName),
            new Claim("ApplicantId",user.ApplicantId),
            new Claim("AccessCodeId",user.AccessCodeId),
            new Claim ( "Registered", "YES")
        };

        identity.AddClaims(claims);

        var principal = new ClaimsPrincipal(identity);

        // turn into Principal
        HttpContext.User = principal;

        AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
    }

I know this question is quite old but I also encountered the same just recently but on a Nancyfx Framework. This might help others too.

You just need to get the current identity and add new claims into it. Note that GetRolesForUser is just a custom method. You can also add claim types other than Role.

string[] roles = GetRolesForUser(User.Identity.Name);

var id = ClaimsPrincipal.Current.Identities.First();
foreach (var role in roles)
{
   id.Claims.Add(new Claim(ClaimTypes.Role, role));
}

I found the idea from BrockAllen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM