Blog

Blog

PHODAL

Ionic Auth与Django JWT API

Ionic Auth与Django JWT API

如上一章中说到的那样在给博客添加App Indexing的时候,顺手做了登陆的功能。

主要用到的便是:

  1. Django REST Framework
  2. Django REST Framework JWT

前端是Django的REST框架,后者则是用于JWT验证的。

Django JWT服务端

1.安装djangorestframework-jwt

$ pip install djangorestframework-jwt

2.添加相应的配置到settings.py

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
        'rest_framework.permissions.IsAuthenticated',
    ),
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'rest_framework.authentication.SessionAuthentication',
        'rest_framework.authentication.BasicAuthentication',
        'rest_framework_jwt.authentication.JSONWebTokenAuthentication',
    ),
}

JWT_AUTH = {
    'JWT_EXPIRATION_DELTA': datetime.timedelta(days=14)
}

3.创建相应的API

@api_view(['POST', 'OPTIONS'])
@authentication_classes([JSONWebTokenAuthentication])
@permission_classes((IsAuthenticated,))
def create_blog(request):

    serializer = BlogpostSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

主要是用于POST,出现OPTIONS的主要原因是用于网页端测试,主要不同便是JSONWebTokenAuthentication这个authentication_classes

接着我们就可以测试这个API了。

测试

1.首先我们要发送用户名和密码获取token

curl -X POST -H "Content-Type: application/json" -d '{"username":"phodal","password":"phodal"}' http://localhost:8000/api-token-auth/

如token可能是

eyJhbGciOiJIUzI3NiIsInR5cCI3IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJ1c2VyX2lkIjoxLCJlbWFpbCI6ImhAcGhvZGFsLmNvbSIsImV4cCI6MTQ0MjQ1MzEyNH0.viYOMaSSt2mG7k9sxhiF4C3VrODz0m-fvglbayb7I7s

2.创建blog

curl -H "Accept: application/json" -H "Content-type: application/json" -H "Authorization: JWT eyJhbGciOiJIUzI3NiIsInR5cCI3IkpXVCJ9.eyJ1c2VybmFtZSI6InJvb3QiLCJ1c2VyX2lkIjoxLCJlbWFpbCI6ImhAcGhvZGFsLmNvbSIsImV4cCI6MTQ0MjQ1MzEyNH0.viYOMaSSt2mG7k9sxhiF4C3VrODz0m-fvglbayb7I7s" -X POST --data '{"content":"在设计","title":"物联网架构设计","user":1}' http://localhost:8000/api/app/blog/

如果上面的步骤正常的话,那说明是可以工作的,我们就可以继续进行下一步了。

Ionic/Cordova 客户端

借助于Ionic默认Demo的AppCtrl,我们在我们的doLogin就可以有下面的代码:

  var username = $scope.loginData.username;
  var password = $scope.loginData.password;
  $http({
    method: 'POST',
    url: 'https://www.phodal.com/api-token-auth/',
    data: {
      username: username,
      password: password
    },
    headers: {
      'Content-Type': 'application/json; charset=UTF-8',
      'User-Agent': 'phodal/2.0 (iOS 8.1, Android 4.4) secret=75456d89c8a654'
    }
  }).success(function (response) {
    $scope.noLogin = false;
    $localstorage.set('token', response.token);
    $scope.closeLogin();
  }).error(function (data, status) {
    console.log('data, status', data, status)
  })

将用户名和密码取出,用POST到服务端,再将token存到LocalStorage中。接着在我们的Blog创建方法里就会有:

$scope.create = function () {
  var token = $localstorage.get('token');
  var data = serialData($scope.posts);

  $http({
    method: 'POST',
    url: 'https://www.phodal.com/api/app/blog/',
    data: data,
    headers: {
      'Authorization': 'JWT ' + token,
      'User-Agent': 'phodal/2.0 (iOS 8.1, Android 4.4) secret=75456d89c8a654'
    }
  }).success(function (response) {
    if ($localstorage.get('draft')) {
      $localstorage.remove('draft');
    }

    $scope.posts = {};
    $state.go('app.blog-detail', {slug: response.slug});
  }).error(function (rep, status) {
    if (status === 401) {
      alert(rep.detail);
    }
    alert(JSON.stringify(rep));
    $localstorage.set('draft', JSON.stringify(data));
  });
}

如果成功,且存在draft就会删除draft。如果失败,则会保存为draft。

其他

博客代码: PhodalDev 博客App代码:Phodal App


或许您还需要下面的文章:

关于我

Github: @phodal     微博:@phodal     知乎:@phodal    

微信公众号(Phodal)

围观我的Github Idea墙, 也许,你会遇到心仪的项目

QQ技术交流群: 321689806
comment

Feeds

RSS / Atom

最近文章

关于作者

Phodal Huang

Engineer, Consultant, Writer, Designer

ThoughtWorks 技术专家

工程师 / 咨询师 / 作家 / 设计学徒

开源深度爱好者

出版有《前端架构:从入门到微前端》、《自己动手设计物联网》、《全栈应用开发:精益实践》

联系我: h@phodal.com

微信公众号: 最新技术分享

标签