How to do cookie auth using vue 3 and C# asp net core?
- User
How to do cookie auth using vue 3 and C# asp net core?
- Assistant
How to do cookie auth using vue 3 and C# asp net core?
Implementing cookie authentication using Vue 3 and ASP.NET Core involves setting up your API in ASP.NET Core to use cookies for authentication and then configuring your Vue.js application to handle login and logout functionality. Below are the main steps to achieve this:
Create a new ASP.NET Core Web API project: You can use the .NET CLI or Visual Studio to create a new project.
Configure Authentication: Open the Startup.cs or Program.cs in your ASP.NET Core project and configure cookie authentication.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/api/account/login"; // Path to login
options.LogoutPath = "/api/account/logout"; // Path to logout
});
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication(); // Enable cookie auth
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
Create Account Controller: Create a controller for handling login/logout.
[Route("api/[controller]")]
[ApiController]
public class AccountController : ControllerBase
{
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginModel model)
{
if (ModelState.IsValid)
{
// Validate user credentials here (e.g., check against a database)
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, model.Username),
};
var claimsIdentity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
var authProperties = new AuthenticationProperties
{
IsPersistent = model.RememberMe
};
await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
new ClaimsPrincipal(claimsIdentity), authProperties);
return Ok();
}
return Unauthorized();
}
[HttpPost("logout")]
public async Task<IActionResult> Logout()
{
await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
return Ok();
}
}
public class LoginModel
{
public string Username { get; set; }
public string Password { get; set; }
public bool RememberMe { get; set; }
}
Create a new Vue 3 project: You can use Vue CLI or any other method to set up your Vue application.
Install axios: You will need a library to make HTTP requests to your API.
npm install axios
Create an Auth Service: This service will handle login, logout, and any necessary API interactions related to authentication.
// src/services/auth.js
import axios from 'axios';
const API_URL = 'https://localhost:5001/api/account/'; // Adjust URL accordingly
class AuthService {
login(username, password, rememberMe) {
return axios.post(API_URL + 'login', {
username,
password,
rememberMe
});
}
logout() {
return axios.post(API_URL + 'logout');
}
}
export default new AuthService();
Create Login Component:
<!-- src/components/Login.vue -->
<template>
<div>
<form @submit.prevent="login">
<input v-model="username" placeholder="Username" required />
<input v-model="password" type="password" placeholder="Password" required />
<label>
<input type="checkbox" v-model="rememberMe" /> Remember Me
</label>
<button type="submit">Login</button>
</form>
<div v-if="error">{{ error }}</div>
</div>
</template>
<script>
import AuthService from "@/services/auth";
export default {
data() {
return {
username: '',
password: '',
rememberMe: false,
error: ''
};
},
methods: {
async login() {
try {
await AuthService.login(this.username, this.password, this.rememberMe);
this.error = '';
// Redirect or perform other actions after login (e.g., update state)
} catch (err) {
this.error = 'Invalid credentials.';
}
}
}
};
</script>
By following these steps, you can successfully implement cookie-based authentication between a Vue.js frontend and an ASP.NET Core backend.
Not yet included in a published release.
Handling Logout:
Create a logout method, either in the same component or in a dedicated service component.
// Add this to your Auth Service
logout() {
return axios.post(API_URL + 'logout');
}