onelogin

package module
v0.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 20, 2021 License: MIT Imports: 15 Imported by: 0

README

onelogin

OneLogin client written in Go.

GoDoc Go Report Card Build Status

This is a fork of arkan/onelogin that has been extended to implement authentication methods that support MFA. It's drifted in time to suit my needs.

Getting Started

go get github.com/asobrien/onelogin

Register an application on OneLogin

First you need to register a new application to have clientID and clientSecret credentials.

At a minimum your credentials need "Authentication Only" scope in order to authenticate a user. Querying the API, requires additional scopes which do not include the ability to authenticate.

If you need to authenticate users are programatically use the API, you will need to use two sets of credentials and reinitialize the client. Only the "Manage All" scope has the ability to authenticate users and interact with the API.

Quickstart

List Users
c := onelogin.New(clientID, clientSecret, "us_or_eu", team)
users, err := c.User.GetUsers(context.Background())
Authenticate

Authenticate via username/password:

c := onelogin.New(clientID, clientSecret, "us_or_eu", team)
user, err := c.Authenticate(context.Background(), "username", "password")

Note this authentication method always returns a user, if authentication if successful, regardless of whether MFA is required or not. To authenticate a user with strict MFA validation, use the AuthenticateWithVerify function:

c := onelogin.New(clientID, clientSecret, "us_or_eu", team)
user, err := c.AuthenticateWithVerify(context.Background(), "username", "password", "Google Authenticator", "123456")

See the documentation for all the available commands.

Licence

MIT

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the *http.Response. HTTP status codes ranging from 200 to 299 are considered are successes. Otherwise an error happen, and the error gets unmarshalled and returned into the error.

Types

type AuthResponse added in v0.2.0

type AuthResponse struct {
	Status       string             `json:"status,omitempty"`
	User         *AuthenticatedUser `json:"user"`
	ReturnToURL  string             `json:"return_to_url,omitempty"`
	ExpiresAt    string             `json:"expires_at,omitempty"`
	SessionToken string             `json:"session_token,omitempty"`
	StateToken   string             `json:"state_token,omitempty"`
	CallbackURL  string             `json:"callback_url,omitempty"`
	Devices      []*Device          `json:"devices,omitempty"`
	// contains filtered or unexported fields
}

AuthResponse is a struct where data in the authentication response can be marshalled into.

type AuthenticatedUser

type AuthenticatedUser struct {
	ID        int64  `json:"id"`
	Username  string `json:"username"`
	Email     string `json:"email"`
	FirstName string `json:"firstname"`
	LastName  string `json:"lastname"`
}

AuthenticatedUser contains user information for the Authentication.

type Client

type Client struct {
	BaseURL *url.URL

	// User agent used when communicating with the OneLogin api.
	UserAgent string

	sync.Mutex

	// Namespaced services
	// https://developers.onelogin.com/api-docs/1/getting-started/dev-overview
	Oauth       *OauthService
	Login       *LoginService
	User        *UserService
	Role        *RoleService
	Group       *GroupService
	SAMLService *SAMLService
	// contains filtered or unexported fields
}

A Client interacts with OneLogin.

func New

func New(clientID, clientSecret, shard, subdomain string) *Client

New returns a new OneLogin client.

func (*Client) AddAuthorization

func (c *Client) AddAuthorization(ctx context.Context, req *http.Request) error

AddAuthorization injects the Authorization header to the request. If the client doesn't has an oauthToken, a new token is issed. If the token is nearly expired, it is automatically refreshed.

func (*Client) Do

func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.

The provided ctx must be non-nil. If it is canceled or times out, ctx.Err() will be returned.

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest instantiate a new http.Request from a method, url and body. The body (if provided) is automatically Marshalled into JSON.

type Device added in v0.2.0

type Device struct {
	DeviceType string `json:"device_type"`
	DeviceID   int64  `json:"device_id"`
}

Device contains registered user devices that can be used for MFA.

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response // HTTP response that caused this error

	Code    int64
	Type    string
	Message string
}

An ErrorResponse reports an error caused by an API request. Onelogin always returns Code, Type and a Message associated to the error. Example:

{
    "status": {
        "error": true,
        "code": 400,
        "type": "bad request",
        "message": "Content Type is not specified or specified incorrectly.
                    Content-Type header must be set to application/json"
    }
}

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

type Group

type Group struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

Group contains the ID (immutable) and name (mutable) of a group.

type GroupService

type GroupService struct {
	// contains filtered or unexported fields
}

GroupService deals with OneLogin groups.

func (*GroupService) GetGroups

func (s *GroupService) GetGroups(ctx context.Context) ([]*Group, error)

GetGroups returns all the OneLogin groups.

type LoginService

type LoginService struct {
	// contains filtered or unexported fields
}

LoginService handles communications with login pages. https://developers.onelogin.com/api-docs/1/login-page/login-user-via-api

func (*LoginService) Authenticate

func (s *LoginService) Authenticate(ctx context.Context, emailOrUsername string, password string) (*AuthenticatedUser, error)

Authenticate a user with an email (or username) and a password. Note that a user can *always* successfully authenticate whether or not MFA is required. To check whether a user is able to verify with strict MFA compliance, AuthenticateWithVerify should be used.

Example

Authenticate a user with a username (or email) and password. Authenticate is not strict with respect to MFA compliance: if the username/password are correct, a successful response will be generated even if user's policy requires MFA.

package main

import (
	"context"
	"fmt"

	"github.com/asobrien/onelogin"
)

func main() {
	c := onelogin.New("clientID", "clientSecret", "us", "myteam")
	user, err := c.Login.Authenticate(context.Background(), "username", "password")
	if err != nil {
		panic(err)
	}
	fmt.Println(user)
}
Output:

func (*LoginService) AuthenticateWithPushVerify

func (s *LoginService) AuthenticateWithPushVerify(ctx context.Context, emailOrUsername string, password string, device string) (*AuthResponse, error)

AuthenticateWithPushVerify can be used with asynchronous factor methods (e.g., SMS). This function is first called to verify username/password authentication and then to generate a push event. Note that this function does not return user information if authentication is successful, a follow call via VerifyPushToken is required to verify the passcode generated in the push event and complete authentication.

Example

AuthenticateWithPushVerify authenticates a user with a username (or email) and password, and then generates a token which is delivered to a client asynchronously (e.g., SMS). To complete the authentication, the token must be verified via a followup call with VerifyPushToken.

In this example, the token is entered via a prompt and read from stdin.

package main

import (
	"bufio"
	"context"
	"fmt"
	"os"

	"github.com/asobrien/onelogin"
)

func main() {
	c := onelogin.New("clientID", "clientSecret", "us", "myteam")

	// Authenticate and generate a SMS token
	resp, err := c.Login.AuthenticateWithPushVerify(context.Background(), "username", "password", "OneLogin SMS")
	if err != nil {
		panic(err)
	}

	// prompt for token
	reader := bufio.NewReader(os.Stdin)
	fmt.Print("Enter Passcode: ")
	token, err := reader.ReadString('\n')
	if err != nil {
		panic(err)
	}

	// verify token and conmplete authentication
	auth, err := c.Login.VerifyPushToken(context.Background(), resp, token)
	if err != nil {
		panic(err)
	}
	fmt.Println(auth)
}
Output:

func (*LoginService) AuthenticateWithVerify

func (s *LoginService) AuthenticateWithVerify(ctx context.Context, emailOrUsername string, password string, device string, token string) (*AuthenticatedUser, error)

AuthenticateWithVerify is used to strictly verify that a user is able both: authenticate with username and password AND to verify a user's second-factor device. If both conditions are not satisfied an error will be returned.

Example

AuthenticateWithVerify authenticates a user with a username (or email) and password, additionally a token from a second-factor device must be provided. This method can be used to ensure that a user is only authenticated if and only if the username and password are correct and valid second factor is provided.

package main

import (
	"context"
	"fmt"

	"github.com/asobrien/onelogin"
)

func main() {
	c := onelogin.New("clientID", "clientSecret", "us", "myteam")
	user, err := c.Login.AuthenticateWithVerify(context.Background(), "username", "password", "Google Authenticator", "123456")
	if err != nil {
		panic(err)
	}
	fmt.Println(user)
}
Output:

func (*LoginService) VerifyPushToken

func (s *LoginService) VerifyPushToken(ctx context.Context, auth *AuthResponse, token string) (*AuthenticatedUser, error)

VerifyPushToken is a follow-on to AuthenticateWithPushVerify and it used to complete second-factor authentication of an asynchronous device. If this is called prior to the generation of a token via AuthenticateWithPushVerify, an error will be returned.

type OauthService

type OauthService struct {
	// contains filtered or unexported fields
}

OauthService handles communications with the authentication related methods on OneLogin.

type Response

type Response struct {
	*http.Response

	PaginationAfterCursor  *string
	PaginationBeforeCursor *string
}

Response embeds a *http.Response as well as some Paginations values.

type Role

type Role struct {
	ID   int64  `json:"id"`
	Name string `json:"name"`
}

Role contains the ID (immutable) and name (mutable) of a role.

type RoleService

type RoleService struct {
	// contains filtered or unexported fields
}

RoleService deals with OneLogin roles.

func (*RoleService) GetRole

func (s *RoleService) GetRole(ctx context.Context, id int64) (*Role, error)

GetRole returns a OneLogin role specified by its ID.

func (*RoleService) GetRoles

func (s *RoleService) GetRoles(ctx context.Context) ([]*Role, error)

GetRoles returns all the OneLogin Roles.

type SAMLAssertion added in v0.2.0

type SAMLAssertion struct {
	Status    string
	Message   string
	Assertion *string
	MFA       *SAMLResponseMFA
}

SAMLAssertion is a struct that contains the SAML assertion response, it contains both the Assertion and the MFAResponse. Note that only one of these fields won't be nil, depending on the response from the endpoing. If MFA is required, this won't contain the Assertion but will contain the an initialized SAMLResponseMFA struct which contains additional information required to proceed.

type SAMLResponseMFA added in v0.2.0

type SAMLResponseMFA struct {
	StateToken  string             `json:"state_token"`
	Devices     []*Device          `json:"devices"`
	CallbackURL string             `json:"callback_url"`
	User        *AuthenticatedUser `json:"user"`
}

SAMLResponseMFA is a struct that contains details about MFA verification.

type SAMLService added in v0.2.0

type SAMLService struct {
	// contains filtered or unexported fields
}

SAMLService deals with OneLogin SAML assertions.

func (*SAMLService) GenerateSAMLAssertion added in v0.2.0

func (s *SAMLService) GenerateSAMLAssertion(ctx context.Context, emailOrUsername, password, appID, ipAddress string) (*SAMLAssertion, error)

GenerateSAMLAssertion returns the SAML assertion if MFA is not required, in the case that MFA is required that info is part of the response.

func (*SAMLService) GenerateSAMLAssertionWithVerify added in v0.2.0

func (s *SAMLService) GenerateSAMLAssertionWithVerify(ctx context.Context, emailOrUsername, password, appID, ipAddress string, device string, token string) (*SAMLAssertion, error)

GenerateSAMLAssertionWithVerify returns a SAML assertion forcing the use of synchronous MFA at the time this function is called. This can be used with with synchronous methods like 'Google Authenticator'.

type User

type User struct {
	ActivatedAt          string            `json:"activated_at"`
	CreatedAt            string            `json:"created_at"`
	Email                string            `json:"email"`
	Username             string            `json:"username"`
	FirstName            string            `json:"firstname"`
	GroupID              int64             `json:"group_id"`
	ID                   int64             `json:"id"`
	InvalidLoginAttempts int64             `json:"invalid_login_attempts"`
	InvitationSentAt     string            `json:"invitation_sent_at"`
	LastLogin            string            `json:"last_login"`
	LastName             string            `json:"lastname"`
	LockedUntil          string            `json:"locked_until"`
	Notes                string            `json:"notes"`
	OpenidName           string            `json:"openid_name"`
	LocaleCode           string            `json:"locale_code"`
	PasswordChangedAt    string            `json:"password_changed_at"`
	Phone                string            `json:"phone"`
	Status               int64             `json:"status"`
	UpdatedAt            string            `json:"updated_at"`
	DistinguishedName    string            `json:"distinguished_name"`
	ExternalID           string            `json:"external_id"`
	DirectoryID          int64             `json:"directory_id"`
	MemberOf             []string          `json:"member_of"`
	SamAccountName       string            `json:"samaccountname"`
	UserPrincipalName    string            `json:"userprincipalname"`
	ManagerAdID          int               `json:"manager_ad_id"`
	RoleIDs              []int64           `json:"role_id"`
	CustomAttributes     map[string]string `json:"custom_attributes"`
}

User represents a OneLogin user.

type UserService

type UserService struct {
	// contains filtered or unexported fields
}

UserService handles communications with the authentication related methods on OneLogin.

func (*UserService) GetCustomAttributes added in v0.4.1

func (s *UserService) GetCustomAttributes(ctx context.Context) ([]string, error)

GetCustomAttributes returns a list of all custom attributes fields (also known as custom user fields) that have been defined for your account.

https://developers.onelogin.com/api-docs/1/users/get-custom-attributes

func (*UserService) GetUser

func (s *UserService) GetUser(ctx context.Context, id int64) (*User, error)

GetUser returns a OneLogin user specified by id.

func (*UserService) GetUsers

func (s *UserService) GetUsers(ctx context.Context) ([]*User, error)

GetUsers returns all the OneLogin users.

func (*UserService) UpdateCustomAttributes

func (s *UserService) UpdateCustomAttributes(ctx context.Context, id int64, attributes map[string]string) error

UpdateCustomAttributes returns a OneLogin user.

Directories

Path Synopsis
cmd
saml-proxy-server
saml-proxy-server provides a server that can be used to proxy SAML assertion requests from a trusted server.
saml-proxy-server provides a server that can be used to proxy SAML assertion requests from a trusted server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL