AD Auth

mail@pastecode.io avatar
unknown
csharp
2 months ago
2.3 kB
0
Indexable
Never
public class ADAuthentication : IAuthenticationStrategy
{
    private readonly JWTSettings _jwtSettings;
    private readonly Authentication _authentication;

    public ADAuthentication(JWTSettings jwtSettings,
    Authentication authentication)
    {
        _jwtSettings = jwtSettings;
        _authentication = authentication;
    }
    public async Task<UserSignInResponse> Authentification(SignInModel signInModel)
    {
        int statusCode = 200;
        string? statusMessage = "Logged successfully !";
        string? errorMessage = "";
        string? userId = null;
        bool isValidRequest = true;
        string? AccessToken = "";
        var path = _authentication.Path;
        if (String.IsNullOrEmpty(signInModel.Username))
        {
            isValidRequest = false;
            statusCode = 500;
            errorMessage = "You have to provide the username !";
        }
        if (isValidRequest)
        {
            try
            {
                string username = signInModel.Username;
                string pwd = signInModel.Password;
                DirectoryEntry de = new DirectoryEntry(path, username, pwd);
                DirectorySearcher dsearch = new DirectorySearcher(de);
                SearchResult results = null;
                results = dsearch.FindOne();
                var authClaims = new List<Claim>
                {
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                };
                var tokenString = Helpers.TokenHandler.CreateToken(authClaims, _jwtSettings);
                AccessToken = new JwtSecurityTokenHandler().WriteToken(tokenString);
                statusCode = 200;
                statusMessage = "Success";
            }
            catch
            {
                statusCode = 401;
                statusMessage = "Unauthorized";
                errorMessage = "Incorrect username or password";

            }
        }
        UserSignInResponse userSignInResponse = new UserSignInResponse
        {
            StatusCode = statusCode,
            StatusMessage = statusMessage,
            ErrorMessage = errorMessage,
            AccessToken = AccessToken,
            UserId = userId
        };
        return userSignInResponse;
    }
}
Leave a Comment