This is class for Custom Authentiction, but it's not printing message for wrong token key(token key is unique string for each user)
=>AuthenticateResult.Fail("Invalid Token Used for Authorisation") It's just showing Unauthorised 401 status code in postman.
var valtoken = auth.getTokenDetails(token); method returns user details if user with specified token has access to get method of controller else returns null. So for null result I want to return Unauthorised 401 status code with custom message for Get api call
namespace CustomAuthDemo
{
/*public class AuthenticationSchemeConstants
{
public const string BasicAuthScheme = "Basic";
}*/
public class BasicAuthSchemeOptions:AuthenticationSchemeOptions
{
}
public class CustAuthHandler : AuthenticationHandler<BasicAuthSchemeOptions>
{
private readonly ICustomAuthService auth;
public CustAuthHandler(IOptionsMonitor<BasicAuthSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
ISystemClock clock,
ICustomAuthService auth):base(options,logger,encoder,clock)
{
this.auth = auth;
}
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
if (!Request.Headers.ContainsKey("Authorization"))
return AuthenticateResult.Fail("Unauthorised");
string authheader = Request.Headers["Authorization"];
if (string.IsNullOrEmpty(authheader))
return AuthenticateResult.Fail("Unauthorised");
if(!authheader.StartsWith("bearer",StringComparison.OrdinalIgnoreCase))
return AuthenticateResult.Fail("Unauthorised");
string token = authheader.Substring("bearer".Length).Trim();
try
{
return ValidateToken(token);
}
catch(Exception ex)
{
Logger.LogInformation(ex.Message);
return AuthenticateResult.Fail("Unauthorised");
}
}
private AuthenticateResult ValidateToken(string token)
{
if (string.IsNullOrEmpty(token))
return AuthenticateResult.Fail("Unauthorised");
var valtoken = auth.getTokenDetails(token);
if (valtoken == null)
return AuthenticateResult.Fail("Invalid Token Used for Authorisation");
var claims = new List<Claim>
{ new Claim(ClaimTypes.Name,valtoken.username)};
var identity = new ClaimsIdentity(claims, Scheme.Name);
var principal = new GenericPrincipal(identity, null);
var ticket = new AuthenticationTicket(principal, Scheme.Name);
return AuthenticateResult.Success(ticket);
}
I just override HandleChallengeAsync method in CustAuthHandler, this method is called Eveytime when authorisation fails, so I've written back a string and 401 status code to response body of my http request which has failed authentication.
protected override async Task HandleChallengeAsync(AuthenticationProperties properties)
{
await base.HandleChallengeAsync(properties);
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
string output = "authentification failed you don't have access to this content";
await Response.BodyWriter.WriteAsync(Encoding.UTF8.GetBytes(output));
}