You're writing Apex code that's exposed as REST service, with @RestResource
etc? In that code you don't have to worry about authorisation. If the code runs - Salesforce already validated the session id, found the user, verified that this user has access to this class, that the session id was created with good OAuth2 scope etc.
If you're talking about external application that logs in and calls this custom service - well. You'd need to pick right OAuth2 flow to log the user in (you tagged it communities so "username password flow" for example won't work, you'll likely need "web server flow" or "user agent flow". For example this one returns "issued at" but it doesn't mean much, it doesn't automatically mean that session is valid for X hours. As user keeps interacting with the app the session timeout gets reset; on other hand an IP change could kick you out, admin could suspect hacking and kick you out using Setup -> Session Management...
Best you can do is code defensively. Make a request with last known session id you got, if it returns something like 401 Unauthorised
- call login procedure (if you're really doing it in community - redirect them to login screen with callback url pointing back to the action you wanted to do), wait for user to complete login and retry the operation? There are many reasons you might be getting authorisation failure, check https://stackoverflow.com/a/72172355/313628 for start.