I want to make if else condition on token if token is null or undefined or "" then it will redirect on event and if token comes from context.get than it will show token exist.
Please check my code but its not working its going to crash every time. Please help me out to get any solution.
function RaiseQuery(agent) {
let token = "";
const infoContext = agent.context.get('info');
token = infoContext.parameters.token;
if (token === null){
agent.setFollowupEvent("Login");
} else {
agent.add("Token Exist");
}
}
Logs:
Thank You
Related
I have a really weird issue,
I have the following flutter code to generate FCM Token for the user upon sign up so I can send them push notification from my backend:
String? fcmToken = await FirebaseMessaging.instance.getToken();
if (fcmToken != null) {
log("FCM Token is not null with value = $fcmToken");
UserAPIService.refreshUserFCMToken(fcmToken);
} else {
log("FCM Token is null"); //Other users weirdly keep getting null
}
This code works on my Android device. But doesn't work on other Android Device users of my app.
However, I am signing my users in with a custom token generated from my nodejs backend.
Here is how I generate the custom token in nodejs
let firebaseCustomToken = await firebase.auth().createCustomToken(apiKey);
And then on the flutter side I have this code:
await FirebaseAuth.instance
.signInWithCustomToken(firebaseCustomToken/*This is sent from the backend immediately after sign up before communicating with firebase*/)
.then((userCredentials)async {
String? fcmToken = await FirebaseMessaging.instance.getToken();
if (fcmToken != null) {
log("FCM Token is not null with value = $fcmToken");
UserAPIService.refreshUserFCMToken(fcmToken);
} else {
log("FCM Token is null"); //Other users weirdly keep getting null
}
}
Please note that I have submitted my release and debug keys already to firebase.
What could be wrong, I can't seem to figure out?
I'm trying to launch a really basic chat app for myself and a few friends and wanted to include a password check upon loading the site by using a prompt + socket.emit:
var username = prompt('password:');
socket.emit('password', password);
I wanted to insert a function that checks their input against whatever I define as the answer. Something like this:
var codeword = prompt('password:', function checkPrompt(password) {
if (prompt.password.length === 0) {
return false;
}
if (password.value !== answer.value) {
return false;
}
return true;
});
But I get ERR_INVALID_ARG_TYPE(name, 'Function', value); once I run the app. How can I implement this?
Sidenote: I know this is super insecure. I'll implement a real password check once I have a DB set up but until then I just wanted a simple placeholder.
prompt is a "blocking" method, so there is no need for a callback. Callbacks are needed when you are uncertain when code within the callback will be executed. This is not the case here. You can work with the returned result in a do...while loop for example.
Dummy example with static password check:
// We will keep the user in the loop until the password is correct...
do {
var password = prompt('Password:');
} while (password !== 'abcd');
// At this point we know the password was correct.
alert('Password was correct!');
Dummy example with dedicated auth method:
function authenticate(username, password) {
if (username == 'john' && password == 'abcd') {
return true;
}
return false;
}
// We will keep the user in the loop until the password is correct...
do {
var username = prompt('Username:');
var password = prompt('Password:');
var loginSuccessful = authenticate(username, password);
} while (!loginSuccessful);
// At this point we know the password was correct.
alert('Password was correct!');
From the security point of view, it only makes sense to have the authentication logic on server-side, so you'll most probably will want to make an AJAX call from within the above authenticate function (using the Fetch API for example or jQuery.post - if you're using jQuery). Then the method would return true or false based on the response of the server-side call.
I have in incoming bearer token that has an incorrect audience. There is enough information in the token via other claims that prove what the audience should be.
I was hoping to fix it up early so that I could still take advantage of the JwtBearerOptions.TokenValidationParameters.ValidateAudience = true;
JwtBearerOptions.TokenValidationParameters.ValidAudiences ={"the right one"};
I can hook the OnTokenValidated event, and rewrite the principal, but that is too late. Earlier in the pipeline the token has been validated and since the audience is wrong, it has already been rejected.
I am able to get around this by using authorization policies, by setting ValidateAudience=false and taking care of this at the controller level. I don't like having to add that [Authorize("the-correct-audience")] attribute to every controller, because someone will miss one.
Another alternative is to introduce a new middleware that works on the identitiy.claims and reject there.
In the end I want to be able to globally reject these tokens the way a validateAudience = true accomplishes, when validateAudience has been taken away from me as a filtering option.
Has anyone done something like this and what other alternatives have you used?
Solution 1: Solve it by introducing a middleware.
NOTE: Don't validate the audience
First hook the following;
```
JwtBearerOptions = options =>{
options.Events = new JwtBearerEvents
{
OnTokenValidated = context =>
{
...
// this will put in the right aud
// replace the entire principal
var appIdentity = new ClaimsIdentity(newClaims);
var claimsPrincipal = new ClaimsPrincipal(appIdentity);
context.Principal = claimsPrincipal;
}
}
}
Introduce this middleware;
I am looking for aud here, but you everything is fair game in the identity.
```
app.UseAuthentication();
app.Use(async (HttpContext context, Func<Task> next) =>
{
//do work before the invoking the rest of the pipeline
if (context.Request.Headers.ContainsKey("x-authScheme") &&
context.Request.Headers.ContainsKey("Authorization") &&
context.User != null)
{
// looking for bearer token stuff.
var claims = context.User.Claims;
var q = from claim in claims
where claim.Type == "aud" && claim.Value == "aggregator_service"
select claim;
if (!q.Any())
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return;
}
}
await next.Invoke(); //let the rest of the pipeline run
//do work after the rest of the pipeline has run
});
```
Hi I am developing web application in Angular 5. I am using azure active directory authentication oauth 2.0 implicit flow for Login. After 1 hour my application redirects to login page because i handled this in code as below.
protected handleError(error, continuation: () => Observable<any>) {
if (error.status == 401) {
this.appContextService.redirectForLogin();
//return Observable.throw(error);
}
else if (error.url && error.url.toLowerCase().includes(this.loginUrl.toLowerCase())) {
return Observable.throw((error.error && error.error.errormessage) ? `session expired (${error.error.errormessage})` : 'session expired');
}
else {
return Observable.throw(error);
}
}
redirectForLogin() {
this.loginRedirectUrl = this.router.url;
this.router.navigate(['']);
this.adalSvc.login();
}
After one hour i want user not to enter password again. I want to implement refresh token mechanism here. Can someone help me to fix this. Thank you.
I have a website with a lot of registered users and many of them have chosen the "remember me" option in login.
I used to use the default login behavior for asp.net core but I installed openiddict and added the following option to services.addIdentity:
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.FromResult(0);
}
};
}
The full method in startup.cs now reads the following:
services.AddIdentity<ApplicationUser, IdentityRole>(options =>
{
options.Password.RequireDigit = false;
options.Password.RequireLowercase = false;
options.Password.RequireNonAlphanumeric = false;
options.Password.RequireUppercase = false;
options.Password.RequiredLength = 6;
options.Cookies.ApplicationCookie.CookieDomain = "mydomain.com";
options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromDays(1);
options.Lockout.MaxFailedAccessAttempts = 10;
options.Cookies.ApplicationCookie.Events = new CookieAuthenticationEvents
{
OnRedirectToLogin = context =>
{
if (context.Request.Path.StartsWithSegments("/api") && context.Response.StatusCode == (int)HttpStatusCode.Unauthorized)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
else
{
context.Response.Redirect(context.RedirectUri);
}
return Task.FromResult(0);
}
};
The problem now that if a previously registered and logged-in user tried to open pages that require authentication he gets an error message. Unfortunately I'm unable to determine that error because appinsights and "development" mode doesn't work for me in Azure. if users go to login page without logging out they get a blank page after logging in.
The only way to solve it is to logout and login again.
Because I have a lot of users I'm trying to find a way to clear all sessions or previous cookies.
Any suggestions on this or comments about my code above is strongly appreciated.
Thank you
Update: I tried try catch and the error happened. Apparently there is no exception... This is very weird.
Update2: This is not account related. A friend of mine is facing the error and gave me his credentials. When I tried it works, perhaps it's a cookie problem?