1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

.net6 core API custom authentication handler and Angular HttpInterceptor [receive Status code...

Discussão em 'Angular' iniciado por himadri, Setembro 30, 2024.

  1. himadri

    himadri Guest

    I have written a custom authentication handler in .net core. The custom handler works fine. if a user is unauthorized it return 401 Unauthorized. In UI i use a angular HttpInspector to receive the Unauthorized response send from api. I faced two problems :-

    1. In HttpInspector I do not receive the status 401, The status code i receive is 0
    2. For any authenticate user(status code 200 Ok) i do not receive any CORS problem. but for unauthorized response i am getting CORS problem ( I also configured the Cor policy in the program.cs file in .net core API) :
      [​IMG] Screenshot of Cors Configuration in Program.cs
      [​IMG]

    Here is the Code for Custom Authentication Handler :

    public class CustomAuthenticationHandler :AuthenticationHandler<AuthenticationSchemeOptions>
    {
    string failReason;
    //Constructor to intinilize base
    public CustomAuthenticationHandler(IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock) :base(options,logger, encoder, clock)
    {
    }

    protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
    {
    if (!Request.Headers.ContainsKey("Authorization"))
    {


    failReason = "Himadri You are failed";
    return AuthenticateResult.Fail(failReason);
    }

    string strAuthorization = Request.Headers["Authorization"];
    if (string.IsNullOrEmpty(strAuthorization))
    {
    return AuthenticateResult.Fail("Unauthorized");
    }

    try
    {
    var handler = new JwtSecurityTokenHandler();
    string token = strAuthorization.Substring("bearer".Length).Trim();
    var tokenS = handler.ReadToken(token) as JwtSecurityToken;
    //var id = tokenS.Claims.First(claim => claim.Type == "nameid").Value;

    var claim = new List<Claim>
    {
    new Claim(ClaimTypes.Name, "himadri")
    };
    var identity = new ClaimsIdentity(claim, Scheme.Name);
    var principal = new GenericPrincipal(identity, null);
    var ticket = new AuthenticationTicket(principal, Scheme.Name);
    return AuthenticateResult.Success(ticket);
    }
    catch (Exception ex)
    {
    return AuthenticateResult.Fail(ex.Message);
    }

    }

    protected override Task HandleChallengeAsync(AuthenticationProperties properties)
    {
    //Response.StatusCode = 401;

    if (failReason != null)
    {

    Response.StatusCode = 401;
    Response.Headers.Append("access-control-expose-headers", "WWW-Authenticate");

    Response.Headers.Append("WWW-Authenticate", failReason);
    Response.WriteAsync(failReason);

    Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = failReason;


    }
    return Task.CompletedTask;
    }
    }


    If i call the API from Postman it shows the status code and header perfectly [​IMG]

    But if call the api from angular application [in a HTTPInterceptor] then for unauthenticated user Status code =0 and CORS problem arrives but for authenticated user data comes properly, Status code=200 and no CORS problem. [Please refer the 1st and 2nd screen shot]

    Screen Shot of HTTPInterecptor [​IMG]

    what I am missing here?. Without receiving proper status code and header how can i display proper message for unauthenticated/Unauthorized user? How can i receive proper status code and headers in angular application from .net core custom authentication middleware?

    Continue reading...

Compartilhe esta Página