Home > OS >  How to get logged user in vuejs
How to get logged user in vuejs

Time:06-08

I made a jwt authetication using asp.net core and vuejs this is my auth controller :

 [Route("Login")]
    [HttpPost]
    public IActionResult Login(LoginArgument loginArgument)
    {
        var user = _userService.GetByEmail(loginArgument.Email);
        if (user == null) return BadRequest(error: new { message = "Invalid credential : verify email" });
        if (!BC.BCrypt.Verify(text: loginArgument.Password, hash: user.Password))
        {
            return BadRequest(error: new { message = "Invalid credential : verify password" });
        }
        var jwt= _jwtService.Generate(user.Id);

        Response.Cookies.Append(key: "jwt", value: jwt, new Microsoft.AspNetCore.Http.CookieOptions
        {
      HttpOnly=false,
      SameSite=Microsoft.AspNetCore.Http.SameSiteMode.None
        }) ;

        return Ok(user);
    }
    
    [Route("User")]
    [HttpGet]
    public IActionResult User()
    {
        try
        {
            var jwt = Request.Cookies["jwt"];

            var token = _jwtService.Verify(jwt);

            int userId = int.Parse(token.Issuer);

            var user = _userService.GetById(userId);

            return Ok(user);
        }
        catch (Exception)
        {
            return Unauthorized();
        }
    }

and this is the login in vue

       <script lang="ts">
import { reactive } from 'vue';
import { useRouter } from "vue-router";
export default {
    name: "Login",
    setup() {
        const data = reactive({
            email: '',
            password: ''
        });
        const router = useRouter();
        const submit = async () => {
            await fetch('https://localhost:44391/api/Auth/Login', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                credentials: 'include',
                body: JSON.stringify(data)
            });
            await router.push('/Countries');
        }
        return {
            data,
            submit
        }
    },
    
}

the login part is working in front and back sides perfectly and i can see the cookies the problem is when i try to get the logged user. in back side i can get it successfully but in front it says that no user is logged here is the loggedUser vue

 <script lang="ts">
import { onMounted, ref } from 'vue';
export default {
    name: "LoggedUser",
    setup() {
        const message = ref('You are not logged in!');
        onMounted(async () => {
           
                const response = await fetch('https://localhost:44391/api/Auth/User', {
                    headers: { 'Content-Type': 'application/json' },
                    credentials: 'include'
                });
                const content = await response.json();
                message.value = `hi ${content.name}`;
            
        });
        return {
            message
        }
    }
}

Here is the errors i got when i inspect the page : this issues appear the moment of login

1- Mark cross-site cookies as Secure to allow setting them in cross-site contexts
2- Migrate entirely to HTTPS to have cookies sent to same-site subresources

this one appears when i call loggedUser in front even so it works in the back side

{type: "https://tools.ietf.org/html/rfc7235#section-3.1", title: "Unauthorized", status: 
401,…}
status: 401
title: "Unauthorized"
traceId: "00-b4a9f6fee8dff6439952ded0bb50005d-43c9aee84c454b40-00"
type: "https://tools.ietf.org/html/rfc7235#section-3.1"

CodePudding user response:

You need to send the access token in the request headers

Example:
let token = '???'
const response = await post('localhost/api/auth/user', {
    headers: { 
    'Content-Type': 'application/json' 
    'Authorization' : 'Bearer '  token
}
});
  • Related