Luka
Luka

Reputation: 97

Web site Authentication against Web API

I have the following scenario with net core 3. A web site with a login page. This login page sends the user and password to a Web API that response with a JWT token if the credentials are correct.

How can I set now my web user as authenticated? how can I set the claims of the web user with the claims I recieve from the API token?

Is it neccessary to add any service on the startup of something similar?

Could you provide me with any basic sample of how to do it or any documentation?

Thank you

Upvotes: 0

Views: 77

Answers (2)

Nan Yu
Nan Yu

Reputation: 27538

You can use cookie authentication :

  1. In the Startup.ConfigureServices method, create the Authentication Middleware services with the AddAuthentication and AddCookie methods:

    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie(options =>
            {
                options.LoginPath = "/Account/Login";
            });
    

    And enable middleware in Configure :

    app.UseAuthentication();
    app.UseAuthorization();
    
  2. And in the action which user post credential to , you can send a http request to web api with credential , web api will validate the credential and return back jwt token , your web application then decode token and sign in user like :

    var stream = "[token]";
    var handler = new JwtSecurityTokenHandler();
    
    var tokenS = handler.ReadToken(stream) as JwtSecurityToken;
    
    
    var claimsIdentity = new ClaimsIdentity(
        tokenS.Claims, CookieAuthenticationDefaults.AuthenticationScheme);
    
    var authProperties = new AuthenticationProperties
    {
    
        RedirectUri = "/Home/Privacy",
    
    };
    
    await HttpContext.SignInAsync(
        CookieAuthenticationDefaults.AuthenticationScheme,
        new ClaimsPrincipal(claimsIdentity),
        authProperties);
    

Upvotes: 1

MRSessions
MRSessions

Reputation: 336

Depending on your front end solution, you need to figure out how to decode the JWT that you received to retrieve the values that you need.

Here are a couple of things, again depending on what you are using on the front end

C# https://developer.okta.com/blog/2019/06/26/decode-jwt-in-csharp-for-authorization

NPM Package for SPA https://www.npmjs.com/package/jwt-decode

Here is another good resource for JWT https://jwt.io/

You can take the JWT you received to view the values that are in it

Upvotes: 0

Related Questions