lately i'm trying to implement a login api for a website.
I'm using Nuxt for the FE, Django REST Framework for the BE and Nuxt Auth Module for the JWT.
Now I tryed to use the normal option for implement my api:
https://auth.nuxtjs.org/schemes/local.html#options
auth: {
localStorage: false,
redirect: {
logout: '/login'
},
cookie: { options: { expires: 7} },//7 minuti
strategies: {
local: {
endpoints: {
login: { url: 'http://127.0.0.1:7777/api/users/login/', method: 'post', propertyName: false},
user: { url: 'http://127.0.0.1:7777/api/users/infoUser/', method: 'get', propertyName: false},
logout: { url: 'http://127.0.0.1:7777/api/users/logout/', method: 'post'},
},
tokenRequired: false,
tokenType: false
}
}
},
but in Django I don't see the token on vscode debug mode.
I need the token for retrieve the user infos.
Can someone help me?
Thank you.
I got it working with the standard Django Restframework endpoint: link
This returns the token which will be set automatically by NuxtJS. In <app>/urls.py I have:
urlpatterns = [
path('login', views.obtain_auth_token, name='login'),
path('user', Views.CurrentUser.as_view()),
path('logout', Views.Logout.as_view()),
]
With the user and logout endpoint being endpoints I created myself.
If this doesn't work can you spicify your way of working on the BE?
Related
I want to use JWT authentication in my nuxtjs app but it's not refreshing the token. For testing purposes, I set the access token expire time 5 seconds and refresh token for 30 minutes.
Access token expire after 5 seconds but the token is not refreshing after 5 second its logged-out
I'm using the Django rest framework and in nuxt I'm using nuxt auth v5
settings.py
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
}
SIMPLE_JWT = {
'AUTH_HEADER_TYPES': ('JWT',),
'ACCESS_TOKEN_LIFETIME': timedelta(seconds=5),
'REFRESH_TOKEN_LIFETIME': timedelta(minutes=30),
}
nuxt.config.js
auth: {
localStorage: false,
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access',
type: 'JWT',
required: true
},
refreshToken: {
property: 'refresh',
},
user: {
property: false,
autoFetch: true
},
endpoints: {
login: { url: '/jwt/create/', method: 'post',},
refresh: { url: '/jwt/refresh/', method: 'post',},
user: {url: '/users/me/', method: 'get' },
logout: false
},
}
}
}
}
I'm little new in JWT and nuxt. Correct me if I'm wrong.
My main goal is just to refresh the token automatically when access toke is expired.
I have an app with react and Django rest framework. I use Django allauth for login and registration. when I want to log in, everything is ok, and the response is 201 but the data is empty and I don't get token. I send this request with the postman and I get the token. what should i do?
React Request:
axios({
method: 'post',
url: 'http://localhost:8000/rest-auth/login/',
data: {
username: 'admin',
email: '',
password: 'admin123456'
},
headers: { 'content-type': 'application/json' }
})
.then(response => {
console.log(response.data.key);
})
.catch(error => {
console.log(error);
});
the response is:
{data: "", status: 200, statusText: "OK", headers: {…}, config: {…}, …}
postman request: http://localhost:8000/rest-auth/login/
{
"username": "mahtab",
"email": "",
"password": "mahtab23"
}
postman response:
{
"key": "f75b9f54848a94ac04f455321118aff5d5a7e6f8"
}
I have a react application linked to a Django backend on two separate servers. I am using DRF for django and I allowed cors using django-cors-headers. For some reason when I curl POST the backend, I am able to get the request out. However when I use axios POST the backend, I get and error. The status of the POST request from axios is failed. The request and takes more than 10 seconds to complete. My code was working locally (both react and django codes), but when I deployed to AWS ec2 ubuntu, the axios requests stopped working.
Console error logs
OPTIONS http://10.0.3.98:8000/token-auth/ net::ERR_CONNECTION_TIMED_OUT
{
"config": {
"transformRequest": {},
"transformResponse": {},
"timeout": 0,
"xsrfCookieName": "XSRF-TOKEN",
"xsrfHeaderName": "X-XSRF-TOKEN",
"maxContentLength": -1,
"headers": {
"Accept": "application/json, text/plain, */*",
"Content-Type": "application/json;charset=UTF-8",
"Access-Control-Allow-Origin": "*"
},
"method": "post",
"url": "http://10.0.3.98:8000/token-auth/",
"data": "{\"username\":\"testaccount\",\"password\":\"testpassword\"}"
},
"request": {}
}
Here is my request code
axios.post('http://10.0.3.98:8000/token-auth/',
JSON.stringify(data),
{
mode: 'no-cors',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin' : '*'
},
},
).then( res => (
console.log(JSON.stringify(res)),
)
).catch( err => (
console.log(JSON.stringify(err))
)
);
my curl code that worked
curl -d '{"username":"testaccount", "password":"testpassword"}' -H "Content-Type: application/json" -X POST http://10.0.3.98:8000/token-auth/
UPDATE 1
on firefox i am getting the warning
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://10.0.3.98:8000/token-auth/. (Reason:
CORS request did not succeed).[Learn More]
UPDATE 2
Perhaps it has something to do with my AWS VPC and subnets? My django server is in a private subnet while my react app is in a public subnet.
UPDATE 3 - my idea of what the problem is
I think the reason why my requests from axios aren't working is because the requests i'm making is setting the origin of the request header to http://18.207.204.70:3000 - the public/external ip address - instead of the private/internal ip address which is http://10.0.2.219:3000 - i search online that the origin is a forbidden field so it can't be changed. How can i set the origin then? Do I have to use a proxy - how can I do that.
try this http request instead of axios, it's called superagent (https://www.npmjs.com/package/superagent) , just install it to your react app via npm,
npm i superagent
and use this instead of axios.
import request from 'superagent'
const payload ={
"1": this.state.number,
"2": this.state.message
}
request.post('LINK HERE')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send(payload)
.end(function(err, res){
if (res.text==='success'){
this.setState({
msgAlert: 'Message Sent!',
})
}
else{
console.log('message failed/error')
}
});
The issue here is that the request is being made on the client browser. You need to either use a reverse proxy or request directly to the api server. You cannot do a local ssh forwarding either.
I made a django OAuth server using Django OAuth Toolkit.
I've setup the code right and when I use CURL in the following way:
curl -X POST -d "grant_type=password&username=geethpw&password=abcabcabc" -u"wHsGgpsHZyw8ghnWbEPZC8f4AZLgJIPmoo50oNWp:ZQcXeQWnae0gmX0SMi6Xn6puBnhiphR2M80UC6ugmffbrUd66awhbguYgxtQ1ufahJZehj4RlGjYu06fHkVgO15TURttSozj27nshl0AhFfCVzUKqTDubBimTSsK4yDS" http://localhost:8000/o/token/
I get a response:
{"access_token": "glzwHLQNvUNQSOU5kFAoopgJxiNHcW", "token_type": "Bearer", "expires_in": 36000, "refresh_token": "5k6jvCd2UxaRUGHKONC2SqDukitG5Y", "scope": "read write groups"}Geeths-MacBook-Pro:~ geethwijewickrama$
Geeths-MacBook-Pro:~ geethwijewickrama$
which is expected.
But When I try postman to do the samething, I always get:
{
"error": "unsupported_grant_type"
}
My headers are:
Content-Type:application/x-www-form-urlencoded
If I remove this header I get:
{
"error": "invalid_client"
}
How can I test my APIs in postman?
Your postman body should be something like:
grant_type: <grant_type>
client_id: <client_id>
client_secret: <client_secret>
username: <username>
password: <password>
Try Bulkedit with these, hope this helps (Hope you have registered the app to obtain client_id and client_secret)
Get token from django-oauth-toolkit from JS:
async function getToken () {
let res = await fetch("https://<your_domain>/o/token/", {
body: new URLSearchParams({
grant_type: 'password',
username: '<user_name>',
password: '<user_pass>',
client_id: '<client_app_id>',
client_secret: '<client_pass>'
}),
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
method: "POST"
})
return res.json();
}
console.log(await getToken());
Your client application authorisation grant type should be: "Resource owner password-based"
P.S. I've failed to get token via "Content-Type": "application/json", not sure why (django-oauth-toolkit documentation says nothing about that).
I have created a SharePoint Hosted app which uses a visual studio workflow to send email within same domain.
Since I am in process of migrating custom aspx forms in SP2010 to SharePoint Online, each form is redeveloped as a SP Hosted app and I don't want to include a workflow every time to send email.
Is there any other workaround to handle email in SP Hosted app?
Thanks!
You can use javascript REST API to send email from hosted app.
See the code below:
var urlTemplate = SPAppWebUrl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': { 'type': 'SP.Utilities.EmailProperties' },
'From': from,
'To': { 'results': [to] },
'Body': emailBody,
'Subject': subject
}
}
),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
//console.log('success')
alert('email send successfull..');
},
error: function (err) {
//console.log(JSON.stringify(err));
alert(JSON.stringify(err));
}
});