Как войти напрямую в Auth0 без перенаправления страницы универсального входа? - PullRequest
0 голосов
/ 07 января 2019

Я работаю над интеграцией Auth0, я успешно интегрировал Auth0 SDK в свой проект Swift, но я хочу реализовать прямой вход из моего приложения без перенаправления на страницу универсального входа Auth0.

Я изучил здесь поток мобильного входа в систему (https://auth0.com/docs/flows/concepts/mobile-login-flow ).

Я реализовал авторизацию Auth0 в iOS Swift, она работает. Но я хочу прямой вход.

Смотрите мои экраны

Когда мы нажимаем логин в моем приложении, появляется всплывающее окно. enter image description here

Нажмите продолжить, чтобы открыть страницу Auth0.com (я не хочу эту страницу, я хочу прямой вход без этой страницы Как?)

enter image description here

Мне не нужна эта страница, я хочу прямой вход без этой страницы через страницу входа в приложение mu, Как ?.

Возможно ли это?

Для этого я перешел по этой ссылке https://auth0.com/docs/flows/guides/mobile-login-flow/add-login-using-mobile-login-flow и реализовал code_verifier и code_challage. Но когда я внедряю Авторизируйте пользователя это дает html response,

Мой код:

func codeVerifier() {
    var buffer = [UInt8](repeating: 0, count: 32)
    _ = SecRandomCopyBytes(kSecRandomDefault, buffer.count, &buffer)
    let verifier = Data(bytes: buffer).base64EncodedString()
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "/", with: "$_")
        .replacingOccurrences(of: "=", with: "")
        .trimmingCharacters(in: .whitespaces)

    print("Code_Verifier : \(verifier)")

    codeChallenger(verifier: verifier)
}

func codeChallenger(verifier:String) {
    // Dependency: Apple Common Crypto library
    // http://opensource.apple.com//source/CommonCrypto
    guard let data = verifier.data(using: .utf8) else {

        return
    }

    var buffer = [UInt8](repeating: 0,  count: Int(CC_SHA256_DIGEST_LENGTH))
    data.withUnsafeBytes {
        _ = CC_SHA256($0, CC_LONG(data.count), &buffer)
    }
    let hash = Data(bytes: buffer)
    let challenge = hash.base64EncodedString()
        .replacingOccurrences(of: "+", with: "-")
        .replacingOccurrences(of: "/", with: "$_")
        .replacingOccurrences(of: "=", with: "")
        .trimmingCharacters(in: .whitespaces)

    print("Code_Challenger : \(challenge)")

    authorizwTheUser(code_challange: challenge)
}

func authorizwTheUser(code_challange:String) {

    let url = "https://domain.auth0.com/authorize?"

    var request = URLRequest(url: URL(string: url)!)

            request.setValue("application/json", forHTTPHeaderField: "Content-Type")
            request.httpMethod = "GET"

            print("URL : \(request)")

    let parameters = "response_type=token&code_challenge=\(code_challange)&code_challenge_method=S256&client_id=&redirect_uri=com.myappname.Auth0DemoSwift://domainname.auth0.com/ios/com.domainname.Auth0DemoSwift/callback&scope=openid profile&state=xyzABC123x"

    request.httpBody = parameters.data(using: .utf8)

    print(parameters)

            let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
                print("error=\(String(describing: error))")
                return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }

                                            // If Response is in String formate
                                            let responseString = String(data: data, encoding: .utf8)
                                            let dictionary = data
                                            print("dictionary = \(dictionary)")
                                            print("responseString = \(String(describing: responseString!))")

                do {
                    let response = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: AnyObject]
                    print(response!)

                    let res = response!["Response"]
                    let status = res!["status"] as! String

                    if status == "SUCCESS" {

                    } else {

                    }

                } catch let error as NSError {
                    print(error)
                }
            }

            task.resume()

}

1 Ответ

0 голосов
/ 07 января 2019

Если вы хотите избежать экрана согласия и перенаправления на страницу входа, размещенную на auth0, вы можете использовать API аутентификации с областью пароля (http://auth0.com/oauth/grant-type/password-realm) тип предоставления. Недостатки:

  • НЕТ SSO
  • Вам необходимо разработать собственный пользовательский интерфейс
  • Простая в использовании атака методом перебора (Включите защиту перебором на приборной панели)

Как описано:

The Authentication API exposes AuthN/AuthZ functionality of Auth0, as well as the supported identity protocols like OpenID Connect, OAuth 2.0, and SAML. We recommend using our Hosted Login Page but if you wish to build your own UI you can use our API endpoints to do so. However some Auth flows (Grant types) are disabled by default so you will need to enable them via your Auth0 Dashboard as explained in this guide.

Вход:

Auth0 .authentication() .login( usernameOrEmail: "support@auth0.com", password: "secret-password", realm: "Username-Password-Authentication", scope: "openid") .start { result in switch result { case .success(let credentials): print("Obtained credentials: \(credentials)") case .failure(let error): print("Failed with \(error)") } } Регистрация:

Auth0 .authentication() .createUser( email: "support@auth0.com", password: "secret-password", connection: "Username-Password-Authentication", userMetadata: ["first_name": "First", "last_name": "Last"] ) .start { result in switch result { case .success(let user): print("User Signed up: \(user)") case .failure(let error): print("Failed with \(error)") } } Здесь задокументировано: https://github.com/auth0/Auth0.swift#authentication-api-ios--macos--tvos

...