Class: UuOidc::Session

Inherits:
UuApp::Authentication::Session
  • Object
show all
Defined in:
lib/uu_oidc/session.rb

Overview

Session provides uuOIDC Client API for Authentication of Users and Clients by OAuth2 or OpenId Connect protocol. There are some other context-aware classes derived from this class, that provide specialized API for different types of applications:

There are supported following OAuth2/OpenIDConnect flows for authentication: specified by http://openid.net/specs/openid-connect-core-1_0.html#Authentication and/or https://tools.ietf.org/html/rfc6749

  • Authorization-code Grant - should be used for interactive user authentication (browser-based-login), it is the most secure way for authentication, supports federated logins like Google, Microsoft, Facebook, SingleSignOn, RememberME, etc.
  • Resource Owner Password Credentials Grant - for authentication of user with known credentials, should not be used for interactive user authentication, it is intended for use with credentials stored somewhere in configuration/password files.

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#provider_uriObject (readonly)

Returns the value of attribute provider_uri



237
238
239
# File 'lib/uu_oidc/session.rb', line 237

def provider_uri
  @provider_uri
end

Class Method Details

.get_access_token_grant_code_uri(parameters = nil) ⇒ String

Deprecated.

Method to obtain URI that could be opened in browser to obtain Access Token Code. This URI is used for interactive User Authentication. It should be redirected or opened in web browser. The Access Token Code is obtained as result of authentication. Than the AccessTokenCode should be used for login(accessTokenCode:code) method, to obtain AccessToken and initialize this session.

require 'uu_oidc'

uri = UuOidc::Session.get_access_token_grant_code_uri()

puts 'Open following URI in browser and follow instructions to return back here with generated Access Token Code.'
puts "Login URI: #{uri}"
puts 'Enter your Access Token Code:'
access_token_code = STDIN.gets.chomp

ses = UuOidc::Session.(code: access_token_code)
puts "Welcome #{ses.identity[:name]}!"

Parameters:

  • parameters (Hash) (defaults to: nil)

    the parameters for Code grant flow.

Options Hash (parameters):

  • :scope (Array[String])
    • Optional. The scope value must begin with the string ‘openid’ and then include ‘profile’ or ‘email’ or both. In addition to these OpenID-specific scopes, your scope argument can also include other scope strings.
  • :state (String)
    • Optional. An opaque string that is round-tripped in the protocol; that is to say, it is returned as a URI parameter in the Basic flow. The state can be useful for correlating requests and responses. Because your redirect_uri can be guessed, using a state value can increase your assurance that an incoming connection is the result of an authentication request.
  • :redirect_uri (String)
    • Optional. Determines where the response is sent.
  • :prompt (String)
    • Optional. A space-delimited list of string values that specifies whether the authorization server prompts the user for reauthentication. The possible values are: none, login. The authorization server does not display any authentication screen; it will return an error if the user is not already authenticated. You can use none to check for existing authentication.
  • :max_age (Integer)
    • Optional. Maximal age of authentication in seconds.
  • :acr_values (Array[String])
    • Optional. LoginLevelOfAssurance, values >0 are for non-anonymous login

Returns:

  • (String)

    URI, that should be open in browser to obtain authenticated access code.

Raises:

  • (UuOidc::Commons::OidcError)

    When some unexpected problem occurred in URI construction.



161
162
163
164
165
166
# File 'lib/uu_oidc/session.rb', line 161

def self.get_access_token_grant_code_uri(parameters = nil)
  parameters = UuApp::Util::UniformHash.from_hash(parameters)
  oauth2 = UuOidc::OAuth2::OAuth2.new(parameters)
  code_grant_uri = oauth2.get_access_code_uri(parameters)
  return code_grant_uri
end

.login(parameters = nil) ⇒ UuOidc::Session

Deprecated.

Factory method used to construct new UuOidc::Session instance.

require 'uu_oidc'


# Change to your user credentials
CREDENTIALS = { access_code1: 'user_frog', access_code2: 'Frog2016Secret$' }

ses=UuOidc::Session.(CREDENTIALS)

puts("Welcome: #{ses.identity}")

Parameters:

  • parameters (Hash) (defaults to: nil)

    the parameters to create a UuOidc::Session with OAuth flows.

Options Hash (parameters):

  • :code (String)
    • initialize Session by CODE obtained from Code-based grant flow, use get_access_token_grant_code_uri to prepare URI to obtain authorization CODE. Prefer this flow instead of direct username/password.
  • :access_token (String)
    • initialize Session from existing access or ID token issued by OIDC Server.
  • :access_code1 (String)

    or :username - registered user name identifier. “access_code1” is UU specific alias for “username” parameter.

  • :access_code2 (String)

    or :password - user secret to be used for authentication. “access_code2” is UU specific alias for “password” parameter.

  • :options (Hash)

    Options to override global uuApp Configuration.

Returns:

Raises:

  • (UuOidc::Commons::OidcError)

    When some unexpected problem occurred in authentication.



126
127
128
129
130
131
# File 'lib/uu_oidc/session.rb', line 126

def self.(parameters = nil)
  parameters = UuApp::Util::UniformHash.from_hash(parameters)
  options = parameters.delete(:options)
  parameters[:client_credentials] = options[:client_credentials] if options
  return UuOidc::AuthenticationService.new(options).authenticate(parameters)
end

.loginInteractive(parameters = nil) ⇒ UuOidc::AppSession::InstalledAppClientSession

Deprecated.

This method could be used for interactive login for situations where user interaction is possible. Like for login from installed applications, or for login from ruby console, etc. The web browser window will be opened for user authentication.

require 'uu_oidc'

ses = UuOidc::Session.loginInteractive()
puts "Welcome #{ses.identity[:name]}!"

ses = UuOidc::Session.loginInteractive(prompt: 'login') # force login prompt
puts "Welcome #{ses.identity[:name]}!"

Parameters:

  • parameters (Hash) (defaults to: nil)

    the parameters to create a UuOidc::Session with OAuth flows.

Options Hash (parameters):

  • :options (Hash)

    Options to override global uuApp Configuration.

Returns:

Raises:

  • (UuOidc::Commons::OidcError)

    When some unexpected problem occurred in authentication.



141
142
143
144
145
# File 'lib/uu_oidc/session.rb', line 141

def self.loginInteractive(parameters = nil)
  parameters = UuApp::Util::UniformHash.from_hash(parameters)
  options = parameters.delete(:options)
  return UuOidc::AuthenticationService.new(options).authenticate(nil)
end

Instance Method Details

#app_identityHash

Deprecated.

Use application_identity

Attributes managed for current application in application registry. When application is not registered, then common data for unregistered applications will be used. To obtain this informations the Session must be initialized with client_credentials associated with this application. * :id [String] - Unique identifier of AppIdentity. * :name [String] - AppIdentity display name.

Returns:

  • (Hash)

    AppIdentity claims.



174
175
176
# File 'lib/uu_oidc/session.rb', line 174

def app_identity
  return application_identity
end

#call_token(scope = nil, requested_token_type = OAUTH_TOKEN_TYPE_QUALIFIED_ID_TOKEN) ⇒ Object



292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/uu_oidc/session.rb', line 292

def call_token(scope = nil, requested_token_type = OAUTH_TOKEN_TYPE_QUALIFIED_ID_TOKEN)
  cache_key = "#{@provider_uri}|#{identity.uu_identity || "NA"}|#{scope || "NA"}"
  call_token = cache[cache_key]
  if !call_token
    credentials = UuOidc::Internal::ClientCredentials.get_credentials
    scope = "#{scope} #{OAUTH_SCOPE_OPENID}"
    token = @oauth_client.exchange_token(@id_token || @access_token, credentials, scope)
    if requested_token_type == OAUTH_TOKEN_TYPE_QUALIFIED_ID_TOKEN
      call_token = "Bearer #{token[:id_token]}"
    else
      call_token = "Bearer #{token[:access_token]}"
    end
    cache[cache_key] = call_token
  end
  return call_token
end

#client_app_identity(opts = nil) ⇒ Hash

Deprecated.

Same as app_identity - but this is info about Client Application calling the current uuApp Server Controller with this Session. * :id [String] - Unique identifier of AppIdentity. * :name [String] - AppIdentity display name.

Returns:

  • (Hash)

    AppIdentity claims.



183
184
185
# File 'lib/uu_oidc/session.rb', line 183

def client_app_identity(opts = nil)
  return application_identity
end

#closeObject



309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/uu_oidc/session.rb', line 309

def close
  super
  credentials = UuOidc::Internal::ClientCredentials.get_credentials
  if @id_token || @access_token
    begin
      @oauth_client.revoke_token(@id_token || @access_token, credentials)
    rescue => e
      # TODO Log error
    end
  end
  @id_token = nil
  @access_token = nil
  return nil
end

#ensure_login(ctrl_env, parameters) ⇒ Void

Deprecated.

Operation is used for check the authentication parameters, when not satisfied the client will be forced with Error to authenticate with requested parameters first. There may be some use cases where the application needs to reassure itself that the authenticated user is already on client side - the login is fresh (max_login_age). Or the application needs to ensure that the authentication was processed with specific secure way - login_level_of_assurance.

require 'uu_oidc'

# This OIDCSampleController must be used with uuAppServer
class OIDCSampleController

  def echo(ctrl_env)

    ses = ctrl_env.session() # obtain current oidc session
    ses.(ctrl_env, { login_level_of_assurance: [UuOidc::Session::OAUTH_ACR_LOA_1, UuOidc::Session::OAUTH_ACR_LOA_2, UuOidc::Session::OAUTH_ACR_LOA_3],
                                 max_login_age: 30 })

    dtoOut = {}
    dtoOut[:sid] = ses.sid() # access unique oidc session ID
    dtoOut[:identity] = ses.identity() # obtain info about User identity
    dtoOut[:client_app_identity] = ses.client_app_identity() # obtain info about
    dtoOut[:app_identity] = ses.app_identity() # info about current application
    dtoOut[:call_token] = ses.get_call_token() # generate token to call other apps
    ctrl_env.result = dtoOut
  end

end

Parameters:

  • :ctrl_env (UuApp::AppServer::UseCaseEnvironment)
    • current controller environment, used to return error to client to force login when needed.
  • parameters (Hash)
    • What login parameters should be checked

Options Hash (parameters):

  • :max_login_age (Integer)
    • Optional. Maximal age of authentication in seconds.
  • :login_level_of_assurance (Array[Integer])

    [UuOidc::Session::OAUTH_ACR_LOA_0, UuOidc::Session::OAUTH_ACR_LOA_1, UuOidc::Session::OAUTH_ACR_LOA_2, UuOidc::Session::OAUTH_ACR_LOA_3] - Optional. LoginLevelOfAssurance, values >0 are for non-anonymous login

Returns:

  • (Void)


221
222
223
224
225
226
227
228
229
230
# File 'lib/uu_oidc/session.rb', line 221

def (ctrl_env, parameters)
  parameters = UuApp::Util::UniformHash.from_hash(parameters)
  mloa = parameters[:login_level_of_assurance]
  mloa = mloa.sort.last if mloa.kind_of?(Array)
  maxa = parameters[:max_login_age]
  constraints = {}
  constraints[:min_authentication_level_of_assurance] = mloa if mloa
  constraints[:max_authentication_age] = maxa if maxa
  return assert_trustiness(constraints)
end

#get_call_token(scope = nil, requested_token_type = OAUTH_TOKEN_TYPE_QUALIFIED_ID_TOKEN) ⇒ String

Deprecated.

Method to obtain Token for remote calls, authenticated by uuOpenIDConnect service. Token could be represented as AccessToken or IDToken - based on token_type parameter . IDToken could be larger than AccessToken but faster for verification and user introspection (IDToken contains claims with informations about user, application, etc.). It is recommended for calls, where request size is not problem, but network latency could be bottleneck(AccessToken needs some additional calls for verification and introspection => latency could be problem). AccessToken is much shorter than IDToken but slower verification and user introspection. It is recommended for calls, where request size does matter - like for mobile applications.

require 'uu_oidc'


# Change to your user credentials
CREDENTIALS = { access_code1: 'user_frog', access_code2: 'Frog2016Secret$' }
UU_APP_UC_URI = UuOidc::Discovery::Discovery.new().[:userinfo_endpoint]

ses=UuOidc::Session.(CREDENTIALS)
token = ses.get_call_token()

# call some command
client = HTTPClient.new();
resp = client.get(UU_APP_UC_URI, header: { 'Authorization' => "Bearer #{token}", 'Accept' => 'application/json' })
puts("uuApp response: #{resp.status}, #{resp.content}")

Parameters:

  • scope (String|Array<String>|Uri|Array<Uri>) (defaults to: nil)

    Parameter scope defines the list of targets, that will be called with. The minimal scope format should be TargetApplicationUri with TenantID. Example: scope=’https://oidc.plus4u.net/uu-oidcg01-main/0-0’

  • requested_token_type (enum{OAUTH_TOKEN_TYPE_ID_TOKEN,OAUTH_TOKEN_TYPE_ID_TOKEN}) (defaults to: OAUTH_TOKEN_TYPE_QUALIFIED_ID_TOKEN)

Returns:

  • (String)

    id_token that could be used for call of specified targets (in scope parameter). Access_code could be used for HTTP-Header like: ‘Authorization: Bearer access_token’

See Also:

  • - for use with CommandClient for seamless integration.


203
204
205
206
207
# File 'lib/uu_oidc/session.rb', line 203

def get_call_token(scope = nil, requested_token_type = OAUTH_TOKEN_TYPE_QUALIFIED_ID_TOKEN)
  token = call_token(scope, requested_token_type)
  # Original method was returning token without prefix
  return token.sub(/^Bearer /i, '')
end

#logout(parameters = nil) ⇒ Object

Deprecated.

Use #close

Logout current session from uuOIDC server.



326
327
328
# File 'lib/uu_oidc/session.rb', line 326

def logout(parameters=nil)
  return close()
end

#sidObject

Deprecated.


233
234
235
# File 'lib/uu_oidc/session.rb', line 233

def sid
  return authentication_id
end