โŒ

Normal view

There are new articles available, click to refresh the page.
Before yesterdayMain stream

How to refresh CSRF token on login when using cookie authentication without identity in ASP .NET Core Web API

I have an ASP .NET Core 3.1 backend, with angular 9 frontend (based on dotnet angular template, just with updated angular to v9). I use cookie authentication (I know JWT is more suited for SPAs, take this as an experiment) and I also added support for CSRF protection on server side:

services.AddAntiforgery(options =>
{
   options.HeaderName = "X-XSRF-TOKEN"; // angular csrf header name
});

I have server side setup to automatically check CSRF using

options => options.Filters.Add(new AutoValidateAntiforgeryTokenAttribute())

so GET requests are not checked against CSRF, but POST are.

At the very beginning, the angular app makes a GET request to api/init to get some initial data before bootstrapping. On server-side this action initializes CSRF as follows:

// init action body
var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions
{
   HttpOnly = false
});
// return some inital data DTO

This works as expected - the GET response contains 2 CSRF cookies - first being ASP .NET core default CSRF cookie .AspNetCore.Antiforgery... and second being XSRF-TOKEN that angular will read and put into X-XSRF-TOKEN header for subsequent requests.

If afterwards I do login (POST request containing credentials to api/auth/login) from the angular app, everything works - request is POSTed including X-XSRF-TOKEN header and CSRF validation passes, so if credentials are correct the user is logged in.

Now here is where the problems begin. The ASP .NET server app uses cookie authentication without identity as described here https://learn.microsoft.com/en-us/aspnet/core/security/authentication/cookie?view=aspnetcore-3.1. In login action also CSRF token needs to be regenerated as with authentication the CSRF token starts including authenticated user identity. Therefore my login action looks like this:

public async Task<IActionResult> Login(CredentialsDto credentials)
{
   // fake user credentials check
   if (credentials.Login != "admin" || credentials.Password != "admin")
   {
      return Unauthorized();
   }

   var claimsIdentity = new ClaimsIdentity(new[]
   {
     new Claim(ClaimTypes.Name, "theAdmin"),
   }, CookieAuthenticationDefaults.AuthenticationScheme);

   var claimsPrincipal = new ClaimsPrincipal(claimsIdentity);
   await HttpContext.SignInAsync(claimsPrincipal); 

   // refresh antiforgery token on login (same code as in init action before)
   var tokens = _antiForgery.GetAndStoreTokens(HttpContext);
   Response.Cookies.Append("XSRF-TOKEN", tokens.RequestToken, new CookieOptions 
   {
       HttpOnly = false
   });

   return new JsonResult(new UserDto { Id = 1, Login = "theAdmin" });
}

This however does not work. The response contains the XSRF-TOKEN cookie, but subsequent POST request (in my case its logout = POST to api/auth/logout) fails with 400, despite angular correctly putting this cookie value into X-XSRF-TOKEN header. I believe the reason is that the dafault .AspNetCore.Antiforgery... cookie is not being set in the response for some reason, therefore retains the original value even after login and thus CSRF check fails as the values don't match,

How does one properly refresh the CSRF token is such scenario?

Unauthorized (401) while i sent a Post request to the server

when i try to add a post to my server i get 401 Unauthorized i sent my jwt in postman with Bearer jwt but nothing change . i think the probleme in the api where exactly i don't have any idea

i use django as backend and react as frontend those are all my code

urls.py :

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView


urlpatterns = [
    #path('admin/', admin.site.urls),
    path('auth/', include('djoser.urls')),
    path('auth/', include('djoser.urls.jwt')),

    path('', include('crm.urls')),
]

urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]

views.py :

from django.shortcuts import render ,redirect ,get_object_or_404          
from rest_framework.parsers import MultiPartParser, FormParser
from .serializers import PostSerializer
from rest_framework.viewsets import ModelViewSet, GenericViewSet
from .forms import CreateUserForm, LoginForm
from rest_framework.response import Response
from rest_framework import status

#, UploadForm
from rest_framework.decorators import api_view, action

from django.contrib.auth.decorators import login_required, user_passes_test
from .models import Post, PostImage

# - Authentication models and functions 
from django.contrib.auth.models import auth 
from django.contrib.auth import authenticate, login, logout

def homepage(request):

    return render(request, 'crm/index.html')

def register(request):

    form = CreateUserForm()

    if request.method == "POST":

        form = CreateUserForm(request.POST)

        if form.is_valid():

            form.save()

            return redirect("my-login")

    context = {'registerform':form}

    return render(request, 'crm/register.html', context=context)



def my_login(request):

    form = LoginForm()

    if request.method == 'POST':

        form = LoginForm(request, data=request.POST)
        
        if form.is_valid():

            username = request.POST.get('username')
            password = request.POST.get('password')

            user = authenticate(request, username=username,password=password)

            if user is not None :

                auth.login(request, user)

                return redirect("dashboard")

    
    context = {'loginform':form}

    return render(request, 'crm/my-login.html', context=context)

def user_logout(request):
    auth.logout(request)
    
    return redirect("")

#def upload(request):
#   if request.POST:
#      form = UploadForm(request.POST, request.FILES)
#     print(request.FILES)
    #    if form.is_valid():
#       form.save_()
#  return redirect(homepage)
    #return render(request, 'crm/upload.html', {'form' : UploadForm })

def post_view(request):
    posts = Post.objects.all()
    return render(request, 'post.html', {'posts':posts})

def detail_view(request, id):
    post = get_object_or_404(Post, id=id)
    photos = PostImage.objects.filter(post=post)
    return render(request, 'detail.html', {
        'post':post,
        'photos':photos
    })

@api_view(['POST'])
class PostsViewSet(ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
    parser_classes = (MultiPartParser, FormParser)
    
    def create(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)






@login_required(login_url="my-login")
def dashboard(request):

    return render(request, 'crm/dashboard.html')

serializers.py :

from djoser.serializers import UserCreateSerializer
from django.contrib.auth import get_user_model
from rest_framework import serializers
from .models import Post, PostImage



User = get_user_model()

class CustomUserCreateSerializer(UserCreateSerializer):
    age = serializers.IntegerField(required=True)
    role = serializers.ChoiceField(choices=User.Role.choices, required=True)

    class Meta(UserCreateSerializer.Meta):
        model = User
        fields = ('id', 'email', 'name', 'password', 'age', 'role')

    def create(self, validated_data):
        user = User.objects.create_user(**validated_data)
        return user
    

class PostImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = PostImage
        fields = ('id', 'post', 'image')

class PostSerializer(serializers.ModelSerializer):
    images = PostImageSerializer(many=True, read_only=True)
    uploaded_images = serializers.ListField(
        child = serializers.ImageField(max_length = 1000000, allow_empty_file = False, use_url = False),
        write_only=True)
    
    class Meta:
        model = Post
        fields = ('id', 'title', 'text', 'category', 'author', 'created_at', 'images', "uploaded_images")
    

    def create(self, validated_data):
        uploaded_images = validated_data.pop("uploaded_images")
        post = Post.objects.create(**validated_data)
        for image in uploaded_images:
            newpost_image = PostImage.objects.create(post=post, image=image)
    
        return post 

models.py :

from django.db import models
from django.contrib.auth.models import PermissionsMixin , AbstractBaseUser, BaseUserManager
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.core.validators import MinValueValidator, MaxValueValidator
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ValidationError

class CustomUserManager(BaseUserManager):
    def create_user(self, email, name, password=None, **extra_fields):
        if not email:
            raise ValueError(_('The Email field must be set'))
        email = self.normalize_email(email)
        user = self.model(email=email, name=name, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, email, name, password=None, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_staff') is not True:
            raise ValueError(_('Superuser must have is_staff=True.'))
        if extra_fields.get('is_superuser') is not True:
            raise ValueError(_('Superuser must have is_superuser=True.'))
        return self.create_user(email, name, password, **extra_fields)

class User(AbstractBaseUser):
    email = models.EmailField(_('email address'), unique=True)
    name = models.CharField(_('name'), max_length=150, default='Anonymous', unique=False)
    age = models.PositiveIntegerField(_('age'), blank=True, null=True, validators=[MinValueValidator(18), MaxValueValidator(100)])
    is_active = models.BooleanField(_('active'), default=True)
    is_staff = models.BooleanField(_('staff status'), default=False)

    class Role(models.TextChoices):
        ADMIN = "ADMIN", "Admin"
        CLIENT = "CLIENT", "Client"
        ANALYST = "ANALYST", "Analyst"

    role = models.CharField(_('role'), max_length=50, choices=Role.choices, default=Role.CLIENT)
    objects = CustomUserManager()
    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'age', 'role']

    def save(self, *args, **kwargs):
        if not self.pk:
            if not self.email:
                raise ValidationError("Email address is required.")
            elif User.objects.filter(email=self.email).exists():
                raise ValidationError("Email address must be unique.")
            elif not self.role:
                self.role = self.Role.CLIENT
        super().save(*args, **kwargs)
class ClientManager(CustomUserManager):
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(role=User.Role.CLIENT)

class Client(User):
    base_role = User.Role.CLIENT
    objects = ClientManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for Client"

class AnalystManager(CustomUserManager):
    def get_queryset(self, *args, **kwargs):
        return super().get_queryset(*args, **kwargs).filter(role=User.Role.ANALYST)

class Analyst(User):
    base_role = User.Role.ANALYST
    objects = AnalystManager()

    class Meta:
        proxy = True

    def welcome(self):
        return "Only for Analysts"




class Post(models.Model):
    CATEGORY_CHOICES = [
        ('math', 'Math'),
        ('philosophy', 'Philosophy'),
        ('science', 'Science'),
        ('political', 'Political'),
        ('other', 'Other'),
    ]
    
    title = models.CharField(max_length=250, blank=False)  # Required field
    text = models.TextField(blank=False)  # Required field
    category = models.CharField(max_length=25, choices=CATEGORY_CHOICES, blank=False)  # Required field
    author = models.CharField(max_length=100)  # You can adjust the max length as needed
    created_at = models.DateTimeField(auto_now_add=True)  # Automatically set to the current date and time when created
    
    def __str__(self):
        return self.title



class PostImage(models.Model):
    post = models.ForeignKey(Post, default=None ,on_delete=models.CASCADE, related_name = "images")
    image = models.ImageField(upload_to='djangoposts/files/images', default="", null=True, blank=True)
    
    def __str__(self):
        return self.post.title

i try to put a jwt token in the Bearer Token in postman but nothing have change the same error still show up

how to segregate authanticated and unauthanticated routes in the react with react-router-dom

this is my 'routes.tsx' file where all i simply want to do is if user is not authenticated then he/she should not able to navigate into dashboard and other routes which will comes into app later. and if he is authenticated then he/she should not navigate to unauthenticated routes which are login , signup , confirm otp there could be more also. for now isAuthenticated function is only returning if local storage has token or not in boolean. this is also looks good but there are some issues in this code which i am facing like

  • even after token is there in the local storage if user tries to navigate to any auth related route he is able to navigate there.
  • one more thing which i want to implement here with 'axios' intercepter that if user manually removes token and then try to run any api then in the interceptor should check if local storage has no token then interceptor should clear storage and then navigate user back to the auth/login

expecting a simple and optimal flow for the authenticated and vice versa routes and with the interceptor 'axios' without refreshing app

import { Suspense } from "react";
import { Navigate, RouteObject } from "react-router-dom";
import { isAuthenticated } from "./auth";
import { Login, Dashboard, Signup, SendOTP } from "../pages";
import { AuthLayout, PrimaryLayout } from "../layouts";

export const routes: RouteObject[] = [
  {
    path: "/dashboard",
    element: (
      <Suspense fallback={<div>...LOADING</div>}>
        {isAuthenticated() ? (
          <PrimaryLayout />
        ) : (
          <Navigate to="/auth/login" replace />
        )}
      </Suspense>
    ),
    children: [
      {
        index: true,
        element: <Dashboard />,
      },
      { path: "*", element: <Navigate to="dashboard" replace /> },
    ],
  },
  {
    path: "/auth",
    element: <AuthLayout />,
    children: [
      {
        index: true,
        element: isAuthenticated() ? (
          <Navigate to="/dashboard" replace />
        ) : (
          <Navigate to="login" replace />
        ),
      },
      {
        path: "login",
        element: (
          <Suspense fallback={<div>...LOADING</div>}>
            <Login />
          </Suspense>
        ),
      },
      {
        path: "signup",
        element: (
          <Suspense fallback={<div>...LOADING</div>}>
            <Signup />
          </Suspense>
        ),
      },
      {
        path: "confirm-otp",
        element: (
          <Suspense fallback={<div>...LOADING</div>}>
            <SendOTP />
          </Suspense>
        ),
      },
      { path: "*", element: <Navigate to="/auth/login" replace /> },
    ],
  },
  {
    path: "*",
    element: isAuthenticated() ? (
      <Navigate to="/dashboard" replace />
    ) : (
      <Navigate to="/auth/login" replace />
    ),
  },
];

How authentication Laravel Sanctum SPA application with two subdomain

I'm currently working on a Laravel application that consists of two areas: Admin and App. The admin area is built using Inertia.js, and authentication is handled with Sanctum, which is functioning correctly. The app area, on the other hand, utilizes Nuxt 3. My goal is to display content fetched via API from the admin application in the app area. While authentication works well, I encounter a 401 error when attempting to fetch authenticated user data.

Additionally, There is one more issue I'm facing if I'm logged into the admin and trying to login into the app it gives a 305 response on the login request and if I logout from the admin and try to login into the app login is successful but the /api/user response 401 and If I visit the admin area it's showing me authenticated.

The domains for the areas: Admin: admin.kpowa.dev App: app.kpowa.dev:80

.env file in the laravel

SANCTUM_STATEFUL_DOMAINS="app.kpowa.dev,app.kpowa.dev:80,admin.kpowa.dev"
SESSION_DOMAIN=.kpowa.dev

login function

public function store(LoginRequest $request): JsonResponse|RedirectResponse
    {
        // Check if the request is from an SPA
        if (!EnsureFrontendRequestsAreStateful::fromFrontend($request)) {
            // Handle API authentication
            $validated = $request->validated();

            // Ensure rate limiting
            $request->ensureIsNotRateLimited();

            $user = User::query()->where('username', $validated['username'])->first();

            if (!$user || !Hash::check($validated['password'], $user->password)) {
                RateLimiter::hit($request->throttleKey());
                return response()->json(['' => trans('auth.failed')], 422);
            }

            $token = $user->createToken($request->userAgent())->plainTextToken;

            // Clear rate limiter
            RateLimiter::clear($request->throttleKey());

            return response()->json(['token' => $token], 200);
        }

        // Handle SPA authentication
        $credentials = $request->only('username', 'password') + ['type' => 1];
        if (!$request->header('x-inertia')) {
            $credentials = $request->only('email', 'password') + ['type' => [0, 2, 3]];
        }

        try {
            // Attempt authentication
            $request->authenticate($credentials);

            // Authentication successful, regenerate session
            $request->session()->regenerate();

            if (!$request->header('x-inertia')) {
                return response()->json(['status' => trans('auth.login_success')], 200);
            }

            return redirect()->intended(RouteServiceProvider::HOME);
        } catch (\Illuminate\Auth\AuthenticationException | \Illuminate\Validation\ValidationException $e) {
            // Authentication failed, redirect back with error message
            return back()->withErrors(['error' => trans('auth.failed')]);
        }
    }

LoginRequest.php

public function authenticate(array $credentials): void
    {
        $this->ensureIsNotRateLimited();

        if (! Auth::attempt($credentials, $this->boolean('remember'))) {
            RateLimiter::hit($this->throttleKey());

            throw ValidationException::withMessages([
                'error' => trans('auth.failed'),
            ]);
        }

        RateLimiter::clear($this->throttleKey());
    }

Could you assist me in resolving this issue?

I am trying to achive that I can use the admin and app area individually with secure authentication.

Role-based claims auth doesnt work asp.net core identity

I have problem

I'm using ASP.Net core Identity.

Realtion between users, claims and roles are as follows: User have role, role have claims

My claims saved in AspNetRoleClaims table

Roles in AspNetRoles

Users in AspNetUsers

Users connected with roles AspNetUserRoles

Now my user has CreateRole permission, but CreateRole endpoint returns 403 forbidden

what am I doing wrong? please help me :)

my program.cs file

    builder.Services.AddAuthorization(options =>
    {
        options.AddPolicy("RoleModulePolicy", policy => policy.RequireClaim("RoleModule"));
        options.AddPolicy("CreateRolePolicy", policy => policy.RequireClaim("CreateRole"));
        options.AddPolicy("EditRolePolicy", policy => policy.RequireClaim("EditRole"));
        options.AddPolicy("DeleteRolePolicy", policy => policy.RequireClaim("DeleteRole"));
    });

ClaimsStore.cs file

public static class ClaimsStore
{
    public static List<Claim> GetAllClaims()
    {
        return new List<Claim>()
        {
            new Claim("RoleModule", "Role Module"),
            new Claim("CreateRole", "Create Role"),
            new Claim("EditRole", "Edit Role"),
            new Claim("DeleteRole", "Delete Role"),
        };
    }
}

controller file

    [Authorize(Policy = "CreateRolePolicy")]
    [HttpPost("[action]")]
    public async Task<IActionResult> CreateRole(RoleCreateRequestModel model)
    {
        var result = await _roleManagementService.CreateRole(model);

        if (result.Succeeded)
        {
            return Ok(result);
        }
        else
        {
            return BadRequest(result);
        }
    }

Reducing Token Generation Delay with Azure.Identity Package

I am encountering a significant delay when generating access tokens using the Azure.Identity (version 1.11.0) package in my application. The scenario involves using a ChainedTokenCredential class with two token credentials:

  1. Managed Identity Credential with client ID.
  2. Default Credential.

My intention is that if the first token credential (Managed Identity Credential) fails to generate a token, the second one (Default Credential) should be used immediately. However, I've noticed that even though the first credential fails as expected, there is a delay of approximately 5 minutes before the token is generated using the second credential.

I suspect that there might be a retry policy in place that is causing this delay. Is there a way to disable or configure this retry policy so that the application switches to the second credential without such a delay?

Below is a simplified version of the code I'm using:

     private static async Task<string> GetTokenAsync()
 {
     AccessToken token =
          new ChainedTokenCredential(
             new ManagedIdentityCredential(clientId: "<client-id>"), 
             new DefaultAzureCredential()) // or AzureCliCredential(),VisualStudioCredential()... so on
         .GetToken(
             new TokenRequestContext(
                 new[] { "https://storage.azure.com/.default" },
                 isCaeEnabled: false
             ));

     return token.Token;
 }

Module not found: Can't resolve 'fs' - NextJS/NextAuth

I'm trying to use getServerSession method in my nextjs app since most users who had the same issue when trying to get profile data returned by session suggested me to go for getServerSession instead of just "getSession", so i just wanted to give it a go hoping it would work fine in this case, but now getting such weird error..

the error only pops out after importing getServerSession, i have to use that, otherwise, removing it and going only for getSession to render session on the client side will return null data, so i wont be able to render user profile data returned by session, checked many times similar questions as well but no luck, cant tell enough how crucial it is for me, any help is highly appreciated.

error:

error - ./node_modules/@mapbox/node-pre-gyp/lib/clean.js:8:0
Module not found: Can't resolve 'fs'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/@mapbox/node-pre-gyp/lib/ sync ^\.\/.*$
./node_modules/@mapbox/node-pre-gyp/lib/node-pre-gyp.js
./node_modules/bcrypt/bcrypt.js
./pages/api/auth/[...nextauth].js
./components/header/Top.js
./components/header/index.js
./pages/_app.js

here is my Top component where i want to show user data:

import { useState } from "react";
import styles from "./styles.module.scss";
import Link from "next/link";
import Image from "next/image";
import UserMenu from "./UserMenu";
import avatar from "../../public/avatar.png";
import { useSession, signIn, signOut, getSession } from "next-auth/react"
import { getServerSession } from "next-auth";
import { authOptions } from "../../pages/api/auth/[...nextauth]";


function Top() {

  const { data: session} = useSession();


  return (
    <> 
      <div className={styles.top}>
        <div className={styles.top__container}>
          <div></div>

          <ul className={styles.top__list}>
            <li className={styles.li}>

              
              <Image
                src="/heart.svg"
                width={20}
                height={20}
                alt="heart"
                className={styles.test}
              />
              <Link href="/profile/wishlist">
                <span>Wishlist</span>
              </Link>
            </li>

            <li className={styles.li}>
              <span className={styles.cart}>3</span>
              <Image src="/cart.svg" width={22} height={22} alt="cart" />

              <Link href="/cart">
                <span>Cart</span>
              </Link>
            </li>
               
              {session ? (
                <li className={styles.li}>
                  <div className={styles.flex}>
                    
                    <Image
                      src={session.user.image || avatar}
                      width={64}
                      height={64}
                      alt="avatar"
                    />
                    <span>{session.user.name}</span>
                  </div>
                </li>
              ) : (
                <li className={styles.li}>
                  <div className={styles.flex}>
                    <span>Account</span>
                  </div>
                </li>
              )}
              {userMenuVisible && <UserMenu session={session} />}
            </li>
          </ul>
        </div>
      </div>
    </>
  );
}

export default Top;

export async function getServerSideProps(context) {

  const session = await getServerSession(authOptions)

  return {
    props: {
      session,
    },
  };
}

OSError: [WinError 5] Access is denied: 'c:\\python311\\scripts\\pip.exe' Consider using the `--user` option

I was trying to upgrade my pip version but this error keep coming after vary efforts I used " python.exe -m pip install --upgrade pip" to upgrade my pip and tried to use --user option but it seems to require a permission and which I am unable to resolve.

I tried to go to my C drive and then Python installation folder and after that Properties and Security and from there I tried to change the Authentication to "Full control" but no luck as such. What should I do?

after using login(request) to create a session in my login view, the session is lost when i access another view in Django

I'm trying to create an API client server model in Django, but every time i log into a user in my login view. When i need to use the information and session from the login, for some reason it gets reset to AnonymousUser in my stories view. And if i use @login required it just redirects me to the login page as if i didn't just authorize and create a session with the user moments ago. Here is my views.py:

@csrf_exempt
def login_view(request):
    if request.method == 'POST':
        payload = request.POST

        # Validate payload keys
        if 'Username' not in payload or 'Password' not in payload:
            return JsonResponse({'message': 'Username or password missing'}, status=400)

        username = payload['Username']
        password = payload['Password']
        
        user = authenticate(request, username=username, password=password)

        if user is not None:
            # Log the user in and store session data
            login(request, user)
            
            return JsonResponse({'message': 'Login successful', 'user_id':user.id}, status=200)
        else:
            # Incorrect username or password
            return JsonResponse({'message': 'Incorrect username or password'}, status=401)
        

@csrf_exempt
@login_required
def stories(request):
    if request.method == 'POST':
        if request.user.is_authenticated:
            print(request.user.username)
            # Retrieve data from the POST request
            headline = request.POST.get('Headline')
            category = request.POST.get('Category')
            region = request.POST.get('Region')
            details = request.POST.get('Details')

            # Get the current user's author object
            author = Author.objects.get(user=request.user.id)
            author_name = author.name

            # Create a new story object
            new_story = Stories.objects.create(
                headline=headline,
                story_cat=category,
                story_region=region,
                autho_name=author,
                story_date=timezone.now(),
                story_details=details
            )

            return JsonResponse({'message': 'Story created successfully'}, status=201)
        else:
            return JsonResponse({'message': 'Authentication required'}, status=503)
    else:
        return JsonResponse({'message': 'Method not allowed'}, status=503)

and here is my client handler:

def login():
    global login_status
    
    url = 'http://127.0.0.1:8000/api/login/'
    username = input("Enter username: ")
    password = input("Enter password: ")
    payload = {'Username': username, 'Password': password}

    # Make sure to set 'Content-Type' header to 'application/x-www-form-urlencoded'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}

    # Encode the payload as 'application/x-www-form-urlencoded'
    data = '&'.join([f"{key}={value}" for key, value in payload.items()])
    
    r = requests.post(url, data=data, headers=headers)
    response_data = r.json()

    if r.status_code == 200:
        print("Login successful")
        login_status = True
    else:
        print("Login failed:", response_data.get('message'))
def Post_story():
    global login_status

    url = 'http://127.0.0.1:8000/api/stories/'
    headline = input("Enter a headline: ")
    category = input("Enter a category(pol, art, tech, trivia): ")
    region = input("Enter a region(uk, eu, w): ")
    details = input("Enter story details: ")
    payload = {'Headline': headline, 'Category': category, 'Region': region, 'Details': details}

    # Make sure to set 'Content-Type' header to 'application/x-www-form-urlencoded'
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}

    # Encode the payload as 'application/x-www-form-urlencoded'
    data = '&'.join([f"{key}={value}" for key, value in payload.items()])
    
    r = requests.post(url, data=data, headers=headers)
    response_data = r.json()


    if r.status_code == 201:
        print("Post successful")
    else:
        print("Post failed:", response_data.get('message'))

while True:
    if login_status == False:
        command = input("Enter command (login/exit): ").strip()
        if command == "login":
            login()
        elif command == "exit":
            break 
        else:
            print("Invalid command. Please enter 'login', or 'exit'.")    
    
    if login_status == True:
        command = input("Enter command (post/logout/exit): ").strip()
        if command == "post":
            Post_story()
        elif command == "logout":
            logout()
        elif command == "exit":
            break
        else:
            print("Invalid command. Please enter 'post', 'logout', or 'exit'.")    

and if needed my url.py:

from django.urls import path

from . import views

urlpatterns = [
    # ex: /api/
    path("", views.index, name="index"),
    # ex: /api/login
    path("login/", views.login_view, name="login"),
    # ex: /api/logout
    path("logout/", views.logout_view, name="logout"),
    # ex: /api/stories
    path("stories/", views.stories, name="stories"),
]

I have tried messing with my settings.py, tried manually storing session data with request.session but for some reason the second the view changes, the session is lost. I want to avoid using external libraries for session storage, but ive tried clearing sessions in the console as well.

Installed Laravel sanctum but faced an error during creating token

I installed the Laravel sanctum for creating token, but when I am going to create a API token I faced this error:

Error: Class 'App\Models\Passport\PersonalAccessToken' not found in file E:\Laravel-WebApps\Vue-CMS\vendor\laravel\sanctum\src\Guard.php on line 63

Even I did not install the Laravel passport.

User Model

use Laravel\Sanctum\HasApiTokens;
use Notifiable, HasApiTokens;

API Route

Route::middleware('auth:sanctum')->get('/user-profile', 'Admin\API\UserController@profile');

User Controller

public function profile(Request $request)
    {
        return auth('sanctum')->user();
        or 
        return auth('api')->user();
    }

auth.php

'api' => [
            'driver' => 'token',
            'provider' => 'users',
            'hash' => false,
        ],

Profile Vue

 mounted(){
            axios.get('/api/user-profile')
            .then( response => {
                console.log( response );
            })
            .catch( error => {
                console.log( error );
            } )
        }

composer.json

{
    "name": "laravel/laravel",
    "type": "project",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "require": {
        "php": "^7.2.5|^8.0",
        "fideloper/proxy": "^4.4",
        "fruitcake/laravel-cors": "^2.0",
        "guzzlehttp/guzzle": "^6.3.1|^7.0.1",
        "laravel/framework": "^7.29",
        "laravel/sanctum": "^2.8",
        "laravel/tinker": "^2.5",
        "laravel/ui": "2.4"
    },
    "require-dev": {
        "facade/ignition": "^2.0",
        "fakerphp/faker": "^1.9.1",
        "mockery/mockery": "^1.3.1",
        "nunomaduro/collision": "^4.3",
        "phpunit/phpunit": "^8.5.8|^9.3.3"
    },
    "config": {
        "optimize-autoloader": true,
        "preferred-install": "dist",
        "sort-packages": true
    },
    "extra": {
        "laravel": {
            "dont-discover": []
        }
    },
    "autoload": {
        "psr-4": {
            "App\\": "app/"
        },
        "classmap": [
            "database/seeds",
            "database/factories"
        ]
    },
    "autoload-dev": {
        "psr-4": {
            "Tests\\": "tests/"
        }
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "scripts": {
        "post-autoload-dump": [
            "Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
            "@php artisan package:discover --ansi"
        ],
        "post-root-package-install": [
            "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
        ],
        "post-create-project-cmd": [
            "@php artisan key:generate --ansi"
        ]
    }
}

AppServiceProvider

public function boot()
    {
        Sanctum::usePersonalAccessTokenModel(PersonalAccessToken::class);
    }

In the console, it always returns unauthenticated

And when I am going to create API token using tinker it throws this above error.

Azure Function App authentication using Azure App Service "Easy Auth"

I have an Azure Function App for GPG encryption/singing and decryption/verification. This is invoked by Azure Data Factory pipelines to perform GPG operations before subsequent SFTP activities.

For authentication to the Function App (from ADF), I'm currently using Function App keys (or could switch to Function Keys easily enough for finer granularity) and this works well, but should I be using AAD? a.k.a. Easy Auth with the App Service Plan

If so, does anyone have some example Terraform scripts for how to do this. There's quite a few auth settings to configure and I haven't come across a simple tutorial/example for this. I'm almost thinking that using Function App keys is easier and probably good enough. Thoughts?

Call to undefined method markEmailAsVerified()

I'm stuck with this error in laravel, What I want is to verify the email address once they receive the email notification. But everytime I click the link on the email notification it has an error: " Call to undefined method App\Models\Businessuser::markEmailAsVerified()

Can somebody Help me? I've installed auth package, but Im new in using this, and I havent tried this on my codes. Just would like to know if theres something to do with the auth.

error message this is for the verify controller

<?php

namespace App\Http\Controllers;
use App\Models\Businessuser;
use Illuminate\Http\Request;
use Illuminate\Auth\Notifications\VerifyEmail;
use Illuminate\Foundation\Auth;

class VerifyemailController extends Controller
{
    public function verify($businessuser_id, Request $request)
    {
        if(!$request->hasValidSignature()){
            return response()->json(["msg"=>'Invalid/Expired url provided'], 401);
        }

        $bususer = Businessuser::find($request->route('id'));

         if($bususer->markEmailAsVerified()){
            return response()->json(["status"=>200, "msg"=>'Verified']);
        }
     
    }
}

Register Controller

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Businessuser;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use App\Mail\Email;
use App\Mail\EmailNotification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;


class RegisterController extends Controller
{
    public function register(Request $request){
       //return view('register');


      $validateEmail = request()->validate([
                'email' => 'required|email|unique:businessusers',
        ]);


      $bususer = new Businessuser;
      $bususer->busname = $request->input('busname');
      $bususer->province = $request->input('province');
      $bususer->city = $request->input('city');
      $bususer->barangay = $request->input('barangay');
      $bususer->street = $request->input('street');

    
      $bususer->tinum = $request->input('tinum');
      $bususer->firstname = $request->input('firstname');
      $bususer->lastname = $request->input('lastname');
      $bususer->middleinitial = $request->input('middleinitial');
      
      $bususer->mobile = $request->input('mobile');
      $bususer->email = $request->input('email');   

      $bususer->save();

      Mail::to($bususer->email)->send(new EmailNotification($bususer));

       return $bususer;

    }

    public function testconnection(){
        
    }
}

Business User Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Concerns\HasTimestamps;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Contracts\Auth\MustVerifyEmail;


class Businessuser extends Model
{
    use HasFactory;

     /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */

     protected $table = 'businessusers';
     protected $primaryKey = 'id';
     protected $fillable = [
        'busname',
        'province',
        'city',
        'barangay',
        'street',
        'tinum',
        'firstname',
        'lastname',
        'middleinitial',
        'owner',
        'mobile',
        'email',
     ];

     /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */

   // const CREATED_AT = 'created_at';
    /* const UPDATED_AT = null;*/

  

    protected $hidden = [
        'password',
        'remember_token',
    ];

     

     protected $casts = [
        'email_verified_at' => 'datetime',
    ];

 
}

api/route

<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RegisterController;
use App\Http\Controllers\VerifyemailController;


Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Route::post('register', [RegisterController::class, 'register']);
Route::get('testconnection', [RegisterController::class, 'testconnection']);
Route::get('email/verify/{id}', [VerifyemailController::class, 'verify'])->name('verification.verify');

Email Html file

<h1>Congratulations! </h1>
<h1>Were Welcoming you from registering in Love Laguna</h1>
<h1>User {{$bususer->id}}</h1>
<h1>Business {{$bususer->busname}} </h1>
<h1>Click on the link to verify the email address<a href="{{URL::temporarySignedRoute('verification.verify', now()->addMinutes(30), ['id' => $bususer->id]) }}"> Verify Email</a></h1>

Routes

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\RegisterController;
use Illuminate\Support\Facades\Auth;

Route::get('/', function () {
    return view('welcome');
});


Route::get('/register', [RegisterController::class, 'register'])->name('register');

How do I combine firebase authentication and realtime Database?

Good day All

I am building a simple project that uses the esp32 to collect sensor data and then save it to a Realtime Database on Firebase, I then retrieve the data in Android Studio to show to the user.

My problem is that my app's authentication works fine and logs in as expected and I can also create new users. But my ESP data is stored in the Realtime Database. How do I combine the authentication and the Realtime Database so each user has his own data?

I need a table something like this for each user that registered. User -ESP32
-Sensor1 -Data -Data -Sensor2 -Data -Data -Sensor3 -Data -Data

Or do I misunderstand how this is supposed to work?

How can I implement OAuth in a desktop app?

I would like to write an email client that would send and receive mail on the Linux desktop. This is to be a local app, like Thunderbird, or mutt, not an online service. I would like it to be able to work through GMail, which requires OAuth authentication. All documentation I have been able to find on that or other Google APIs assumes that the implementation will be running on a server, where it can store client_id and secret in a place not accessible to the user. My app will be installed and run locally, and will be open source, so there is no way to store these credentials in secret.

Google goes out of its way to emphasize that the API key, the OAuth client_id, and its secret must not be published. Because of this, a few other email clients that have implemented OAuth support require each user to create his own API key and OAuth credentials. For an average user, the process for doing this is too complicated, and there is no way I am going to make them do it.

So the question is this: how can OAuth be done from a desktop app without requiring users to create API keys and credentials?

Firebase: Hostname match not found (auth/captcha-check-failed). However vercel domain name is present in firebase console

When implementing signInWithPhoneNumber using firebase in react 18 application, I kept facing the same error as mentioned Hostname match not found (auth/captcha-check-failed) and I have added my domain in the authorized domains in firebase console.

I have done this with before with signInWithPopup and it has worked flawlessly, Now I have observed that the domain I am facing issue with is with vercel custom domain https://**-******-****-**-**-9cf5b3-*********.vercel.app/ so I have added the domain name vercel.app in the authorized section

Is there something I am missing?

I have added my domain in the authorized domains in firebase console. I expected when I added the domain, it should have worked as shown in documentation Worked with signInWithPopup but not working with signInWithPhoneNumber Works when adding full domain

โŒ
โŒ