nucleusoauth
v1.1.1
Published
sign in using nucleus auth for PSG students
Downloads
3
Readme
Nucleus Oauth
The Auth tool for Students
Use the NucleusAuth protocol for authentication and authorization. This package supports common OAuth scenarios such as those for web server, client-side, installed, and limited-input device applications.
To begin, obtain OAuth credentials from the nucleus Console. Then your client application requests an access token from the Nucleus Authorization Server, extracts a token from the response, and sends the token to the Nucleus API that you want to access.
- Easy sign in option
- Retains cookies and gives a single sign on option using pre existing cookies
- ✨LOGIN Magic ✨
This module provides Express middleware for validating JWTs (JSON Web Tokens) through the jsonwebtoken module. The decoded JWT payload is available on the request object.
Install
$ npm install nucleusoauth
Usage
Basic usage using an HS256 secret:
var jwt = require("express-jwt");
app.get(
"/protected",
jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }),
function (req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
}
);
The decoded JWT payload is available on the request via the user
property.
Required Parameters
The algorithms
parameter is required to prevent potential downgrade attacks when providing third party libraries as secrets.
:warning: Do not mix symmetric and asymmetric (ie HS256/RS256) algorithms: Mixing algorithms without further validation can potentially result in downgrade vulnerabilities.
jwt({
secret: "shhhhhhared-secret",
algorithms: ["HS256"],
//algorithms: ['RS256']
});
If the JWT has an expiration (
exp
), it will be checked.
If you are using a base64 URL-encoded secret, pass a Buffer
with base64
encoding as the secret instead of a string:
jwt({
secret: Buffer.from("shhhhhhared-secret", "base64"),
algorithms: ["RS256"],
});
Optionally you can make some paths unprotected as follows:
app.use(
jwt({ secret: "shhhhhhared-secret", algorithms: ["HS256"] }).unless({
path: ["/token"],
})
);
Use function nucleus_auth to use the API These params must be included in the request body:
- Username
- Password
- Student/tutor
await axios
.post("https://nucleus.amcspsgtech.in/oauth", request_body)
.then(async (response) => {
if (response.status === 200 && response.data.status === "Success") {
const cookies = response.headers["set-cookie"];
const data = {
role: req.body.role,
id: req.body.userID,
cookies: cookies,
};
const userData = await userHelper.fetch_user(data);
const response_data = {
rollNo: userData.id,
firstName: userData.firstName,
lastName: userData.lastName,
email: userData.email,
classId: userData.classId,
role: "student",
};
const token = jsonwebtoken.sign(response_data, process.env.JWT_SECRET);
res.cookie("bonafide_token", token);
res.status(200).json({
success: true,
data: response_data,
});
}
})
.catch(() => {
res.clearCookie("bonafide_token");
res.status(401).json({
success: false,
});
});
Customizing Token Location
A custom function for extracting the token from a request can be specified with
the getToken
option. This is useful if you need to pass the token through a
query parameter or a cookie. You can throw an error in this function and it will
be handled by express-jwt
.
app.use(
jwt({
secret: "hello world !",
algorithms: ["HS256"],
credentialsRequired: false,
getToken: function fromHeaderOrQuerystring(req) {
if (
req.headers.authorization &&
req.headers.authorization.split(" ")[0] === "Bearer"
) {
return req.headers.authorization.split(" ")[1];
} else if (req.query && req.query.token) {
return req.query.token;
}
return null;
},
})
);
For example, if the secret varies based on the JWT issuer:
var jwt = require("express-jwt");
var data = require("./data");
var utilities = require("./utilities");
var secretCallback = function (req, payload, done) {
var issuer = payload.iss;
data.getTenantByIdentifier(issuer, function (err, tenant) {
if (err) {
return done(err);
}
if (!tenant) {
return done(new Error("missing_secret"));
}
var secret = utilities.decrypt(tenant.secret);
done(null, secret);
});
};
app.get(
"/protected",
jwt({ secret: secretCallback, algorithms: ["HS256"] }),
function (req, res) {
if (!req.user.admin) return res.sendStatus(401);
res.sendStatus(200);
}
);
Error handling
The default behavior is to throw an error when the token is invalid, so you can add your custom logic to manage unauthorized access as follows:
app.use(function (err, req, res, next) {
if (err.name === "UnauthorizedError") {
res.status(401).send("invalid token...");
}
});
You might want to use this module to identify registered users while still providing access to unregistered users. You can do this by using the option credentialsRequired
:
app.use(
jwt({
secret: "hello world !",
algorithms: ["HS256"],
credentialsRequired: false,
})
);
Tests
$ npm install
$ npm test
Development
Want to contribute? Great! Go to the github and put in a merge rqeuest
License
MIT
Free Software, Hell Yeah!