I am having an issue with OTHER USERS using my app.
Right now my app has a login button that sends the user to the yahoo API Request_Token here's the code.
var main = angular.module("main", ["firebase", "ngRoute"]);
main.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'partials/login.html',
controller: 'loginController'
})
.when('/:token', {
templateUrl: 'partials/callback.html',
controller: 'welcomeController'
})
.otherwise(
{redirectTo: '/'
});
}]);
main.controller("loginController", function ($routeParams, $scope) {
$scope.login = function () {
var clientID = "[redacted]";
window.location.href = "https://api.login.yahoo.com/oauth2/request_auth?client_id=" + clientID + "&redirect_uri=http://www.acleanpairofshorts.com/fantasy&response_type=token&language=en-us";
}
});
The user SHOULD BE redirected to the callback.html view.. AND THIS WORKS FOR ME... however, my friends are telling me that they are being redirected back to the login view and there is no /access_token appended to the URL.. so this leads me to believe that Yahoo is not providing access tokens to anyone but me... does anyone know if they can spot anything wrong with my code?
Related
I am implementing NextAuth authentication and there is something that remains unclear for me. I explain.
To perform authentication with CredentialsProviders and signIn() well (means avoid the session's status unauthenticated during the first attempt). The doc gives a partial solution which is:
You can use useSession() in a way that makes sure you always have a valid session
I use the default behavior to satisfy this advice by implementing my signIn() method like this
const login_user = async () => {
const response = await signIn("Credentials", {
redirect: false,
username: username,
password: password,
});
if (response?.error) {
setError(response.error);
} else {
setError(null);
}
//If user signed successfully we redirect to the dashboard page
if (response.url && response.ok === true) {
router.push("/dashboard/general");
}
};
and it works well.
Now always in the doc, they say that we may add callbackUrl to signIn() which is the url where you want to redirect the user after successful sign in.
I configure my redirect callback in [...nextauth].ts file like this
redirect: async ({ url, baseUrl }) => {
return url.startsWith(baseUrl)
? Promise.resolve(url)
: Promise.resolve(baseUrl);
},
and modify signIn() method by adding it callbackUrl like below in the react component.
const login_user = async () => {
const response = await signIn("Credentials", {
redirect: false,
username: username,
password: password,
callbackUrl: "/dashboard/general",
});
if (response?.error) {
setError(response.error);
} else {
setError(null);
}
};
But when a user sign in, he is not redirected.
My question is:
What is the role of callbackUrl at that place if after the sign in or first attempt of sign in it cannot redirect the user to the specified callbackUrl?
I know the importance of callbackUrl about security against attacker)
May be I do not understand well that notion.
Can someone explains it?
I'm working on a Rails/React/Redux app using Devise for user authentication. There's something fishy going on somewhere in between my login function and my receiveCurrentUser action where the currentUser becomes changed to an HTML string of the entire document. Here's what happens:
I first dispatch this login function:
export const login = (user) => (dispatch) => {
debugger
return SessionAPIUtil.login(user)
.then(currentUser => {
dispatch(receiveCurrentUser(currentUser));
return currentUser;
},
errors => {
dispatch(receiveSessionErrors(errors.responseJSON));
return errors;
});
};
Putting in a debugger I saw that my user was what it should be:
{username: "test_user", password: "password123"}
A debugger in my login util function (ajax call) still has user as what it should be.
export const login = user => {
debugger
return $.ajax({
method: 'POST',
url: '/users/sign_in',
data: { user }
});
};
However, when it returns from the ajax call to the ".then(..." of the first login function and we enter the receiveCurrentUser:
export const receiveCurrentUser = (currentUser) => {
debugger
return {
type: RECEIVE_CURRENT_USER,
currentUser
};
};
a debugger reveals that currentUser is an HTML string of the document:
Any insight or advice would be greatly appreciated!
I have a Umbraco website that has google sign in button configured as follows:
At the top of the page (inside the header section) I have the scripts for calling google API:
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: '<myapp client Id>.apps.googleusercontent.com',
// Scopes to request in addition to 'profile' and 'email'
redirect_uri: 'http://localhost:40136/umbraco/Surface/AuthSurface/GoogleAuthrizedUser',
scope: 'profile email'
});
});
}
</script>
In the body section of the code I have the google button setup and associated click function:
<script>
function onSignIn(authResult) {
if (authResult['code']) {
var authCode = authResult['code'];
console.log("Authorization Code: " + authCode);
$.post("/umbraco/Surface/AuthSurface/GoogleAuthrizedUser", { code: authCode })
.done(function(msg) {
// Success settings
})
.fail(function(xhr, status, error) {
});
} else {
//authResult['code'] is null
//handle the error message.
}
};
</script>
Controller code that handles the call back on the server end:
public class AuthSurfaceController : SurfaceController
{
public ActionResult GoogleAuthrizedUser()
{
string AuthCode = HttpContext.Request["code"];
var info = new GoogleAccessTokenResponse();
var client = new GoogleOAuthClient();
try
{
info = client.GetAccessTokenFromAuthorizationCode(AuthCode);
}
catch (Exception ex)
{
var strMessage = String.Format("<div class=\"info\"><p>{0}</p><p>{1}</p></div>", "Google Login Error",
ex.Message);
return Json(new AjaxOperationResponse(false, strMessage));
}
}
}
On the Serverside I am using Skybrud Social plugin for accessing google apis.
The google authentication happens in the popup and authorizes client with credentials and authResult['code'] has a valid code.
In the controller when I initialize the client and call the function GetAccessTokenFromAuthorizationCode(AuthCode), it returns an exception of 'Invalid Request'
I tried checking this authResult['code'] returned in the javascript function onSignIn in the https://developers.google.com/oauthplayground/
Same error description is shown 'Invalid request'. I am not sure why this is happening. The error returned is "invalid_grant"
Can anyone have a solution to this problem? What am I doing wrong here?
In your surface controller you're initializing a new instance of GoogleOAuthClient, but without setting any of the properties. The GetAccessTokenFromAuthorizationCode method requires the ClientId, ClientSecret and RedirectUri properties to have a value. You can initialize the properties like this:
// Initialize a new instance of the OAuth client
GoogleOAuthClient oauth = new GoogleOAuthClient {
ClientId = "The client ID of your project",
ClientSecret = "The client secret of your project",
RedirectUri = "The return URI (where users should be redirected after the login)"
};
You can read more about authentication in the documentation: http://social.skybrud.dk/google/authentication/ (the approach explained there will however not use any JavaScript)
I have a Web Api Application which has the following question.
[HttpGet]
[Route("Account/userName{userName}/password={password}/rememberMe/{rememberMe}")]
public HttpResponseMessage LogIn(string userName, string password, bool rememberMe)
{
if (User.Identity.IsAuthenticated)
{
return Request.CreateResponse(HttpStatusCode.Conflict, "already logged in.");
}
var dbPerson = dbContext.Persons.Where(x => x.UserName.Equals(userName) && x.EncryptedPassword.Equals(password)).FirstOrDefault();
if (dbPerson != null)
{
FormsAuthentication.SetAuthCookie(userName, rememberMe);
return Request.CreateResponse(HttpStatusCode.OK, "logged in successfully");
}
else
{
return new HttpResponseMessage(HttpStatusCode.Unauthorized);
}
}
I am calling from another MVC project. I Got the authentication but very next page where I am calling the ajax method
var uri = 'http://localhost:44297/api/XXXX';
$(document).ready(function () {
// Send an AJAX request
$.getJSON(uri)
.done(function (data) {
// On success, 'data' contains a list of products.
for (var i = 0; i < data.$values.length; i++)
{
}
})
.fail(function() {
console.log( "error" )});
});
I am getting GET http://localhost:44297/api/StudyFocus 401 (Unauthorized). how I can solve this issue. I know I need to pass some cookie/session value with this ajax call. but I don't know how. can anyone explain me with example.
My application relies on web Api project including authentication. I need to make web api application secure using form authentication. Any help is highly appreciable. Thanks
You can't authenticate web api by the use of cookies or session. You need access token to do that.
Follow this tutorial for the implementation http://www.asp.net/web-api/overview/security/individual-accounts-in-web-api
I have the following js code:
$.get('/desk/AddTicketToCart', { clientId: clientId}, function(data) {
});
And controller's action:
public ActionResult AddTicketToCart(int clientId)
{
// do work
return new RedirectResult("/", true);
}
But, I get white page and url not changed in address bar. I also tryed the following:
return RedirectToAction("Index", "Home")
but, I also get white page.
How to make redirect properly?
Thanks.
Redirect in server won't help you here since you're making a ajax call. You need to set the new url in js in the callback.
$.get('/desk/AddTicketToCart', { clientId: clientId}, function(data) {
window.location = // the url
});