django oauth2 authentication with client_id and cl

2019-08-30 18:38发布

I implement Oauth2 in django and my refresh token is under o/token/ url, I want to define another url like this:

path('api/v1/login',Login.as_view()), and inside my login view I want to have something like this:

class login(APIView):
  def post(self,request):
    client_id = "123"
    client_Secret = "123"
    username = request.query_params.get('username')
    ....
   *problem is here*

I want to define those parameters inside login class and then pass it to o/token/ url and get the token as a result. In fact, when the user enters www.example.com/api/v1/login address, it enters just username and password and previously inside my code I said to OAuth what my client info is and then the token will generate.

1条回答
冷血范
2楼-- · 2019-08-30 19:07

I think what you want to do is to define a login route for your users, It's true that if we pass client_id and client_secret in front end there will be a lot of security problem, thus we hide it inside our code. What you should do is that to define a new route for your login, then in view define a post method that needs user/pass from the user and send this data with some data you enter in your code to a request command (check here:enter link description here) notice that in order to have a JSON response in the output you need to return Response (r.json()) thus: url.py

path('api/v1/login',Login.as_view()),

view.py

class Login(APIView):
def post(self, request, *args, **kwargs):
    username = request.POST['username']
    password = request.POST['password']
    r = requests.post('http://localhost:8000/api/o/token/', #your token address
                      data = {'grant_type':'password', # your defined grant type
                              'client_id':'123', # your clinet id
                              'client_secret':'123', #your client secret
                              'username': username, # your username that you get from user
                              'password':password #your password that you get from user

}) return Response(r.json()) #response in json format

查看更多
登录 后发表回答