简体   繁体   English

如何通过alamofire4和swift3提供身份验证令牌来登录api

[英]how to provide authentication token to login api by alamofire4 and swift3

all. 所有。

I can get authentication token by login. 我可以通过登录获取身份验证令牌。 but I can authenticate on my server by swift and alamofire. 但我可以通过swift和alamofire在服务器上进行身份验证。

this is Postman. 这是邮递员。 as you see, if i have token, i can be authenticated on myserver. 如您所见,如果我有令牌,则可以在myserver上进行身份验证。 在此处输入图片说明

this is swift viewcontroller. 这是快速的viewcontroller。

import UIKit
import Alamofire
import SwiftyJSON
import KeychainAccess

class ViewController: UIViewController {
    let authLoginUrl = "http://ec2-52-79-155-29.ap-northeast-2.compute.amazonaws.com:8000/rest-auth/login/"
    let keychain = Keychain(service: "wanote")
    let projectUrl = "http://ec2-52-79-155-29.ap-northeast-2.compute.amazonaws.com:8000/api/user/ryulstory"

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let username = "username"
        let password = "1234!"

        self.doAuth(username: username, password: password)
        }

        override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func doAuth(username:String, password:String) {
        let params = ["username": username, "password": password]
        var authToken = Alamofire.request(self.authLoginUrl, method: .post, parameters: params)
        authToken.responseJSON { response in
            let statusCode = response.response?.statusCode ?? 0

            switch statusCode {
            case 200...299:
                let jsonData = JSON(response.result.value)
                if let token = jsonData["key"].string{
                    self.keychain["token"] = token
                    self.getProjects()
                }
            case 400...499:
                print("Server responded no")

            case 500...599:
                print("Server error")

            default:
                print("There was an error with your request")
            }

    }
}

    func getProjects(){
        if let token = self.keychain["token"] {
            if let Purl = URL(string: self.projectUrl){
                var mutableUrlRequest = URLRequest(url: Purl)
                mutableUrlRequest.httpMethod = "GET"
                mutableUrlRequest.setValue("Token " + token, forHTTPHeaderField: "Authorization")
                var manager = Alamofire.SessionManager.default
                var getProjectsRequest = manager.request(mutableUrlRequest)
                    getProjectsRequest.responseJSON { response in
                        print(response.data)
                }

            }

        } else {
            print("no token")
        }


    }


}

I checked getting token by function doAuth. 我检查了通过功能doAuth获取令牌。 it is correctly operating. 它运行正常。 function getprojects makes error status code 401. I think there are problem in function getprojects. 函数getprojects使错误状态代码为401。我认为函数getprojects中存在问题。 but i can't find it. 但我找不到它。

could you help me? 你可以帮帮我吗?

Best regards. 最好的祝福。

It goes to 401 because you are sending the request without the header authorization. 转到401,因为您发送的请求没有标题授权。

With Alamofire you can set the header Authorization like this. 使用Alamofire,您可以像这样设置标头授权。

    let url = "URL_LOGIN"
    //Get token logic
    let token = ""
    let headers = ["Authorization": "Token \(token)"]
    let params = ["user": "", "pass":""] //This goes in the body of the request
    Alamofire.request(url, method: .post, parameters: params, encoding: URLEncoding.default, headers: headers).responseJSON { (response) in
        if let value = response.result.value {
            print(value)
        }

    }

With this you'll send the headers in the request to get what you want. 这样,您将在请求中发送标题以获得所需的内容。

I think this part have the header authorization. 我认为这部分具有标题授权。 is it wrong? 这是错的吗?

mutableUrlRequest.httpMethod = "GET"
                mutableUrlRequest.setValue("Token " + token, forHTTPHeaderField: "Authorization")
                var manager = Alamofire.SessionManager.default
                var getProjectsRequest = manager.request(mutableUrlRequest)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM