Capturing a log event so that I can cache other user information

I have created a web application. When I built it, I marked "Organizational accounts"

This works well - I am logged in with my Office 365 account, and it User.Identity.Namecontains an email address

This app is a front-end replacement for the old ASP Classic app. The application has an existing security table that I need to use.

I want to use the email address to search for entries in this table to get

  • The internal database key for the user (so I can use it in database calls)

  • Security level (authorization) for the user

I want to see this as soon as I go through authentication and save these two values ​​until Session, to refer to later

I have an existing method that does all this searching and caching. I really got it working by calling it from a view _LoginPartial.cshtml, but it is obviously wrong to run this view from a view

Here is the code for searching and caching user information. So far it is in AccountController.cs, but it should not be

private Boolean GetAdditionalUserInfo()
{
    // if authentication info is saved, don't go find it
    if (Session["UID"] != null) return true;

    // get the db employee id from the database and save it to the session
    var r = (
            from e in db.Employees
            where e.Email == User.Identity.Name
            select new
            {
                e.Emp_ID,
                e.Group_ID
            }
            ).SingleOrDefault();

    if ((r == null) || (r.Group_ID == (int)Role.Inactive))
    {
        // couldn't find record or inactive
        return false;
    }

    // Update last login datetime
    Employee ell = db.Employees.Find(r.Emp_ID);
    ell.LastLogin = DateTime.Now;
    db.SaveChangesAsync();

    // Save user details to the session
    Session["UID"] = r.Emp_ID;
    // TBD: Investigate "CLAIMS" - this should probably be a claim
    Session["Role"] = r.Group_ID;

    return true;

}

, User.Identity.Name , , ( , ), , - OnAuthentication, , OnAuthenticated. :

https://msdn.microsoft.com/en-us/library/system.web.mvc.controller.onauthentication(v=vs.118).aspx

https://msdn.microsoft.com/en-us/library/microsoft.owin.security.microsoftaccount.microsoftaccountauthenticationprovider.onauthenticated(v=vs.113).aspx

, OO - , , .

, Startup.Auth.cs, Startup.Auth.cs . Startup.Auth.cs, , "" . ( , app.UseKentorOwinCookieSaver(); , , -, Session, !!!)

- GetAdditionalUserInfo()? ? , , , .

public partial class Startup
{
    private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
    private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
    private static string tenantId = ConfigurationManager.AppSettings["ida:TenantId"];
    private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
//private static string authority = aadInstance + tenantId;
// to make this multi tenant, use common endpoint, not the tenant specific endpoint
private static string authority = aadInstance + "common";

public void ConfigureAuth(IAppBuilder app)
{
    app.SetDefaultSignInAsAuthenticationType(
        CookieAuthenticationDefaults.AuthenticationType);

    // https://stackoverflow.com/questions/20737578/asp-net-sessionid-owin-cookies-do-not-send-to-browser
    app.UseKentorOwinCookieSaver();

    app.UseCookieAuthentication(
        new CookieAuthenticationOptions());

    app.UseOpenIdConnectAuthentication(
        new OpenIdConnectAuthenticationOptions
        {
            ClientId = clientId,
            Authority = authority,
            PostLogoutRedirectUri = postLogoutRedirectUri,
            TokenValidationParameters = new TokenValidationParameters
            {
                // If you don't add this, you get IDX10205
                // from here http://charliedigital.com/2015/03/14/adding-support-for-azure-ad-login-o365-to-mvc-apps/
                ValidateIssuer = false                        
            },
            Notifications = new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = ctx =>
                {
                    bool isAjaxRequest = (ctx.Request.Headers != null && ctx.Request.Headers["X-Requested-With"] == "XMLHttpRequest");

                    if (isAjaxRequest)
                    {
                        ctx.Response.Headers.Remove("Set-Cookie");
                        ctx.State = NotificationResultState.HandledResponse;
                    }

                    return System.Threading.Tasks.Task.FromResult(0);
                }
            }
        });
   }
}
+6
1

OWIN OpenID Connect Middleware , Notifications. SecurityTokenValidated:

RedirectToIdentityProvider = ctx => {...},
SecurityTokenValidated = (context) =>
{
    string userID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

    // Here you can retrieve information from Database. Let say you get r.Group_ID.

    var role = r.Group_ID;

    // You can now add it to Identity and no need to use session.

    Claim roleClaim = new Claim(
        "http://nomatterwhatyouput/role",
        role,
        ClaimValueTypes.[RoleType],
        "LocalAuthority");
    context.AuthenticationTicket.Identity.AddClaim(roleClaim);

    // Do same for all values you have. Remember to set unique claim URL for each value.

    return Task.CompletedTask;
},

, :

public ActionResult Index()
{
    var role = ClaimsPrincipal.Current.FindFirst("http://nomatterwhatyouput/role");
    return View();
}
+4

Source: https://habr.com/ru/post/1016461/


All Articles