Explain the use of Session function in ABP framework-Basic application

Source: Internet
Author: User
Tags instance method static class


If an application needs to log on, it must know what the current user has done. So ASP.net provides a set of its own session sessions object at the presentation layer, while ABP provides a place to
Gets the Iabpsession interface for the current user and tenant.



About Iabpsession
you must implement the Iabpsession interface if you need to get session information. Although you can implement it in your own way (iabpsession), it has been fully implemented in the Module-zero project.



Inject session
iabpsession is usually in the form of a property injection in a class that requires it, and it is not needed in a class that does not need to get session information. If we use the attribute injection method, we can use the
Nullabpsession.instance initializes it as the default (Iabpsession), as follows:


public class Myclass:itransientdependency
{public
  iabpsession abpsession {get; set;}

  Public MyClass ()
  {
    abpsession = nullabpsession.instance;
  }

  public void MyMethod ()
  {
    var currentuserid = Abpsession.userid;
    //...
  }
}


Since authorization is the task of the application tier, we should use iabpsession at the upper level of the application and application tiers (it is normal for us not to use iabpsession at the domain level).
Applicationservice, Abpcontroller and Abpapicontroller these 3 base classes have been injected into the abpsession attribute, so in the Application service instance method, Can directly use the Abpsession attribute.



Using the Session Property
some key properties defined by Abpsession:


    • UserId: The identity ID of the current user, or null if there is no current user. If authorized access is required, it cannot be empty.
    • Tenantid: The identity ID of the current tenant, or null if no current tenant is present.
    • Multitenancyside: May be host or tenant.


UserID and Tenantid can be null. The GetUserID () and Gettenantid () methods for obtaining data when they are not null are of course provided. When you are sure that you have the current user, you can use the GetUserID () method.



If the current user is empty, using this method throws an exception. Gettenantid () is used in the same way as GetUserID ().



ABP How to implement the session
Catalog Code:






Class Diagram:






Iabpsession:iabpsession interface


Using Abp.multitenancy;

Namespace Abp.Runtime.Session
{public
  interface iabpsession
  {
    long? UserId {get;}
    Int? Tenantid {get;}
    Multitenancysides multitenancyside {get;}
    Long? Impersonatoruserid {get;}
    Int? Impersonatortenantid {get;}}}



Nullabpsession: null object pattern implemented


using Abp.MultiTenancy;

namespace Abp.Runtime.Session
{
  /// <summary>
  /// Implements null object pattern for <see cref="IAbpSession"/>.
  /// </summary>
  public class NullAbpSession : IAbpSession
  {
    /// <summary>
    /// Singleton instance.
    /// </summary>
    public static NullAbpSession Instance { get { return SingletonInstance; } }
    private static readonly NullAbpSession SingletonInstance = new NullAbpSession();

    /// <inheritdoc/>
    public long? UserId { get { return null; } }

    /// <inheritdoc/>
    public int? TenantId { get { return null; } }

    public MultiTenancySides MultiTenancySide { get { return MultiTenancySides.Tenant; } }
    
    public long? ImpersonatorUserId { get { return null; } }
    
    public int? ImpersonatorTenantId { get { return null; } }

    private NullAbpSession()
    {

    }
  }
}


Claimsabpsession: Getting session State


using System;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using Abp.Configuration.Startup;
using Abp.MultiTenancy;
using Abp.Runtime.Security;

namespace Abp.Runtime.Session
{
  /// <summary>
  /// Implements <see cref="IAbpSession"/> to get session properties from claims of <see cref="Thread.CurrentPrincipal"/>.
  /// </summary>
  public class ClaimsAbpSession : IAbpSession
  {
    private const int DefaultTenantId = 1;

    public virtual long? UserId
    {
      get
      {
        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
        if (claimsPrincipal == null)
        {
          return null;
        }

        var claimsIdentity = claimsPrincipal.Identity as ClaimsIdentity;
        if (claimsIdentity == null)
        {
          return null;
        }

        var userIdClaim = claimsIdentity.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier);
        if (userIdClaim == null || string.IsNullOrEmpty(userIdClaim.Value))
        {
          return null;
        }

        long userId;
        if (!long.TryParse(userIdClaim.Value, out userId))
        {
          return null;
        }

        return userId;
      }
    }

    public virtual int? TenantId
    {
      get
      {
        if (!_multiTenancy.IsEnabled)
        {
          return DefaultTenantId;
        }

        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
        if (claimsPrincipal == null)
        {
          return null;
        }

        var tenantIdClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.TenantId);
        if (tenantIdClaim == null || string.IsNullOrEmpty(tenantIdClaim.Value))
        {
          return null;
        }

        return Convert.ToInt32(tenantIdClaim.Value);
      }
    }

    public virtual MultiTenancySides MultiTenancySide
    {
      get
      {
        return _multiTenancy.IsEnabled && !TenantId.HasValue
          ? MultiTenancySides.Host
          : MultiTenancySides.Tenant;
      }
    }

    public virtual long? ImpersonatorUserId
    {
      get
      {
        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
        if (claimsPrincipal == null)
        {
          return null;
        }

        var impersonatorUserIdClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorUserId);
        if (impersonatorUserIdClaim == null || string.IsNullOrEmpty(impersonatorUserIdClaim.Value))
        {
          return null;
        }

        return Convert.ToInt64(impersonatorUserIdClaim.Value);
      }
    }

    public virtual int? ImpersonatorTenantId
    {
      get
      {
        if (!_multiTenancy.IsEnabled)
        {
          return DefaultTenantId;
        }

        var claimsPrincipal = Thread.CurrentPrincipal as ClaimsPrincipal;
        if (claimsPrincipal == null)
        {
          return null;
        }

        var impersonatorTenantIdClaim = claimsPrincipal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.ImpersonatorTenantId);
        if (impersonatorTenantIdClaim == null || string.IsNullOrEmpty(impersonatorTenantIdClaim.Value))
        {
          return null;
        }

        return Convert.ToInt32(impersonatorTenantIdClaim.Value);
      }
    }

    private readonly IMultiTenancyConfig _multiTenancy;

    /// <summary>
    /// Constructor.
    /// </summary>
    public ClaimsAbpSession(IMultiTenancyConfig multiTenancy)
    {
      _multiTenancy = multiTenancy;
    }
  }
}


Abpsessionextensions:iabpsession extension Methods


using System;

namespace Abp.Runtime.Session
{
  /// <summary>
  /// Extension methods for <see cref="IAbpSession"/>.
  /// </summary>
  public static class AbpSessionExtensions
  {
    /// <summary>
    /// Gets current User's Id.
    /// Throws <see cref="AbpException"/> if <see cref="IAbpSession.UserId"/> is null.
    /// </summary>
    /// <param name="session">Session object.</param>
    /// <returns>Current User's Id.</returns>
    public static long GetUserId(this IAbpSession session)
    {
      if (!session.UserId.HasValue)
      {
        throw new AbpException("Session.UserId is null! Probably, user is not logged in.");
      }

      return session.UserId.Value;
    }

    /// <summary>
    /// Gets current Tenant's Id.
    /// Throws <see cref="AbpException"/> if <see cref="IAbpSession.TenantId"/> is null.
    /// </summary>
    /// <param name="session">Session object.</param>
    /// <returns>Current Tenant's Id.</returns>
    /// <exception cref="AbpException"></exception>
    public static int GetTenantId(this IAbpSession session)
    {
      if (!session.TenantId.HasValue)
      {
        throw new AbpException("Session.TenantId is null! Possible problems: No user logged in or current logged in user in a host user (TenantId is always null for host users).");
      }

      return session.TenantId.Value;
    }

    /// <summary>
    /// Creates <see cref="UserIdentifier"/> from given session.
    /// Returns null if <see cref="IAbpSession.UserId"/> is null.
    /// </summary>
    /// <param name="session">The session.</param>
    public static UserIdentifier ToUserIdentifier(this IAbpSession session)
    {
      return session.UserId == null
        ? null
        : new UserIdentifier(session.TenantId, session.GetUserId());
    }
  }
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.