Auth provider unhandled error
Description / Steps to reproduce / Feature proposal
Following @loopback/authentication example I'm getting a situation where calling cb there doesn't seem to be a graceful return of the error. It returns a standard 500 with no further explication.
Unhandled error in POST /vendors/login: 500 InternalServerError: Error: Email not found. at BasicStrategy.strategy.error (D:\Work\monotto\monotto-ts\node_modules@loopback\authentication\dist\strategy-adapter.js:51:24) at verified (D:\Work\monotto\monotto-ts\node_modules\passport-http\lib\passport-http\strategies\basic.js:89:28) at AuthStrategyProvider.verify (D:\Work\monotto\monotto-ts\dist\src\providers\auth-strategy.provider.js:48:17) at process._tickCallback (internal/process/next_tick.js:68:7)
I'm sure this is just some small oversight into the setup.
auth-strategy.provider.ts
import {Provider, inject, ValueOrPromise, Setter, Getter} from "@loopback/context";
import {Strategy} from "passport";
import {
AuthenticationBindings,
AuthenticationMetadata,
UserProfile,
AuthenticationStrategy
} from "@loopback/authentication";
import {BasicStrategy} from "passport-http";
import {repository} from "@loopback/repository";
import {VendorsRepository} from "../repositories";
import Encryption from "../libs/encryption.helper";
import {isNullOrUndefined} from "util";
import {HttpErrors} from "@loopback/rest";`
export class AuthStrategyProvider implements Provider<Strategy | undefined> {
constructor(
@inject(AuthenticationBindings.METADATA)
private metadata: AuthenticationMetadata,
@repository(VendorsRepository)
public vendorsRepository: VendorsRepository,
@inject.setter(AuthenticationBindings.CURRENT_USER)
readonly setCurrentUser: Setter<UserProfile>
) {}
async value() {
// The function was not decorated, so we should not attempt authentication
if (!this.metadata) {
return undefined;
}
const name = this.metadata.strategy;
if (name === 'BasicStrategy') {
const data = await new BasicStrategy(this.verify.bind(this));
return data;
} else {
return Promise.reject(`The strategy ${name} is not available.`);
}
}
async verify(
username: string,
password: string,
cb: (err: Error | null, user?: UserProfile | false) => void
) {
try {
let vendor = await this.vendorsRepository.findOne({
where: {email: username}
});
if (vendor == null) {
cb(new Error('Email not found.'), false);
} else {
if (isNullOrUndefined(vendor.passwordDigest)) {
cb(new Error('Vendor does not have password.'), false);
} else {
if (
await !Encryption.CheckPassword(password, vendor.passwordDigest)
) {
cb(new Error('Password did not match.'), false);
}
const userProfile: UserProfile = {
id: vendor.id.toString(),
name: vendor.name,
email: vendor.email
};
this.setCurrentUser(userProfile);
cb(null, userProfile);
}
}
} catch (e) {
cb(e, false);
}
}
}
Current Behavior
Fails gracefully, but does not return more information about what went wrong.
Expected Behavior
Fails gracefully and returns what went wrong during authentication.
Feature Proposal
Additional steps to resolve the situation is added to documentation @loopback/authentication or provide clarity on particular situations that may occur.
@emonddr @jannyHou , could you PTAL? Thanks.
Is it not reporting the email is not found?
InternalServerError: Error: Email not found.
On Tue, 23 Apr 2019, 19:18 Diana Lau, [email protected] wrote:
@emonddr https://github.com/emonddr @jannyHou https://github.com/jannyHou , could you PTAL? Thanks.
— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/strongloop/loopback-next/issues/2786#issuecomment-485917503, or mute the thread https://github.com/notifications/unsubscribe-auth/AAU36CIBXR3LP6NPRGRQW7TPR5HJBANCNFSM4HH3YTXA .
@dougal83 this is the response I'm getting
{
"error": {
"statusCode": 500,
"message": "Internal Server Error"
}
}
To me it seems that the error is not being handled. Since it would be weird that 500 is the default error code. It seems that should be some configuration step I missed to handle error.
@joshuaanthonydeleon I guess it's secure error handling, maybe there is a debug flag like in LB3? https://loopback.io/doc/en/lb3/Using-strong-error-handler.html
You could try to catch the error in controller and output in console in the meantime?
@dougal83 I do have error catching in the controller. Debugging never actually hits the controller. It looks like there is some other error handling taking care of this, but I can't establish where that is and how it needs to be configured.
controller.ts
@authenticate('BasicStrategy')
async getVendorAccessToken(): Promise<VendorToken> {
try {
let vendor = await this.vendorsRepository.findOne({
where: {email: this.user.email},
});
if (isNullOrUndefined(vendor)) {
throw new Error(`User could not be found`);
}
return {Token: vendor.token} as VendorToken;
} catch (e) {
throw new HttpErrors.BadRequest(e.message);
}
}
Fair enough. I guess we need to see the rest of the code where authentication is implemented.
Make sure you're using an up to date @loopback-cli too if you haven't already checked that.
On Thu, 25 Apr 2019, 19:48 joshuaanthonydeleon, [email protected] wrote:
@dougal83 https://github.com/dougal83 I do have error catching in the controller. Debugging never actually hits the controller. It looks like there is some other error handling taking care of this, but I can't establish where that is and how it needs to be configured. controller.ts
@authenticate('BasicStrategy') async getVendorAccessToken(): Promise
{ try { let vendor = await this.vendorsRepository.findOne({ where: {email: this.user.email}, }); if (isNullOrUndefined(vendor)) { throw new Error(`User could not be found`); } return {Token: vendor.token} as VendorToken; } catch (e) { throw new HttpErrors.BadRequest(e.message); }}
— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/strongloop/loopback-next/issues/2786#issuecomment-486793933, or mute the thread https://github.com/notifications/unsubscribe-auth/AAU36CJFQ2Q3BLYV5GMGSX3PSH4IRANCNFSM4HH3YTXA .
A couple of suggestions:
-
Instead of an
Error(...), throw anHttpErrors.Unauthorized(...)from your AuthProvider.Standard errors tend to become 500 in the response, whereas HttpErrors make it back to the client. (That's true for controllers anyway.)
-
Take a look at the bottom of
sequence.ts. Play with the error handling there:} catch (err) { // The standard error message from passport's BasicStrategy is not very helpful. // Let's improve it. if (err.name === 'UnauthorizedError') { console.warn(`[sequence.ts] !! Auth error for '${context.request.path}':`, err); err.message = `You must be authenticated to use this route (${err.message})`; } this.reject(context, err); }We had an old version of Loopback 4. We found that the some of the errors that reached
sequence.tswere uninformative, but at least we could set a "friendly" message for the client.
By the way, off topic but for anyone interested, we log unexpected errors in production like this:
const httpError = err instanceof HttpError && <HttpError>err;
const recordError = httpError
? httpError.statusCode >= 500 /* || httpError.statusCode === 424 */
: true;
if (recordError) {
this.recordError(err, context); // Implement this yourself, save to DB or to log
}
@joshuaanthonydeleon @dougal83 @joeytwiddle sorry for joining the discussion late. The best practive for the auth error handling in the sequence has changed, and the auth strategy resolver(provider) is now refactored to be an extension point.
See documentation https://loopback.io/doc/en/lb4/Loopback-component-authentication.html about ho w to use @loopback/[email protected] system.
The error handling relevant parts are:
- In the strategy class, you throw the error with proper error code, see this section.
- You can try specify the error code in the controller as well.
- In the sequence, the error is processed according to its code, see this section
Let me know if you still have questions :)
Besides the links that @jannyHou provided above, the original README.md link you provided at the beginning of the discussion, https://github.com/strongloop/loopback-next/blob/master/packages/authentication/README.md, has also been revised.
I will close this issue for now. But please re-open if you still need help. Thank you.