Authentication and authorize, djangorestframework - django-rest-framework

I have a problem with django rest framework token-based authentication. I can create user, but his password not hash, then I wrote implementation of method create in my serializer. This didn't worked. Only root can receive token and his password is hashed. Even user receive a Token. Code here:
https://github.com/XxXAsmoXxX/DjangoBlogAuthorization and authentication in folder restapi, folder with settings tasks

From http://www.django-rest-framework.org/api-guide/serializers/ ...
I am using a create function like this in my serializer. It sets the password hashed if you were using django User model.
def create(self, validated_data):
user = User(
email=validated_data['email'],
username=validated_data['username']
)
user.set_password(validated_data['password'])
user.save()
return user

Related

How to connect accounts with Django rest auth / all auth?

I'm using Django rest-auth for authentication and account creation with Django rest framework. Currently, I have six providers set up and I'd like to start connecting them.
It's not clear from the documentation (either rest-auth or all-auth) what I have to do to connect the accounts.
For example, if I try to connect a Google account to a LinkedIn one (same email address), even if I make a POST request to /rest-auth/linkedin/connect/ with the correct access token for the Google provider, I get a 400 response saying: "non-field-errors": [ "Incorrect value" ].
I'm using JWTs for authentication, and providing the correct token in the Authorization header.
views.py
class GoogleConnect(SocialConnectView):
adapter_class = GoogleOAuth2Adapter
class LinkedInConnect(SocialConnectView):
adapter_class = LinkedInOAuth2Adapter
I've written a tutorial that should cover your question. This should be the part you are looking for.
In short: You have to write your own ConnectView which inherits from the rest_auth view like this:
class GoogleCallbackConnect(SocialConnectView):
"""
Connects the provider's user account to the currently logged in user.
"""
adapter_class = GoogleOAuth2Adapter
client_class = OAuth2Client
#property
def callback_url(self):
url = self.adapter_class(self.request).get_callback_url(
self.request,
None,
)
return url

Laravel API login with username and token

I am developing a laravel API(MyAPI) with the 5.1 version.I am connecting to this API from a widget which hosted in another website.it has a separate API(hostAPI). I need to authenticate user when widget loaded.
following are my requirement.
" When the widget loads it will attempt to authenticate. It will send a request to the MyAPI with
{
username: username,
token: token
}
MyAPI will POST this information on to the hostAPI. This will return either success or a 401.
On sucess, we log the user in. We may need to create an account if an user with that name does not exist"
how can i auth a user with only username and a token key
Is not a good practice to login user by user interface.
But it is an option and maybe in your case you can use that.
So you know only the username, and token.
I think you can query the database based on you username and token . find the user and login the selected one :)
Example:
$user=User::where('username',$username)->where('token',$token)->first();
Auth::login($user);
return Auth::user();
In case you want to create the user if it does not exist:
$user=User::where('username',$username)->where('token',$token)->firstOrCreate(['username' => $username,'token'=>$token]);

How do I use password reset REST APIs on service now?

I want to simulate the password reset service for service now users from an external application and I have installed Password Reset - Orchestration Add-on plugin on my servicenow developer instance. Along with this I can see a list of Pwd Reset APIs on my REST explorer (e.g pwd_init, pwd_verify, etc). I went through the documentation available on this documentation page but I'm at a loss to understand what the request payload would be like if I'm trying to call these APIs from an external service like Postman. I wanted something similar this api documentation.
Can anyone help me with this?
Use the Table APIs to do this.
In order to reset a user's password, you basically want to update the user_password field of the user record from sys_user table.
Method: PUT/PATCH
http://<instance>/api/now/table/{tableName}/{sys_id}
here tableName will be sys_user and sys_id will be the sys_id of the user's record in sys_user table.
The body of the API request should be something like this:
{
"user_password": "resetpasswordtext"
}
Bear in mind that this will reset the user's password but the new password will not be "resetpasswordtext". So the user will not be able to login using "resetpasswordtext".
To actually set the password for a user via API, same table API as above can be used. But in order to store the password properly encrypted in the database, below query parameter should be added in the request URL to set the password.
sysparm_input_display_value=true
So the API call will be
Method: PUT/PATCH
http://<instance>/api/now/table/{tableName}/{sys_id}?sysparm_input_display_value=true
BODY: {
"user_password": "newpassword"
}
Now the text "newpassword" can be used by the user to login to the instance.
hope it helps in your use case.
so, my use case did not involve using the Password reset API, but for those of you interested in generating a new password externally, then making an api call to set that as the new password for that user, then here is acode sample that is based on Milind's answer above:
Python3
def change_password_snow(user, pwd, new_pwd, snow_url, sys_id):
# Set the request parameters
url = snow_url + sys_id
# Set proper headers
headers = {"Content-Type":"application/xml","Accept":"application/json"}
# Set query params
params = {"sysparm_input_display_value": "true", "sysparm_fields": "user_password"}
# Do the HTTP request
response = requests.patch(url, auth=(user, pwd), headers=headers, params=params, data=f"<request><entry><user_password>{new_pwd}</user_password></entry></request>")
return response
Setup on ServiceNow
For this to work, the user you are authenticating with in ServiceNow needs to have Admin privileges.
Either that, or modify the sys_user.user_password ACLs to allow non admin users to read and write to that field if they have a role that you select. For my use case, I created a custom role and attached it to that user.

Auth0 with Authorization Extension not passing roles to Spring Security JWT object

I have an Auth0 project that I am using for authentication. I have modeled my Spring code based on this example.
I am trying to limit an area like this...
.antMatchers(ADMIN).hasRole(Role.ADMIN.getRoleName())
But when I add my Admin role to my user and try to log back in the JWT does not show any roles when I run...
Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) SecurityContextHolder.getContext().getAuthentication().getAuthorities();
It is empty. How do I pass the roles to my application using Auth0
More Information
I tried decoding the JWT token and I don't see the role information even being passed....
Header
{"typ":"JWT","alg":"RS256","kid":"<Removed>"}
Body
{"iss":<Removed>,"sub":<Removed>,"aud":<removed>,"iat":<removed>,"exp":<removed>}
So why is Auth0 not passing this information.
Groups, roles and permissions won't be added to the jwt automatically. You have to
create a new rule or modify the default rule which is created after enabling (publishing) the authorization extension.
Adding roles and permissions to a JWT access token in Auth0
You should provide the granted authorities to your principal when you're authenticating it.
I assume you have a custom class that implements UserDetails and you overwrite getAuthorities(). This method should return an authority called ROLE_ADMIN. Notice that the role should be prefixed with ROLE_

How to get authenticated user in spring-security-oauth

For my REST aplication I used Basic Authentication (sending user's password and login with every request). For some needs I obtain logged user using:
User loggedUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
But then I implemented Spring-Security-Oauth2 and I am using access token instead password and login. And now .getPrincipal() method returns "anonymousUser".
So my question: Is there any way to obtain logged User somehow as above in spring-security-oauth?
EDIT:
I figured out that I had a proplem in my security "intercept-url pattern". So now I can use SecurityContextHolder from which I can obtain authenticated user.
inside controller method you can add this paramter then it will be injected for you and you can access user information
getUserAuthentication(OAuth2Authentication auth,Model model)

Resources