How to create session in Next js project? - reactjs

I'm using Next js to create my project, and I have created a custom signup form in it. In here I'm getting email and password of the user and them I'm sending an otp on user's email. after varifieng user I want to store his data.
I want to use session for this, but I'm not getting any good way to create session in Next js
How can I do that?

What I have done to solve this is used browser cookie to store the token, as cookies allows expiry option.
let today = new Date();
today.setHours(today.getHours() + 1);
document.cookie = "User_Token=" + userTokenValue + ";expires=" + today +
";domain=https://www.example.com";

Related

React, Django: How do I manage a session after a user changes their password?

I am developing an administration panel in React with Django for user management, amongst other actions.
Django takes care of ORM and users' login.When the user first logs in, the React app obtains the session id and the csrf token. The app asks for the csrf token from the document cookies and that's the token used for later REST queries.
Issue/Challenge:
One of the app component allows a user to change the password. However, after a successful password change doing so, the session id and the csrf token become expired and the REST queries I do from that time on are unauthorized.
If I reload the page, after then, the session is expired. I tried to get the token again but it doesn't work.
Question:
How can I update the session id after changing the password?
Should I just send the user outside the app for them to log in again?
I don't know if that is the common way to proceded.
Below is the function that I use to get the token:
getCookie(name) {
console.log(name);
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i += 1) {
const cookie = jQuery.trim(cookies[i]);
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (`${name}=`)) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
console.log(cookieValue);
this.setState({
token: cookieValue,
});
//getCookie('csrftoken')
I don't usually work with cookies, apart from getting the csrf token, so I would appreciate any help.
Update
I found the problem might be due to Django: https://docs.djangoproject.com/en/3.1/topics/auth/default/#session-invalidation-on-password-change
As I am changing the password with Django Rest Framework -- following this tutorial: https://medium.com/django-rest/django-rest-framework-change-password-and-update-profile-1db0c144c0a3 -- I used the function update_session_auth_hash in the serializer as follows:
## serializer
def update(self, instance, validated_data):
instance.set_password(validated_data['password'])
instance.save()
request = self.context['request']
user = request.user
update_session_auth_hash(request, user)
return instance
I doesn't work either...
I finally managed to make it work by using instance instead of user:
## serializer
def update(self, instance, validated_data):
instance.set_password(validated_data['password'])
instance.save()
request = self.context['request']
update_session_auth_hash(request, instance)
return instance

Set Cookies expiration in angular js

When a user is logging in, I am storing the values in cookies that I received from the backend. Now I want to set the cookies' expiration to 8 hours. How can I do that?
I have done like this but I am not sure if it is correct or not
var expireDate = new Date();
var time = expireDate.setDate(expireDate.getDate() + 1);
$cookieStore.put('userData', record.data.profileData,{'expires':time});
In Chrome developping tools (it's probably existing in others browsers) you can check what is the expiration date of your cookies.
You can access to this functionnalitie in the tab Application and on the left there is the label Cookies :
Be carefull with the use of $cookieStore because it's depreciated since v1.4.0

how can I get refresh token

i learn this code sample :https://github.com/Azure-Samples/active-directory-dotnet-graphapi-web ,and yes ,i can get access token in AuthorizationCodeReceived :
AuthenticationHelper.token = result.AccessToken;
but how do i get the refresh token ?result.RefreshToken is not available , then how do i use acquiretokenbyrefreshtoken function ?
https://msdn.microsoft.com/en-us/library/microsoft.identitymodel.clients.activedirectory.authenticationcontext.acquiretokenbyrefreshtoken.aspx
The acquiretokenbyrefreshtoken function is available in ADAL 2.X , that code sample is using ADAL 3.13.8 , and from ADAL3.X, library won't expose refresh token and AuthenticationContext.AcquireTokenByRefreshToken function.
ADAL caches refresh token and will automatically use it whenever you call AcquireToken and the requested token need renewing(even you want to get new access token for different resource).
please see the explanation from here . Also click here and here for more details about refresh token in ADAL .
If you looking for a persistent mechanism, you can simply use TokenCache.Serialize()
Here's how I did it:
First, get the token and serialize the cache token
AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{Tenant}");
var authResult = authContext.AcquireTokenAsync(resource, ClientId, new Uri("https://login.microsoftonline.com/common/oauth2/nativeclient"), new PlatformParameters(PromptBehavior.SelectAccount)).Result;
byte[] blobAuth = authContext.TokenCache.Serialize();
Then, load the cached bytes
AuthenticationContext authContext = new AuthenticationContext($"https://login.microsoftonline.com/{tenant}/");
authContext.TokenCache.Deserialize(blobAuth);
var res = authContext.AcquireTokenSilentAsync(resource, clientId).Result;

force.com sites - direct link to salesforce visual force page not working

Am facing an obstacle using force.com site
a template email is used to send to portal users with direct link to some record in salesforce
example https://example.force.com/SamplePage?id=xxxxx
by trying to use refURL param half way was done as in the next example :
https://example.force.com?refURL=/SamplePage?id=xxxxx
but passing from an obstacle to facing another,now every time i click on the new link in the email i have to re-login again regardless that i just made a login.
so for the first attempt its logical to input the credentials to login to the site but i need to prevent when the session still on to re login again every time by clicking on the link from my email
my login code in Apex is as below :
global PageReference login() {
//Get refUrl
String strRefUrl = System.currentPageReference().getParameters().get('refURL');
//Get startUrl
String strStartUrl = System.currentPageReference().getParameters().get('startURL');
if(strRefUrl != null && strRefUrl != '' && ! strRefUrl.startsWithIgnoreCase(Site.getBaseInsecureUrl() )){
//Need to remove domain part because site.login() does not redirect to absolute URL
strStartUrl = strRefUrl.replace(Site.getBaseRequestUrl(),'');
}
else if (strRefUrl.startsWithIgnoreCase(Site.getBaseInsecureUrl())){
//Redirect to base URL if refUrl is empty
strStartUrl = Site.getBaseUrl() + '/LoginPage';
}
return Site.login(username, password, strStartUrl );
}

Passing user credentials to Adal AquireTokenAsync

I am using Adal (Active Directory Authentication Library) Version 3.13.x. I am doing something like below to fetch the Access token
AuthResult = await AuthContext.AcquireTokenAsync(relyingUrl, ServiceConstants.CLIENTID, ServiceConstants.RETURNURI, param);
I need to pass the UserCredentials along as well, but right now I can only pass one parameter to the UserCredential() unlike in the Versions 2.x.x of Adal.
I also tried using UserPasswordCredential as suggested in this solution , but since I want to Fetch the token from a Mobile app, I only have access to .net Core and hence can not use UserPasswordCredential
I want to pass the username and password together while acquiring the token. Is there any way i can achieve this?
Any help would be appreciated.
EDIT
After trying out the solution from Fei Xue - MSFT, i get the following 503 error.
I want to pass the username and password together while acquiring the token. Is there any way i can achieve this?
In this scenario, we can perform the REST request directly instead of using the client library. Here is a sample for your reference:
Post:https://login.microsoftonline.com/{tenant}/oauth2/token
resource={resource}&client_id={clientId}&grant_type=password&username={userName}&password={password}
Update
string authority = "https://login.microsoftonline.com/{tenantid}";
string resrouce = "https://graph.windows.net";
string clientId = "";
string userName = "";
string password = "";
UserPasswordCredential userPasswordCredential = new UserPasswordCredential(userName, password);
AuthenticationContext authContext = new AuthenticationContext(authority);
var token = authContext.AcquireTokenAsync(resrouce, clientId, userPasswordCredential).Result.AccessToken;
Console.WriteLine(token);

Resources