Back to Devexpress

UserManager.GetCurrentPrincipal() Method

expressappframework-devexpress-dot-expressapp-dot-security-dot-usermanager.md

latest3.2 KB
Original Source

UserManager.GetCurrentPrincipal() Method

Gets the current user’s ClaimsPrincipal object.

Namespace : DevExpress.ExpressApp.Security

Assembly : DevExpress.ExpressApp.Security.v25.2.dll

NuGet Package : DevExpress.ExpressApp.Security

Declaration

csharp
public IPrincipal GetCurrentPrincipal()
vb
Public Function GetCurrentPrincipal As IPrincipal

Returns

TypeDescription
IPrincipal

An object that implements the IPrincipal interface.

|

Remarks

The following code snippet demonstrates a custom authentication provider implementation that uses the GetCurrentPrincipal method to access the ClaimsPrincipal object returned by a third-party authentication service (Template Kit generates equivalent code for applications configured to use OAuth2).

csharp
public class CustomAuthenticationProvider : IAuthenticationProviderV2 {
    private readonly UserManager userManager;

    public CustomAuthenticationProvider(UserManager userManager) {
        this.userManager = userManager;
    }

    public object Authenticate(IObjectSpace objectSpace) {
        var currentPrincipal = userManager.GetCurrentPrincipal();
        if(currentPrincipal?.Identity?.IsAuthenticated ?? false) {
            var user = userManager.FindUserByPrincipal<ApplicationUser>(objectSpace, currentPrincipal);
            if(user != null) {
                return new UserResult<ApplicationUser>(user);
            }

        // The code below creates users for testing purposes only.
#if !RELEASE
            bool autoCreateUser = true;
            if(autoCreateUser) {
                var userResult = userManager.CreateUser<ApplicationUser>(objectSpace, currentPrincipal, user => {
                    user.Roles.Add(objectSpace.FirstOrDefault<PermissionPolicyRole>(role => role.Name == "Default"));
                });
                if(!userResult.Succeeded) {
                    //throw userResult.Error;
                }
                return userResult;
            }
#endif
        }
        return null;
    }
}

See Also

Authentication System Architecture (Blazor)

UserManager Class

UserManager Members

DevExpress.ExpressApp.Security Namespace