Auth data is not accessible in AppServiceProvider Laravel 5.5 - authentication

namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Schema;
use App\Classes\DynamicMenu;
use App\Http\Controllers\WelcomeController;
use Auth;
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
dd(Auth::user());
}
}
This returns 'null' for me, but other controllers returns user details. How to fix this?

Why?
It is because, when the boot method of a service provider is being called, the user is not yet authenticated.
Solution:
I guess you are trying to use View Composers
From the documentation:
So, what if we need to register a view composer within our service
provider? This should be done within the boot method. This method is
called after all other service providers have been registered, meaning
you have access to all other services that have been registered by the
framework:
So you can use the following:
public function boot(Guard $auth) {
view()->composer('*', function($view) use ($auth) {
$user = $auth->user();
// other application logic...
$view->with('currentUser', $user);
});
}

Related

Phalcon Controller $this->session and Phalcon\Session\Manager()

I'm using Phalcon v.4 and I have seen that are two ways to create the session inside a controller:
class PostController extends Controller
{
public function postAction(): Response
{
$session = new Phalcon\Session\Manager()
}
}
or
class PostController extends Controller
{
public function postAction(): Response
{
$this->session;
}
}
I have seen that the methods are the same, but I'm not able to understand the different and which is better to use.
if you created your project using phalcon's cli devtools then the session service would be created by default in app/config/services.php
that being said in your controller when you access the instance's property session aka $this->session this would look for a service called session and by default it would setup session using file adapter and starts it and $this->session would return an instance of Phalcon\Session\Manager

Auth user check role is not working in serviceProvider Laravel

when i use (auth()->user()->hasRole('User')) or (Auth::user()->hasRole('User')) in service provider it gives me this error:
Call to a member function hasRole() on null
I use spatie library and include this in my serviceProvider file:
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Models\Role;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Traits\HasRoles;
and the code I write is:
if (Auth::user()->hasRole('User')) {
$count = Complaint::where('user_id', auth()->user()->id)->where('is_deleted', 'not_deleted')->get()->count();
} else {
$count = Complaint::where('status', '!=', null)->where('is_deleted', 'not_deleted')->get()->count();
}
Unfortunately, the Laravel session is initialized in the middleware so you can't access Auth::... from a Service Provider because they are executed before the middleware in the request lifecycle.

Is there a way to get a non-null Principal/Authentication using Spring Security with anonymous access?

I'm using Spring Security, and want to be able to run with a "local" profile with security off. I can do this by using a profile-controlled WebSecurityConfigurerAdapter which allows anonymous access, but the problem is that any Principal or Authentication arguments to controller methods are null.
The way I've solved this before is by passing the arguments through an adapter, which has a non-local pass-through implementation and a "local"-profile implementation that substitutes a configured value:
#GetMapping()
public ResponseEntity<List<Thing>> getThings(Principal principal) {
Principal myPrincipal = securityAdapter.principal(principal);
...
}
But this feels really clunky. Is there some way to configure Spring Security to make the substitution so that I can keep the code clean?
Unfortunately it is a SpringSecurity feature: the AnonymousAuthenticationToken is not injected in controller methods. I could find some references for that in this issue.
A possible workaround (from above issue) is to inject a custom trust resolver that pretends that the AnonymousAuthenticationToken is not anonymous...
#Bean
public AuthenticationTrustResolver trustResolver() {
return new AuthenticationTrustResolver() {
#Override
public boolean isRememberMe(final Authentication authentication) {
return false;
}
#Override
public boolean isAnonymous(final Authentication authentication) {
return false;
}
};
}
Rather ugly, but as it is intended to run in a profile where anonymous authentication is expected to be valid, it could be enough.

Is there a way to specify which IAuthProvider to use for authentication on a particular Service class?

I have two services within the same project:
[Authenticate]
public class OnlyDoesBasicAuth : Service
{
}
[Authenticate]
public class OnlyDoesJwtAuth : Service
{
}
//AppHost
public override void Configure(Container container)
{
Plugins.Add(new AuthFeature(
() => new AuthUserSession(),
new IAuthProvider[]
{
new BasicAuthProvider(AppSettings),
new JwtAuthProvider(AppSettings)
}
)
{
HtmlRedirect = null
});
}
The way this is set up, I can get into both services using Basic Authentication or with a valid Bearer token. I'd prefer to have it so that only one service can do one means of authentication. Is there a way to specify with provider to use on authentication?
I'm at a loss on how to approach this. I was thinking that maybe there was a way via global request filter or something to that effect, but maybe that's not the way to go. I could split the project into two projects, which will definitely work, but it's not the way I want to approach it.
I'm just looking for a way for the OnlyDoesBasicAuth to only use the BasicAuthProvider on authentication and OnlyDoesJwtAuth to only use the JwtAuthProvider within the same project. Any and all suggestions will be greatly appreciated.
Thanks in advance.
Typically once you're authenticated using any of the Auth Providers you're considered as an Authenticated User everywhere in ServiceStack.
You can restrict access so that a Service needs to be Authenticated with by specifying the AuthProvider name in the [Authenticate] attribute, e.g:
[Authenticate(BasicAuthProvider.Name)]
public class OnlyDoesBasicAuth : Service
{
}
[Authenticate(JwtAuthProvider.Name)]
public class OnlyDoesJwtAuth : Service
{
}
Alternatively you can validate within your Service that they need to be authenticated with a specific Auth Provider, e.g:
if (SessionAs<AuthUserSession>().AuthProvider != JwtAuthProvider.Name)
throw HttpError.Forbidden("JWT Required");

Laravel: Dependency Inject Auth

How do I dependency inject Auth in Laravel?
Like this:
public function __construct(Auth $auth)
{
$this->auth = $auth;
}
If I do that then this does not work:
$user_type = Auth::user()->user_type;
You should type hint Illuminate\Auth\AuthManager:
public function __construct(Illuminate\Auth\AuthManager $auth)
{
$this->auth = $auth;
}
If you want to inject Auth, you actually need to inject this class:
use Illuminate\Contracts\Auth\Guard;
That will resolve everything what you define inside:
config/auth.php
If you want to extend Auth you can do that but only for:
Guard Driver which is Guard Class - it needs to implement Guard or StatefulGuard interface.
Provider which is UserProvider Class - it needs to implement UserProvider interface.
Standard Auth Guard drivers in Laravel / Lumen are:
SessionGuard
TokenGuard
Standard Auth UserProviders are in Laravel / Lumen are:
EloquentUserProvider
DatabaseUserProvider
More about extending Auth you have in official Laravel documentation. See link below:
https://laravel.com/docs/5.0/extending#authentication
This is the code which I have in my controller and it is working like a charm:
public function createToken(Request $request, Guard $guard)
{
// return 'in progress...';
}
Best Practise for extending Auth class is in ServiceProvider boot() method.
Hope this helps!
Cheers.