MySQL Export

Hi, I’m trying to export a database with MySQL Workbench 8.0. But when I try to export my data the following error appears :

“Error Unhandled exception : local variable ‘pwd’ referenced before assignment”

I use Wamp server.

Can you help me ?

This sounds like a bug on either workbench or mysql server. Are you running version 8.0.18 of workbench? On what version of mysql?

In version 6.xx i had a similar bug and upgrading workbench to the latest version solved it.

Hi, the bug was that the server didn’t execute the correct version of powershell, but thanks for your reply

how did you fix this buddy?

For me the problem was with blank root password. Changing it to any valid password solved it.

Related Topics

Topic Replies Views Activity
Business 0 24 December 1, 2008
Programming & Development 1 44 December 1, 2008
Business 34 428 December 16, 2008
Databases 2 87 June 26, 2019
Databases 13 110 August 17, 2010

unhandled exception local variable 'pwd' referenced before assignment

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

MYSQL_PWD and access denied

My system monitoring program isn't working anymore since upgrading from Ubuntu Server 14.04 to 16.04 with MySQL 5.6 to 5.7. It performs the following command:

It also sets the MYSQL_PWD environment variable for that process to the required password. The error message however is:

When I try it interactively, it works fine:

When I try to reproduce the tool's behaviour like this, it also fails:

So isn't MYSQL_PWD supported anymore? But it says "using password: YES" so it must have noticed my environment variable. It just doesn't seem to read it right.

ygoe's user avatar

  • What happens if you try to use MYSQL_PWD='xxx' mysql -u statuser -p –  Kristopher Ives Commented Nov 27, 2016 at 13:59
  • Maybe the easiest solution would be to store the password in some other way. The MySQL docs describe multiple ways, and expressively say that using the MYSQL_PWD env variable is discouraged. –  Henning Kockerbeck Commented Nov 27, 2016 at 13:59
  • If I set the variable and the -p parameter, I need to type in the password. If I just press Enter then, it says "access denided, using password: NO" –  ygoe Commented Nov 27, 2016 at 14:00
  • Thanks I was trying to see if the MYSQL_PWD works for regular mysql client, which it doesn't appear to be working. Can you try making a new user with a very simple password no spaces and try setting that like MYSQL_PWD=abc123 mysql -u newuser I'm thinking some kind of quote trimming has changed –  Kristopher Ives Commented Nov 27, 2016 at 14:03
  • That is already a separate user for this statistics purpose. The password does not contain spaces. I've now changed it to pass the password as command line argument, for the "insecure" but not "extremely insecure" option. It prints a warning into my terminal from the background, but that won't bother me once I get that tool running as a service again. (Stupid upstart has been replaced by systemd, too... As if Ubuntu knew their special solution wouldn't last long.) –  ygoe Commented Nov 27, 2016 at 14:13

Hey buddies I used these commands and it solved my issue:

Hope it should relieve you the agony

bademba's user avatar

  • 2 Can't downvote. What does this answer have to do with my question? –  ygoe Commented Nov 29, 2016 at 21:41

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged mysql ..

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites

Hot Network Questions

  • Has any spacecraft ever been severely damaged by a micrometeorite?
  • Is "UN law" a thing?
  • Is it possible for a company to dilute my shares to the point they are insignificant
  • Can I take tea with me to Canada?
  • How to remove a file named "."?
  • Retroactively specifying `-only` or `-or-later` for GPLv2 in an adopted project
  • Why is the identity of the actor voicing Spider-Man kept secret even in the commentary?
  • Constructing a specific 2-variable function taking integer arguments whose value is odd/even only when arguments are equal
  • Series of discrete groups with a Lie group limit
  • Why name the staves in LilyPond's "published" "Solo piano" template?
  • Did Esau sell his birthright under duress?
  • What prevents applications from misusing private keys?
  • Did polls adjust their methodology after overestimating Democrat's shares in the 2016 and 2020 presidential elections in the Rust Belt?
  • Would weightlessness (i.e. in thrill rides, planes, skydiving, etc.) be different on a Flat Earth?
  • How to make two alignments in the environment align?
  • What is the origin of this quote on telling a big lie?
  • Accents on abbreviations of words
  • The meaning of “manage” in this context
  • How to add content security headers in Next.js which are configurable from cms side? where to add?
  • What is the rationale behind requiring ATC to retire at age 56?
  • Handling Race Condition with Concurrent SOQL Queries in Salesforce Integration
  • Why don't we observe protons deflecting in J.J. Thomson's experiment?
  • On intersection theory on toric varieties
  • Faster simulation of two spins

unhandled exception local variable 'pwd' referenced before assignment

Fix "local variable referenced before assignment" in Python

unhandled exception local variable 'pwd' referenced before assignment

Introduction

If you're a Python developer, you've probably come across a variety of errors, like the "local variable referenced before assignment" error. This error can be a bit puzzling, especially for beginners and when it involves local/global variables.

Today, we'll explain this error, understand why it occurs, and see how you can fix it.

The "local variable referenced before assignment" Error

The "local variable referenced before assignment" error in Python is a common error that occurs when a local variable is referenced before it has been assigned a value. This error is a type of UnboundLocalError , which is raised when a local variable is referenced before it has been assigned in the local scope.

Here's a simple example:

Running this code will throw the "local variable 'x' referenced before assignment" error. This is because the variable x is referenced in the print(x) statement before it is assigned a value in the local scope of the foo function.

Even more confusing is when it involves global variables. For example, the following code also produces the error:

But wait, why does this also produce the error? Isn't x assigned before it's used in the say_hello function? The problem here is that x is a global variable when assigned "Hello ". However, in the say_hello function, it's a different local variable, which has not yet been assigned.

We'll see later in this Byte how you can fix these cases as well.

Fixing the Error: Initialization

One way to fix this error is to initialize the variable before using it. This ensures that the variable exists in the local scope before it is referenced.

Let's correct the error from our first example:

In this revised code, we initialize x with a value of 1 before printing it. Now, when you run the function, it will print 1 without any errors.

Fixing the Error: Global Keyword

Another way to fix this error, depending on your specific scenario, is by using the global keyword. This is especially useful when you want to use a global variable inside a function.

No spam ever. Unsubscribe anytime. Read our Privacy Policy.

Here's how:

In this snippet, we declare x as a global variable inside the function foo . This tells Python to look for x in the global scope, not the local one . Now, when you run the function, it will increment the global x by 1 and print 1 .

Similar Error: NameError

An error that's similar to the "local variable referenced before assignment" error is the NameError . This is raised when you try to use a variable or a function name that has not been defined yet.

Running this code will result in a NameError :

In this case, we're trying to print the value of y , but y has not been defined anywhere in the code. Hence, Python raises a NameError . This is similar in that we are trying to use an uninitialized/undefined variable, but the main difference is that we didn't try to initialize y anywhere else in our code.

Variable Scope in Python

Understanding the concept of variable scope can help avoid many common errors in Python, including the main error of interest in this Byte. But what exactly is variable scope?

In Python, variables have two types of scope - global and local. A variable declared inside a function is known as a local variable, while a variable declared outside a function is a global variable.

Consider this example:

In this code, x is a global variable, and y is a local variable. x can be accessed anywhere in the code, but y can only be accessed within my_function . Confusion surrounding this is one of the most common causes for the "variable referenced before assignment" error.

In this Byte, we've taken a look at the "local variable referenced before assignment" error and another similar error, NameError . We also delved into the concept of variable scope in Python, which is an important concept to understand to avoid these errors. If you're seeing one of these errors, check the scope of your variables and make sure they're being assigned before they're being used.

unhandled exception local variable 'pwd' referenced before assignment

Monitor with Ping Bot

Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

OpenAI

© 2013- 2024 Stack Abuse. All rights reserved.

Local variable referenced before assignment in Python

avatar

Last updated: Apr 8, 2024 Reading time · 4 min

banner

# Local variable referenced before assignment in Python

The Python "UnboundLocalError: Local variable referenced before assignment" occurs when we reference a local variable before assigning a value to it in a function.

To solve the error, mark the variable as global in the function definition, e.g. global my_var .

unboundlocalerror local variable name referenced before assignment

Here is an example of how the error occurs.

We assign a value to the name variable in the function.

# Mark the variable as global to solve the error

To solve the error, mark the variable as global in your function definition.

mark variable as global

If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global .

# Local variables shadow global ones with the same name

You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the global one.

accessing global variables in functions

Accessing the name variable in the function is perfectly fine.

On the other hand, variables declared in a function cannot be accessed from the global scope.

variables declared in function cannot be accessed in global scope

The name variable is declared in the function, so trying to access it from outside causes an error.

Make sure you don't try to access the variable before using the global keyword, otherwise, you'd get the SyntaxError: name 'X' is used prior to global declaration error.

# Returning a value from the function instead

An alternative solution to using the global keyword is to return a value from the function and use the value to reassign the global variable.

return value from the function

We simply return the value that we eventually use to assign to the name global variable.

# Passing the global variable as an argument to the function

You should also consider passing the global variable as an argument to the function.

pass global variable as argument to function

We passed the name global variable as an argument to the function.

If we assign a value to a variable in a function, the variable is assumed to be local unless explicitly declared as global .

# Assigning a value to a local variable from an outer scope

If you have a nested function and are trying to assign a value to the local variables from the outer function, use the nonlocal keyword.

assign value to local variable from outer scope

The nonlocal keyword allows us to work with the local variables of enclosing functions.

Had we not used the nonlocal statement, the call to the print() function would have returned an empty string.

not using nonlocal prints empty string

Printing the message variable on the last line of the function shows an empty string because the inner() function has its own scope.

Changing the value of the variable in the inner scope is not possible unless we use the nonlocal keyword.

Instead, the message variable in the inner function simply shadows the variable with the same name from the outer scope.

# Discussion

As shown in this section of the documentation, when you assign a value to a variable inside a function, the variable:

  • Becomes local to the scope.
  • Shadows any variables from the outer scope that have the same name.

The last line in the example function assigns a value to the name variable, marking it as a local variable and shadowing the name variable from the outer scope.

At the time the print(name) line runs, the name variable is not yet initialized, which causes the error.

The most intuitive way to solve the error is to use the global keyword.

The global keyword is used to indicate to Python that we are actually modifying the value of the name variable from the outer scope.

  • If a variable is only referenced inside a function, it is implicitly global.
  • If a variable is assigned a value inside a function's body, it is assumed to be local, unless explicitly marked as global .

If you want to read more about why this error occurs, check out [this section] ( this section ) of the docs.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

  • SyntaxError: name 'X' is used prior to global declaration

book cover

Borislav Hadzhiev

Web Developer

buy me a coffee

Copyright © 2024 Borislav Hadzhiev

How to fix UnboundLocalError: local variable 'x' referenced before assignment in Python

You could also see this error when you forget to pass the variable as an argument to your function.

How to reproduce this error

How to fix this error.

I hope this tutorial is useful. See you in other tutorials.

Take your skills to the next level ⚡️

How to Fix Local Variable Referenced Before Assignment Error in Python

How to Fix Local Variable Referenced Before Assignment Error in Python

Table of Contents

Fixing local variable referenced before assignment error.

In Python , when you try to reference a variable that hasn't yet been given a value (assigned), it will throw an error.

That error will look like this:

In this post, we'll see examples of what causes this and how to fix it.

Let's begin by looking at an example of this error:

If you run this code, you'll get

The issue is that in this line:

We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the variable that we defined in the first line.

If we want to refer the variable that was defined in the first line, we can make use of the global keyword.

The global keyword is used to refer to a variable that is defined outside of a function.

Let's look at how using global can fix our issue here:

Global variables have global scope, so you can referenced them anywhere in your code, thus avoiding the error.

If you run this code, you'll get this output:

In this post, we learned at how to avoid the local variable referenced before assignment error in Python.

The error stems from trying to refer to a variable without an assigned value, so either make use of a global variable using the global keyword, or assign the variable a value before using it.

Thanks for reading!

unhandled exception local variable 'pwd' referenced before assignment

  • Privacy Policy
  • Terms of Service

[SOLVED] Local Variable Referenced Before Assignment

local variable referenced before assignment

Python treats variables referenced only inside a function as global variables. Any variable assigned to a function’s body is assumed to be a local variable unless explicitly declared as global.

Why Does This Error Occur?

Unboundlocalerror: local variable referenced before assignment occurs when a variable is used before its created. Python does not have the concept of variable declarations. Hence it searches for the variable whenever used. When not found, it throws the error.

Before we hop into the solutions, let’s have a look at what is the global and local variables.

Local Variable Declarations vs. Global Variable Declarations

Local VariablesGlobal Variables
A variable is declared primarily within a Python function.Global variables are in the global scope, outside a function.
A local variable is created when the function is called and destroyed when the execution is finished.A Variable is created upon execution and exists in memory till the program stops.
Local Variables can only be accessed within their own function.All functions of the program can access global variables.
Local variables are immune to changes in the global scope. Thereby being more secure.Global Variables are less safer from manipulation as they are accessible in the global scope.

[Fixed] typeerror can’t compare datetime.datetime to datetime.date

Local Variable Referenced Before Assignment Error with Explanation

Try these examples yourself using our Online Compiler.

Let’s look at the following function:

Local Variable Referenced Before Assignment Error

Explanation

The variable myVar has been assigned a value twice. Once before the declaration of myFunction and within myFunction itself.

Using Global Variables

Passing the variable as global allows the function to recognize the variable outside the function.

Create Functions that Take in Parameters

Instead of initializing myVar as a global or local variable, it can be passed to the function as a parameter. This removes the need to create a variable in memory.

UnboundLocalError: local variable ‘DISTRO_NAME’

This error may occur when trying to launch the Anaconda Navigator in Linux Systems.

Upon launching Anaconda Navigator, the opening screen freezes and doesn’t proceed to load.

Try and update your Anaconda Navigator with the following command.

If solution one doesn’t work, you have to edit a file located at

After finding and opening the Python file, make the following changes:

In the function on line 159, simply add the line:

DISTRO_NAME = None

Save the file and re-launch Anaconda Navigator.

DJANGO – Local Variable Referenced Before Assignment [Form]

The program takes information from a form filled out by a user. Accordingly, an email is sent using the information.

Upon running you get the following error:

We have created a class myForm that creates instances of Django forms. It extracts the user’s name, email, and message to be sent.

A function GetContact is created to use the information from the Django form and produce an email. It takes one request parameter. Prior to sending the email, the function verifies the validity of the form. Upon True , .get() function is passed to fetch the name, email, and message. Finally, the email sent via the send_mail function

Why does the error occur?

We are initializing form under the if request.method == “POST” condition statement. Using the GET request, our variable form doesn’t get defined.

Local variable Referenced before assignment but it is global

This is a common error that happens when we don’t provide a value to a variable and reference it. This can happen with local variables. Global variables can’t be assigned.

This error message is raised when a variable is referenced before it has been assigned a value within the local scope of a function, even though it is a global variable.

Here’s an example to help illustrate the problem:

In this example, x is a global variable that is defined outside of the function my_func(). However, when we try to print the value of x inside the function, we get a UnboundLocalError with the message “local variable ‘x’ referenced before assignment”.

This is because the += operator implicitly creates a local variable within the function’s scope, which shadows the global variable of the same name. Since we’re trying to access the value of x before it’s been assigned a value within the local scope, the interpreter raises an error.

To fix this, you can use the global keyword to explicitly refer to the global variable within the function’s scope:

However, in the above example, the global keyword tells Python that we want to modify the value of the global variable x, rather than creating a new local variable. This allows us to access and modify the global variable within the function’s scope, without causing any errors.

Local variable ‘version’ referenced before assignment ubuntu-drivers

This error occurs with Ubuntu version drivers. To solve this error, you can re-specify the version information and give a split as 2 –

Here, p_name means package name.

With the help of the threading module, you can avoid using global variables in multi-threading. Make sure you lock and release your threads correctly to avoid the race condition.

When a variable that is created locally is called before assigning, it results in Unbound Local Error in Python. The interpreter can’t track the variable.

Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable declaration have been explained, and multiple solutions regarding the issue have been provided.

Trending Python Articles

[Fixed] nameerror: name Unicode is not defined

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications You must be signed in to change notification settings

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement . We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

UnboundLocalError: local variable 'pwd' referenced before assignment #730

@andre-merzky

vivek-bala commented Sep 17, 2015

I got this error with one of jenkins tests for extasy-0.1. ExTASY 0.1 uses rp 0.35 (pypi).
This is while running on Stampede. T

Full log:

This is not repeatable, the next build is successful.

@andre-merzky

andre-merzky commented Sep 18, 2015

This is resolved in devel now. Thanks!

Sorry, something went wrong.

No branches or pull requests

@andre-merzky

Login / Register

  • Developer Zone
  • Report a bug
  • Advanced search
  • Saved searches
Bug #52981 unhandled exception: local variable 'tables' referenced before assignment
Submitted: 20 Apr 2010 12:34 Modified: 28 Apr 2010 10:53
Reporter: Email Updates:
Status: Closed Impact on me:
Category:MySQL Workbench: Administration Severity:S1 (Critical)
Version:5.2.19 beta OS:Any (XP SP3)
Assigned to: CPU Architecture:Any
Tags: , ,
  • Add Comment
  • Edit Submission
  • View Progress Log
  • Contributions
  • Legal Policies
  • Your Privacy Rights
  • Terms of Use

Portions of this website are copyright © 2001, 2002 The PHP Group

Page generated in 0.026 sec. using MySQL 8.0.36-u4-cloud

Timestamp references displayed by the system are UTC. Content reproduced on this site is the property of the respective copyright holders. It is not reviewed in advance by Oracle and does not necessarily represent the opinion of Oracle or any other party.

The Research Scientist Pod

Python UnboundLocalError: local variable referenced before assignment

by Suf | Programming , Python , Tips

If you try to reference a local variable before assigning a value to it within the body of a function, you will encounter the UnboundLocalError: local variable referenced before assignment.

The preferable way to solve this error is to pass parameters to your function, for example:

Alternatively, you can declare the variable as global to access it while inside a function. For example,

This tutorial will go through the error in detail and how to solve it with code examples .

Table of contents

What is scope in python, unboundlocalerror: local variable referenced before assignment, solution #1: passing parameters to the function, solution #2: use global keyword, solution #1: include else statement, solution #2: use global keyword.

Scope refers to a variable being only available inside the region where it was created. A variable created inside a function belongs to the local scope of that function, and we can only use that variable inside that function.

A variable created in the main body of the Python code is a global variable and belongs to the global scope. Global variables are available within any scope, global and local.

UnboundLocalError occurs when we try to modify a variable defined as local before creating it. If we only need to read a variable within a function, we can do so without using the global keyword. Consider the following example that demonstrates a variable var created with global scope and accessed from test_func :

If we try to assign a value to var within test_func , the Python interpreter will raise the UnboundLocalError:

This error occurs because when we make an assignment to a variable in a scope, that variable becomes local to that scope and overrides any variable with the same name in the global or outer scope.

var +=1 is similar to var = var + 1 , therefore the Python interpreter should first read var , perform the addition and assign the value back to var .

var is a variable local to test_func , so the variable is read or referenced before we have assigned it. As a result, the Python interpreter raises the UnboundLocalError.

Example #1: Accessing a Local Variable

Let’s look at an example where we define a global variable number. We will use the increment_func to increase the numerical value of number by 1.

Let’s run the code to see what happens:

The error occurs because we tried to read a local variable before assigning a value to it.

We can solve this error by passing a parameter to increment_func . This solution is the preferred approach. Typically Python developers avoid declaring global variables unless they are necessary. Let’s look at the revised code:

We have assigned a value to number and passed it to the increment_func , which will resolve the UnboundLocalError. Let’s run the code to see the result:

We successfully printed the value to the console.

We also can solve this error by using the global keyword. The global statement tells the Python interpreter that inside increment_func , the variable number is a global variable even if we assign to it in increment_func . Let’s look at the revised code:

Let’s run the code to see the result:

Example #2: Function with if-elif statements

Let’s look at an example where we collect a score from a player of a game to rank their level of expertise. The variable we will use is called score and the calculate_level function takes in score as a parameter and returns a string containing the player’s level .

In the above code, we have a series of if-elif statements for assigning a string to the level variable. Let’s run the code to see what happens:

The error occurs because we input a score equal to 40 . The conditional statements in the function do not account for a value below 55 , therefore when we call the calculate_level function, Python will attempt to return level without any value assigned to it.

We can solve this error by completing the set of conditions with an else statement. The else statement will provide an assignment to level for all scores lower than 55 . Let’s look at the revised code:

In the above code, all scores below 55 are given the beginner level. Let’s run the code to see what happens:

We can also create a global variable level and then use the global keyword inside calculate_level . Using the global keyword will ensure that the variable is available in the local scope of the calculate_level function. Let’s look at the revised code.

In the above code, we put the global statement inside the function and at the beginning. Note that the “default” value of level is beginner and we do not include the else statement in the function. Let’s run the code to see the result:

Congratulations on reading to the end of this tutorial! The UnboundLocalError: local variable referenced before assignment occurs when you try to reference a local variable before assigning a value to it. Preferably, you can solve this error by passing parameters to your function. Alternatively, you can use the global keyword.

If you have if-elif statements in your code where you assign a value to a local variable and do not account for all outcomes, you may encounter this error. In which case, you must include an else statement to account for the missing outcome.

For further reading on Python code blocks and structure, go to the article: How to Solve Python IndentationError: unindent does not match any outer indentation level .

Go to the  online courses page on Python  to learn more about Python for data science and machine learning.

Have fun and happy researching!

Share this:

  • Click to share on Facebook (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on Pinterest (Opens in new window)
  • Click to share on Telegram (Opens in new window)
  • Click to share on WhatsApp (Opens in new window)
  • Click to share on Twitter (Opens in new window)
  • Click to share on Tumblr (Opens in new window)
  • Python Course
  • Python Basics
  • Interview Questions
  • Python Quiz
  • Popular Packages
  • Python Projects
  • Practice Python
  • AI With Python
  • Learn Python3
  • Python Automation
  • Python Web Dev
  • DSA with Python
  • Python OOPs
  • Dictionaries

UnboundLocalError Local variable Referenced Before Assignment in Python

Handling errors is an integral part of writing robust and reliable Python code. One common stumbling block that developers often encounter is the “UnboundLocalError” raised within a try-except block. This error can be perplexing for those unfamiliar with its nuances but fear not – in this article, we will delve into the intricacies of the UnboundLocalError and provide a comprehensive guide on how to effectively use try-except statements to resolve it.

What is UnboundLocalError Local variable Referenced Before Assignment in Python?

The UnboundLocalError occurs when a local variable is referenced before it has been assigned a value within a function or method. This error typically surfaces when utilizing try-except blocks to handle exceptions, creating a puzzle for developers trying to comprehend its origins and find a solution.

Why does UnboundLocalError: Local variable Referenced Before Assignment Occur?

below, are the reasons of occurring “Unboundlocalerror: Try Except Statements” in Python :

Variable Assignment Inside Try Block

Reassigning a global variable inside except block.

  • Accessing a Variable Defined Inside an If Block

In the below code, example_function attempts to execute some_operation within a try-except block. If an exception occurs, it prints an error message. However, if no exception occurs, it prints the value of the variable result outside the try block, leading to an UnboundLocalError since result might not be defined if an exception was caught.

In below code , modify_global function attempts to increment the global variable global_var within a try block, but it raises an UnboundLocalError. This error occurs because the function treats global_var as a local variable due to the assignment operation within the try block.

Solution for UnboundLocalError Local variable Referenced Before Assignment

Below, are the approaches to solve “Unboundlocalerror: Try Except Statements”.

Initialize Variables Outside the Try Block

Avoid reassignment of global variables.

In modification to the example_function is correct. Initializing the variable result before the try block ensures that it exists even if an exception occurs within the try block. This helps prevent UnboundLocalError when trying to access result in the print statement outside the try block.

 

Below, code calculates a new value ( local_var ) based on the global variable and then prints both the local and global variables separately. It demonstrates that the global variable is accessed directly without being reassigned within the function.

In conclusion , To fix “UnboundLocalError” related to try-except statements, ensure that variables used within the try block are initialized before the try block starts. This can be achieved by declaring the variables with default values or assigning them None outside the try block. Additionally, when modifying global variables within a try block, use the `global` keyword to explicitly declare them.

Please Login to comment...

Similar reads.

  • Python Programs
  • Python Errors

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

solveForum

  • Search forums
  • Solveforum All topics

[Solved] Why am I getting "Unhandled exception: local variable 'pwd' referenced before assignment"?

  • Thread starter Jossy
  • Start date Apr 20, 2023
  • Apr 20, 2023

Jossy Asks: Why am I getting "Unhandled exception: local variable 'pwd' referenced before assignment"? I'm trying to transfer a schema from my personal machine to RDS via Workbench. I've exported an SQL dump file and am trying to import it into RDS. However, I get the following error: Code: Unhandled exception: local variable 'pwd' referenced before assignment Check the log for more details. The log file has this: Code: 14:05:01 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1 14:05:01 [ERR][ pymforms]: Unhandled exception in Python code: Traceback (most recent call last): File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1334, in _update_progress r = self.update_progress() File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 913, in update_progress self.start() File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1323, in start password = self.get_mysql_password(self.bad_password_detected) File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password if pwd is None: UnboundLocalError: local variable 'pwd' referenced before assignment An earlier attempt yielded a little more detail: Code: 14:00:24 [ERR][wb_admin_export.py:process_db:251]: Error from task: ERROR 1045 (28000): Access denied for user 'admin'@'<some_numbers_I_probably_shouldn't_share!>.skybroadband.com' (using password: YES) 14:00:24 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1 14:00:24 [ERR][ pymforms]: Unhandled exception in Python code: Traceback (most recent call last): File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1334, in _update_progress r = self.update_progress() File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 913, in update_progress self.start() File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 1323, in start password = self.get_mysql_password(self.bad_password_detected) File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password if pwd is None: UnboundLocalError: local variable 'pwd' referenced before assignment 14:00:43 [ERR][wb_admin_utils.py:page_activated:329]: Exception activating the page - 'Label' object has no attribute 'remove_from_parent'Error from task: ERROR 1045 (28000): Access denied for user 'admin'@'<some_numbers_I_probably_shouldn't_share!> (using password: YES) This has confused me somewhat as I'm not using Python to transfer anything - I'm using Workbench. Clearly I have a password issue but what is it exactly and how do I fix it? I'm logged into RDS and can add or remove schemas/tables etc manually so Workbench knows what the correct passwords are...  

Recent Threads

Why is it okay for my .bashrc or .zshrc to be writable by my normal user.

  • Zach Huxford
  • Jun 26, 2023
SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the answer that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may not be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your thoughts here to help others. Click to expand...

SFTP user login details real-time filtering

  • Amal P Ramesh

get nat port forwarding IP address

Using docker does not give error with sudo but using ctr does on starting a container, what are some of the latest nike soccer shoes that have gained popularity among players and enthusiasts in recent years, can't change tcp/ipv4 settings on windows 10.

unhandled exception local variable 'pwd' referenced before assignment

Customer service access 2007 template

  • tintincutes

Latest posts

  • Latest: SomeBody
  • 28 minutes ago
  • Latest: user1631306
  • 38 minutes ago
  • Latest: user1973004
  • Latest: Mark Spangler
  • Latest: Sadhin Santo

Newest Members

anvl

unhandled exception local variable 'pwd' referenced before assignment

为什么我会收到“未处理的异常:分配前引用的局部变量 &#39;pwd&#39;”?

[英]Why am I getting "Unhandled exception: local variable 'pwd' referenced before assignment"?

我正在尝试通过 Workbench 将架构从我的个人计算机传输到 RDS。 我已经导出了一个 SQL 转储文件,并试图将其导入 RDS。 但是,我收到以下错误:

较早的尝试产生了更多细节:

这让我有些困惑,因为我没有使用 Python 来传输任何东西——我使用的是 Workbench。 很明显我有一个密码问题,但它到底是什么,我该如何解决? 我已登录 RDS,可以手动添加或删除模式/表等,因此 Workbench 知道正确的密码是什么......

解决方案1  3  2022-02-07 12:44:01

对我来说,错误与 db 权限有关:

您必须从 MySQL Workbench 中数据导出器右上角的“高级选项”中取消选中锁定表选项。

--lock-tables=FALSE flag.--> 如果您使用命令导出,则添加 --lock-tables=FALSE 标志。

在此处输入图像描述

解决方案2  1  2021-03-30 11:47:50

如果您只想迁移数据库结构:

  • 在左侧,在“导航器”面板中选择“管理”
  • 在窗口的右侧,您应该找到一个“选择框”。 Dump Structure and Data to Dump Data only --> 将 Dump Structure and Data 切换为 Dump Data only

Dump Data only when you will import it!--> 同样,只有在导入 Dump Data only !

老实说,我不知道它是如何解决错误的:

'UnboundLocalError: 赋值前引用的局部变量 'pwd',

但只是在没有数据的情况下移动结构对我有用。

在此处输入图像描述

解决方案3  1  2021-11-10 21:21:33

转到 C:\Users\User_Name\AppData\Roaming\MySQL\Workbench\sql_workspaces 并删除出现错误的服务器的工作区,或者以简单的方式,您可以删除 sql_workspaces 中的所有文件夹

unhandled exception local variable 'pwd' referenced before assignment

[英]Why am I getting Error 1054: Unknown column in field list for certain inputs?

[英]Can someone tell my why am i getting this error in mysql workbench while forward engineering?

[英]Client Connections wont load Unhandled exception:DbMySQLQuery

[英]Why am I unable to execute my code in mysql

[英]No options for Data Export and Advanced Options gives unhandled exception

[英]I have a mysql database on my laptop. How could I connect to it when I am not using the Local computer?

[英]When creating a foreign key I am getting the error "Syntax error: missing 'closing parenthesis'

[英]Trying to synchronize my table in mysql Model with my database and I am getting this error

[英]Mysql server: i got connected to localhost, and after that when i click server startup/shutdown i am getting error message

[英]mysqlWorkbench Error : Unhandled exception: new-line character seen in unquoted field

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

  • mysql-workbench
  • foreign-keys
  • syntax-error
  • mysql-error-1064

Securing Applications and Services Guide

1.1. basic steps to secure applications and services, 1.2.1. openid connect, 1.2.2. saml, 1.3. terminology, 2.1.1. endpoints, 2.2.1. authorization code, 2.2.2. implicit, 2.2.3. resource owner password credentials, 2.2.4. client credentials, 2.2.5. device authorization grant, 2.2.6. client initiated backchannel authentication grant, 2.3. keycloak specific errors, 2.4. keycloak java adapters, 2.5.1. installation, 2.5.2. keycloak server configuration, 2.5.3. using the adapter, 2.5.4. session status iframe, 2.5.5. implicit and hybrid flow, 2.5.6. hybrid apps with cordova, 2.5.7. custom adapters, 2.5.8. modern browsers with tracking protection, 2.5.9. api reference, 2.6.1. installation, 2.6.2. usage, 2.6.3. installing middleware, 2.6.4. configuration for proxies, 2.6.5. protecting resources, 2.6.6. additional urls, 2.6.7. complete example, 2.7. mod_auth_openidc apache httpd module, 2.8.1. fapi client profiles, 2.8.2. open finance brasil financial-grade api security profile, 2.8.3. australia consumer data right (cdr) security profile, 2.8.4. tls considerations, 2.9.1. oauth 2.1 client profiles, 2.10.1. validating access tokens, 2.10.2. redirect uris, 3.1.1. general adapter config, 3.1.2. jboss eap/wildfly adapter, 3.1.3. installing adapters from a galleon feature pack, 3.1.4. registering with an identity provider, 3.1.5. logout, 3.1.6. obtaining assertion attributes, 3.1.7. error handling, 3.1.8. troubleshooting, 3.1.9. multi tenancy, 3.1.10. migration from older versions, 3.2.1. configuring mod_auth_mellon with keycloak, 3.2.2. setting the samesite value for the cookie used by mod_auth_mellon, 3.3. keycloak specific errors, 4.1. docker registry configuration file installation, 4.2. docker registry environment variable override installation, 4.3. docker compose yaml file, 5.1.1. bearer token, 5.1.2. initial access token, 5.1.3. registration access token, 5.2. keycloak representations, 5.3. keycloak adapter configuration, 5.4. openid connect dynamic client registration, 5.5. saml entity descriptors, 5.6. example using curl, 5.7. example using java client registration api, 5.8. client registration policies, 6.1. configuring a new regular user for use with client registration cli, 6.2. configuring a client for use with the client registration cli, 6.3. installing the client registration cli, 6.4.1. logging in, 6.4.2. working with alternative configurations, 6.4.3. initial access and registration access tokens, 6.4.4. creating a client configuration, 6.4.5. retrieving a client configuration, 6.4.6. modifying a client configuration, 6.4.7. deleting a client configuration, 6.4.8. refreshing invalid registration access tokens, 6.5. troubleshooting, 7.1.1. form parameters, 7.1.2. responses from a token exchange request, 7.2.1. granting permission for the exchange, 7.2.2. making the request, 7.3.1. granting permission for the exchange, 7.3.2. making the request, 7.4.1. granting permission for the exchange, 7.4.2. making the request, 7.5.1. granting permission for the exchange, 7.5.2. making the request, 7.6.1. granting permission for the exchange, 7.6.2. making the request, 7.7. expand permission model with service accounts, 7.8. exchange vulnerabilities.

Securing Apps

Getting Started

Server Administration

Server Developer

Authorization Services

Release Notes

Version 25.0.4

1. Planning for securing applications and services

As an OAuth2, OpenID Connect, and SAML compliant server, Keycloak can secure any application and service as long as the technology stack they are using supports any of these protocols. For more details about the security protocols supported by Keycloak, consider looking at Server Administration Guide .

Most of the support for some of these protocols is already available from the programming language, framework, or reverse proxy they are using. Leveraging the support already available from the application ecosystem is a key aspect to make your application fully compliant with security standards and best practices, so that you avoid vendor lock-in.

For some programming languages, Keycloak provides libraries that try to fill the gap for the lack of support of a particular security protocol or to provide a more rich and tightly coupled integration with the server. These libraries are known by Keycloak Client Adapters , and they should be used as a last resort if you cannot rely on what is available from the application ecosystem.

These are the basic steps for securing an application or a service in Keycloak.

Register a client to a realm using one of these options:

The Keycloak Admin Console

The client registration service

Enable OpenID Connect or SAML protocols in your application using one these options:

Leveraging existing OpenID Connect and SAML support from the application ecosystem

Using a Keycloak Adapter

This guide provides the detailed instructions for these steps. You can find more details in the Server Administration Guide about how to register a client to Keycloak through the administration console.

1.2. Getting Started

The Keycloak Quickstarts Repository provides examples about how to secure applications and services using different programming languages and frameworks. By going through their documentation and codebase, you will understand the bare minimum changes required in your application and service in order to secure it with Keycloak.

Also, see the following sections for recommendations for trusted and well-known client-side implementations for both OpenID Connect and SAML protocols.

Wildfly Elytron OIDC

Spring Boot

JavaScript (client-side)

Node.js (server-side), apache http server.

mod_auth_openidc

mod_auth_mellon

These terms are used in this guide:

Clients are entities that interact with Keycloak to authenticate users and obtain tokens. Most often, clients are applications and services acting on behalf of users that provide a single sign-on experience to their users and access other services using the tokens issued by the server. Clients can also be entities only interested in obtaining tokens and acting on their own behalf for accessing other services.

Applications include a wide range of applications that work for specific platforms for each protocol

Client adapters are libraries that make it easy to secure applications and services with Keycloak. They provide a tight integration to the underlying platform and framework.

Creating a client and registering a client are the same action. Creating a Client is the term used to create a client by using the Admin Console. Registering a client is the term used to register a client by using the Keycloak Client Registration Service.

A service account is a type of client that is able to obtain tokens on its own behalf.

2. Using OpenID Connect to secure applications and services

This section describes how you can secure applications and services with OpenID Connect using Keycloak.

2.1. Available Endpoints

As a fully-compliant OpenID Connect Provider implementation, Keycloak exposes a set of endpoints that applications and services can use to authenticate and authorize their users.

This section describes some of the key endpoints that your application and service should use when interacting with Keycloak.

The most important endpoint to understand is the well-known configuration endpoint. It lists endpoints and other configuration options relevant to the OpenID Connect implementation in Keycloak. The endpoint is:

To obtain the full URL, add the base URL for Keycloak and replace {realm-name} with the name of your realm. For example:

http://localhost:8080/realms/master/.well-known/openid-configuration

Some RP libraries retrieve all required endpoints from this endpoint, but for others you might need to list the endpoints individually.

Authorization endpoint

The authorization endpoint performs authentication of the end-user. This authentication is done by redirecting the user agent to this endpoint.

For more details see the Authorization Endpoint section in the OpenID Connect specification.

Token endpoint

The token endpoint is used to obtain tokens. Tokens can either be obtained by exchanging an authorization code or by supplying credentials directly depending on what flow is used. The token endpoint is also used to obtain new access tokens when they expire.

For more details, see the Token Endpoint section in the OpenID Connect specification.

Userinfo endpoint

The userinfo endpoint returns standard claims about the authenticated user; this endpoint is protected by a bearer token.

For more details, see the Userinfo Endpoint section in the OpenID Connect specification.

Logout endpoint

The logout endpoint logs out the authenticated user.

The user agent can be redirected to the endpoint, which causes the active user session to be logged out. The user agent is then redirected back to the application.

The endpoint can also be invoked directly by the application. To invoke this endpoint directly, the refresh token needs to be included as well as the credentials required to authenticate the client.

Certificate endpoint

The certificate endpoint returns the public keys enabled by the realm, encoded as a JSON Web Key (JWK). Depending on the realm settings, one or more keys can be enabled for verifying tokens. For more information, see the Server Administration Guide and the JSON Web Key specification .

Introspection endpoint

The introspection endpoint is used to retrieve the active state of a token. In other words, you can use it to validate an access or refresh token. This endpoint can only be invoked by confidential clients.

For more details on how to invoke on this endpoint, see OAuth 2.0 Token Introspection specification .

Introspection endpoint triggered with application/jwt header

You can invoke an introspection endpoint with the HTTP header Accept: application/jwt instead of Accept: application/json . In case of application/jwt , the response may contain the additional claim jwt with the full JWT access token, which can be useful especially if the token to be introspected was a lightweight access token . This requires that you enable Support JWT claim in Introspection Response on the client advanced settings, which triggers the token introspection.

Dynamic Client Registration endpoint

The dynamic client registration endpoint is used to dynamically register clients.

For more details, see the Client Registration chapter and the OpenID Connect Dynamic Client Registration specification .

Token Revocation endpoint

The token revocation endpoint is used to revoke tokens. Both refresh tokens and access tokens are supported by this endpoint. When revoking a refresh token, the user consent for the corresponding client is also revoked.

For more details on how to invoke on this endpoint, see OAuth 2.0 Token Revocation specification .

Device Authorization endpoint

The device authorization endpoint is used to obtain a device code and a user code. It can be invoked by confidential or public clients.

For more details on how to invoke on this endpoint, see OAuth 2.0 Device Authorization Grant specification .

Backchannel Authentication endpoint

The backchannel authentication endpoint is used to obtain an auth_req_id that identifies the authentication request made by the client. It can only be invoked by confidential clients.

For more details on how to invoke on this endpoint, see OpenID Connect Client Initiated Backchannel Authentication Flow specification .

Also refer to other places of Keycloak documentation like Client Initiated Backchannel Authentication Grant section of this guide and Client Initiated Backchannel Authentication Grant section of Server Administration Guide.

2.2. Supported Grant Types

This section describes the different grant types available to relaying parties.

The Authorization Code flow redirects the user agent to Keycloak. Once the user has successfully authenticated with Keycloak, an Authorization Code is created and the user agent is redirected back to the application. The application then uses the authorization code along with its credentials to obtain an Access Token, Refresh Token and ID Token from Keycloak.

The flow is targeted towards web applications, but is also recommended for native applications, including mobile applications, where it is possible to embed a user agent.

For more details refer to the Authorization Code Flow in the OpenID Connect specification.

The Implicit flow works similarly to the Authorization Code flow, but instead of returning an Authorization Code, the Access Token and ID Token is returned. This approach reduces the need for the extra invocation to exchange the Authorization Code for an Access Token. However, it does not include a Refresh Token. This results in the need to permit Access Tokens with a long expiration; however, that approach is not practical because it is very hard to invalidate these tokens. Alternatively, you can require a new redirect to obtain a new Access Token once the initial Access Token has expired. The Implicit flow is useful if the application only wants to authenticate the user and deals with logout itself.

You can instead use a Hybrid flow where both the Access Token and an Authorization Code are returned.

One thing to note is that both the Implicit flow and Hybrid flow have potential security risks as the Access Token may be leaked through web server logs and browser history. You can somewhat mitigate this problem by using short expiration for Access Tokens.

For more details, see the Implicit Flow in the OpenID Connect specification.

Per current OAuth 2.0 Security Best Current Practice , this flow should not be used. This flow is removed from the future OAuth 2.1 specification .

Resource Owner Password Credentials, referred to as Direct Grant in Keycloak, allows exchanging user credentials for tokens. Per current OAuth 2.0 Security Best Practices , this flow should not be used, preferring alternative methods such as Device Authorization Grant or Authorization code .

The limitations of using this flow include:

User credentials are exposed to the application

Applications need login pages

Application needs to be aware of the authentication scheme

Changes to authentication flow requires changes to application

No support for identity brokering or social login

Flows are not supported (user self-registration, required actions, and so on.)

Security concerns with this flow include:

Involving more than Keycloak in handling of credentials

Increased vulnerable surface area where credential leaks can happen

Creating an ecosystem where users trust another application for entering their credentials and not Keycloak

For a client to be permitted to use the Resource Owner Password Credentials grant, the client has to have the Direct Access Grants Enabled option enabled.

This flow is not included in OpenID Connect, but is a part of the OAuth 2.0 specification. It is removed from the future OAuth 2.1 specification .

For more details, see the Resource Owner Password Credentials Grant chapter in the OAuth 2.0 specification.

Example using CURL

The following example shows how to obtain an access token for a user in the realm master with username user and password password . The example is using the confidential client myclient :

Client Credentials are used when clients (applications and services) want to obtain access on behalf of themselves rather than on behalf of a user. For example, these credentials can be useful for background services that apply changes to the system in general rather than for a specific user.

Keycloak provides support for clients to authenticate either with a secret or with public/private keys.

This flow is not included in OpenID Connect, but is a part of the OAuth 2.0 specification.

For more details, see the Client Credentials Grant chapter in the OAuth 2.0 specification.

Device Authorization Grant is used by clients running on internet-connected devices that have limited input capabilities or lack a suitable browser.

The application requests that Keycloak provide a device code and a user code.

Keycloak creates a device code and a user code.

Keycloak returns a response including the device code and the user code to the application.

The application provides the user with the user code and the verification URI. The user accesses a verification URI to be authenticated by using another browser.

The application repeatedly polls Keycloak until Keycloak completes the user authorization.

If user authentication is complete, the application obtains the device code.

The application uses the device code along with its credentials to obtain an Access Token, Refresh Token and ID Token from Keycloak.

For more details, see the OAuth 2.0 Device Authorization Grant specification .

Client Initiated Backchannel Authentication Grant is used by clients who want to initiate the authentication flow by communicating with the OpenID Provider directly without redirect through the user’s browser like OAuth 2.0’s authorization code grant.

The client requests from Keycloak an auth_req_id that identifies the authentication request made by the client. Keycloak creates the auth_req_id.

After receiving this auth_req_id, this client repeatedly needs to poll Keycloak to obtain an Access Token, Refresh Token, and ID Token from Keycloak in return for the auth_req_id until the user is authenticated.

In case that client uses ping mode, it does not need to repeatedly poll the token endpoint, but it can wait for the notification sent by Keycloak to the specified Client Notification Endpoint. The Client Notification Endpoint can be configured in the Keycloak Admin Console. The details of the contract for Client Notification Endpoint are described in the CIBA specification.

For more details, see OpenID Connect Client Initiated Backchannel Authentication Flow specification .

Also refer to other places of Keycloak documentation such as Backchannel Authentication Endpoint of this guide and Client Initiated Backchannel Authentication Grant section of Server Administration Guide. For the details about FAPI CIBA compliance, see the FAPI section of this guide .

Keycloak server can send errors to the client application in the OIDC authentication response with parameters error=temporarily_unavailable and error_description=authentication_expired . Keycloak sends this error when a user is authenticated and has an SSO session, but the authentication session expired in the current browser tab and hence the Keycloak server cannot automatically do SSO re-authentication of the user and redirect back to client with a successful response. When a client application receives this type of error, it is ideal to retry authentication immediately and send a new OIDC authentication request to the Keycloak server, which should typically always authenticate the user due to the SSO session and redirect back. For more details, see the Server Administration Guide .

.

2.5. Keycloak JavaScript adapter

Keycloak comes with a client-side JavaScript library called keycloak-js that can be used to secure web applications. The adapter also comes with built-in support for Cordova applications.

The adapter is distributed in several ways, but we recommend that you install the keycloak-js package from NPM:

Alternatively, the library can be retrieved directly from the Keycloak server at /js/keycloak.js and is also distributed as a ZIP archive. We are however considering the inclusion of the adapter directly from the Keycloak server as deprecated, and this functionality might be removed in the future.

One important thing to consider about using client-side applications is that the client has to be a public client as there is no secure way to store client credentials in a client-side application. This consideration makes it very important to make sure the redirect URIs you have configured for the client are correct and as specific as possible.

To use the adapter, create a client for your application in the Keycloak Admin Console. Make the client public by toggling Client authentication to Off on the Capability config page.

You also need to configure Valid Redirect URIs and Web Origins . Be as specific as possible as failing to do so may result in a security vulnerability.

The following example shows how to initialize the adapter. Make sure that you replace the options passed to the Keycloak constructor with those of the client you have configured.

To authenticate, you call the login function. Two options exist to make the adapter automatically authenticate. You can pass login-required or check-sso to the init() function.

login-required authenticates the client if the user is logged in to Keycloak or displays the login page if the user is not logged in.

check-sso only authenticates the client if the user is already logged in. If the user is not logged in, the browser is redirected back to the application and remains unauthenticated.

You can configure a silent check-sso option. With this feature enabled, your browser will not perform a full redirect to the Keycloak server and back to your application, but this action will be performed in a hidden iframe. Therefore, your application resources are only loaded and parsed once by the browser, namely when the application is initialized and not again after the redirect back from Keycloak to your application. This approach is particularly useful in case of SPAs (Single Page Applications).

To enable the silent check-sso , you provide a silentCheckSsoRedirectUri attribute in the init method. Make sure this URI is a valid endpoint in the application; it must be configured as a valid redirect for the client in the Keycloak Admin Console:

The page at the silent check-sso redirect uri is loaded in the iframe after successfully checking your authentication state and retrieving the tokens from the Keycloak server. It has no other task than sending the received tokens to the main application and should only look like this:

Remember that this page must be served by your application at the specified location in silentCheckSsoRedirectUri and is not part of the adapter.

functionality is limited in some modern browsers. Please see the .

To enable login-required set onLoad to login-required and pass to the init method:

After the user is authenticated the application can make requests to RESTful services secured by Keycloak by including the bearer token in the Authorization header. For example:

One thing to keep in mind is that the access token by default has a short life expiration so you may need to refresh the access token prior to sending the request. You refresh this token by calling the updateToken() method. This method returns a Promise, which makes it easy to invoke the service only if the token was successfully refreshed and displays an error to the user if it was not refreshed. For example:

By default, the adapter creates a hidden iframe that is used to detect if a Single-Sign Out has occurred. This iframe does not require any network traffic. Instead the status is retrieved by looking at a special status cookie. This feature can be disabled by setting checkLoginIframe: false in the options passed to the init() method.

You should not rely on looking at this cookie directly. Its format can change and it’s also associated with the URL of the Keycloak server, not your application.

Session Status iframe functionality is limited in some modern browsers. Please see .

By default, the adapter uses the Authorization Code flow.

With this flow, the Keycloak server returns an authorization code, not an authentication token, to the application. The JavaScript adapter exchanges the code for an access token and a refresh token after the browser is redirected back to the application.

Keycloak also supports the Implicit flow where an access token is sent immediately after successful authentication with Keycloak. This flow may have better performance than the standard flow because no additional request exists to exchange the code for tokens, but it has implications when the access token expires.

However, sending the access token in the URL fragment can be a security vulnerability. For example the token could be leaked through web server logs and or browser history.

To enable implicit flow, you enable the Implicit Flow Enabled flag for the client in the Keycloak Admin Console. You also pass the parameter flow with the value implicit to init method:

Note that only an access token is provided and no refresh token exists. This situation means that once the access token has expired, the application has to redirect to Keycloak again to obtain a new access token.

Keycloak also supports the Hybrid flow.

This flow requires the client to have both the Standard Flow and Implicit Flow enabled in the Admin Console. The Keycloak server then sends both the code and tokens to your application. The access token can be used immediately while the code can be exchanged for access and refresh tokens. Similar to the implicit flow, the hybrid flow is good for performance because the access token is available immediately. But, the token is still sent in the URL, and the security vulnerability mentioned earlier may still apply.

One advantage in the Hybrid flow is that the refresh token is made available to the application.

For the Hybrid flow, you need to pass the parameter flow with value hybrid to the init method:

Keycloak supports hybrid mobile apps developed with Apache Cordova . The adapter has two modes for this: cordova and cordova-native :

The default is cordova , which the adapter automatically selects if no adapter type has been explicitly configured and window.cordova is present. When logging in, it opens an InApp Browser that lets the user interact with Keycloak and afterwards returns to the app by redirecting to http://localhost . Because of this behavior, you whitelist this URL as a valid redirect-uri in the client configuration section of the Admin Console.

While this mode is easy to set up, it also has some disadvantages:

The InApp-Browser is a browser embedded in the app and is not the phone’s default browser. Therefore it will have different settings and stored credentials will not be available.

The InApp-Browser might also be slower, especially when rendering more complex themes.

There are security concerns to consider, before using this mode, such as that it is possible for the app to gain access to the credentials of the user, as it has full control of the browser rendering the login page, so do not allow its use in apps you do not trust.

The alternative mode is`cordova-native`, which takes a different approach. It opens the login page using the system’s browser. After the user has authenticated, the browser redirects back into the application using a special URL. From there, the Keycloak adapter can finish the login by reading the code or token from the URL.

You can activate the native mode by passing the adapter type cordova-native to the init() method:

This adapter requires two additional plugins:

cordova-plugin-browsertab : allows the app to open webpages in the system’s browser

cordova-plugin-deeplinks : allow the browser to redirect back to your app by special URLs

The technical details for linking to an app differ on each platform and special setup is needed. Please refer to the Android and iOS sections of the deeplinks plugin documentation for further instructions.

Different kinds of links exist for opening apps: * custom schemes, such as myapp://login or android-app://com.example.myapp/https/example.com/login * Universal Links (iOS) ) / Deep Links (Android) . While the former are easier to set up and tend to work more reliably, the latter offer extra security because they are unique and only the owner of a domain can register them. Custom-URLs are deprecated on iOS. For best reliability, we recommend that you use universal links combined with a fallback site that uses a custom-url link.

Furthermore, we recommend the following steps to improve compatibility with the adapter:

Universal Links on iOS seem to work more reliably with response-mode set to query

To prevent Android from opening a new instance of your app on redirect add the following snippet to config.xml :

In some situations, you may need to run the adapter in environments that are not supported by default, such as Capacitor. To use the JavasScript client in these environments, you can pass a custom adapter. For example, a third-party library could provide such an adapter to make it possible to reliably run the adapter:

This specific package does not exist, but it gives a pretty good example of how such an adapter could be passed into the client.

It’s also possible to make your own adapter, to do so you will have to implement the methods described in the KeycloakAdapter interface. For example the following TypeScript code ensures that all the methods are properly implemented:

Naturally you can also do this without TypeScript by omitting the type information, but ensuring implementing the interface properly will then be left entirely up to you.

In the latest versions of some browsers, various cookies policies are applied to prevent tracking of the users by third parties, such as SameSite in Chrome or completely blocked third-party cookies. Those policies are likely to become more restrictive and adopted by other browsers over time. Eventually cookies in third-party contexts may become completely unsupported and blocked by the browsers. As a result, the affected adapter features might ultimately be deprecated.

The adapter relies on third-party cookies for Session Status iframe, silent check-sso and partially also for regular (non-silent) check-sso . Those features have limited functionality or are completely disabled based on how restrictive the browser is regarding cookies. The adapter tries to detect this setting and reacts accordingly.

Browsers with "SameSite=Lax by Default" Policy

All features are supported if SSL / TLS connection is configured on the Keycloak side as well as on the application side. For example, Chrome is affected starting with version 84.

Browsers with Blocked Third-Party Cookies

Session Status iframe is not supported and is automatically disabled if such browser behavior is detected by the adapter. This means the adapter cannot use a session cookie for Single Sign-Out detection and must rely purely on tokens. As a result, when a user logs out in another window, the application using the adapter will not be logged out until the application tries to refresh the Access Token. Therefore, consider setting the Access Token Lifespan to a relatively short time, so that the logout is detected as soon as possible. For more details, see Session and Token Timeouts .

Silent check-sso is not supported and falls back to regular (non-silent) check-sso by default. This behavior can be changed by setting silentCheckSsoFallback: false in the options passed to the init method. In this case, check-sso will be completely disabled if restrictive browser behavior is detected.

Regular check-sso is affected as well. Since Session Status iframe is unsupported, an additional redirect to Keycloak has to be made when the adapter is initialized to check the user’s login status. This check is different from the standard behavior when the iframe is used to tell whether the user is logged in, and the redirect is performed only when the user is logged out.

An affected browser is for example Safari starting with version 13.1.

Constructor

Is true if the user is authenticated, false otherwise.

The base64 encoded token that can be sent in the Authorization header in requests to services.

The parsed token as a JavaScript object.

The user id.

The base64 encoded ID token.

The parsed id token as a JavaScript object.

The realm roles associated with the token.

The resource roles associated with the token.

The base64 encoded refresh token that can be used to retrieve a new token.

The parsed refresh token as a JavaScript object.

The estimated time difference between the browser time and the Keycloak server in seconds. This value is just an estimation, but is accurate enough when determining if a token is expired or not.

Response mode passed in init (default value is fragment).

Flow passed in init.

Allows you to override the way that redirects and other browser-related functions will be handled by the library. Available options:

"default" - the library uses the browser api for redirects (this is the default)

"cordova" - the library will try to use the InAppBrowser cordova plugin to load keycloak login/registration pages (this is used automatically when the library is working in a cordova ecosystem)

"cordova-native" - the library tries to open the login and registration page using the phone’s system browser using the BrowserTabs cordova plugin. This requires extra setup for redirecting back to the app (see Hybrid Apps with Cordova ).

"custom" - allows you to implement a custom adapter (only for advanced use cases)

Response type sent to Keycloak with login requests. This is determined based on the flow value used during initialization, but can be overridden by setting this value.

init(options)

Called to initialize the adapter.

Options is an Object, where:

useNonce - Adds a cryptographic nonce to verify that the authentication response matches the request (default is true ).

onLoad - Specifies an action to do on load. Supported values are login-required or check-sso .

silentCheckSsoRedirectUri - Set the redirect uri for silent authentication check if onLoad is set to 'check-sso'.

silentCheckSsoFallback - Enables fall back to regular check-sso when silent check-sso is not supported by the browser (default is true ).

token - Set an initial value for the token.

refreshToken - Set an initial value for the refresh token.

idToken - Set an initial value for the id token (only together with token or refreshToken).

scope - Set the default scope parameter to the Keycloak login endpoint. Use a space-delimited list of scopes. Those typically reference Client scopes defined on a particular client. Note that the scope openid will always be added to the list of scopes by the adapter. For example, if you enter the scope options address phone , then the request to Keycloak will contain the scope parameter scope=openid address phone . Note that the default scope specified here is overwritten if the login() options specify scope explicitly.

timeSkew - Set an initial value for skew between local time and Keycloak server in seconds (only together with token or refreshToken).

checkLoginIframe - Set to enable/disable monitoring login state (default is true ).

checkLoginIframeInterval - Set the interval to check login state (default is 5 seconds).

responseMode - Set the OpenID Connect response mode send to Keycloak server at login request. Valid values are query or fragment . Default value is fragment , which means that after successful authentication will Keycloak redirect to JavaScript application with OpenID Connect parameters added in URL fragment. This is generally safer and recommended over query .

flow - Set the OpenID Connect flow. Valid values are standard , implicit or hybrid .

enableLogging - Enables logging messages from Keycloak to the console (default is false ).

pkceMethod - The method for Proof Key Code Exchange ( PKCE ) to use. Configuring this value enables the PKCE mechanism. Available options:

"S256" - The SHA256 based PKCE method (default)

false - PKCE is disabled.

acrValues - Generates the acr_values parameter which refers to authentication context class reference and allows clients to declare the required assurance level requirements, e.g. authentication mechanisms. See Section 4. acr_values request values and level of assurance in OpenID Connect MODRNA Authentication Profile 1.0 .

messageReceiveTimeout - Set a timeout in milliseconds for waiting for message responses from the Keycloak server. This is used, for example, when waiting for a message during 3rd party cookies check. The default value is 10000.

locale - When onLoad is 'login-required', sets the 'ui_locales' query param in compliance with section 3.1.2.1 of the OIDC 1.0 specification .

Returns a promise that resolves when initialization completes.

login(options)

Redirects to login form.

Options is an optional Object, where:

redirectUri - Specifies the uri to redirect to after login.

prompt - This parameter allows to slightly customize the login flow on the Keycloak server side. For example, enforce displaying the login screen in case of value login . Or enforce displaying of consent screen for the value consent in case that client has Consent Required . Finally it is possible use the value none to make sure that login screen is not displayed to the user, which is useful just to check SSO for the case when user was already authenticated before (This is related to the onLoad check with value check-sso described above).

maxAge - Used just if user is already authenticated. Specifies maximum time since the authentication of user happened. If user is already authenticated for longer time than maxAge , the SSO is ignored and he will need to re-authenticate again.

loginHint - Used to pre-fill the username/email field on the login form.

scope - Override the scope configured in init with a different value for this specific login.

idpHint - Used to tell Keycloak to skip showing the login page and automatically redirect to the specified identity provider instead. More info in the Identity Provider documentation .

acr - Contains the information about acr claim, which will be sent inside claims parameter to the Keycloak server. Typical usage is for step-up authentication. Example of use { values: ["silver", "gold"], essential: true } . See OpenID Connect specification and Step-up authentication documentation for more details.

action - If the value is register , the user is redirected to the registration page. See Registration requested by client section for more details. If the value is UPDATE_PASSWORD or another supported required action, the user will be redirected to the reset password page or the other required action page. However, if the user is not authenticated, the user will be sent to the login page and redirected after authentication. See Application Initiated Action section for more details.

locale - Sets the 'ui_locales' query param in compliance with section 3.1.2.1 of the OIDC 1.0 specification .

cordovaOptions - Specifies the arguments that are passed to the Cordova in-app-browser (if applicable). Options hidden and location are not affected by these arguments. All available options are defined at https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-inappbrowser/ . Example of use: { zoom: "no", hardwareback: "yes" } ;

createLoginUrl(options)

Returns the URL to login form.

Options is an optional Object, which supports same options as the function login .

logout(options)

Redirects to logout.

redirectUri - Specifies the uri to redirect to after logout.

createLogoutUrl(options)

Returns the URL to log out the user.

register(options)

Redirects to registration form. Shortcut for login with option action = 'register'

Options are same as for the login method but 'action' is set to 'register'

createRegisterUrl(options)

Returns the url to registration page. Shortcut for createLoginUrl with option action = 'register'

Options are same as for the createLoginUrl method but 'action' is set to 'register'

accountManagement()

Redirects to the Account Console.

createAccountUrl(options)

Returns the URL to the Account Console.

redirectUri - Specifies the uri to redirect to when redirecting back to the application.

hasRealmRole(role)

Returns true if the token has the given realm role.

hasResourceRole(role, resource)

Returns true if the token has the given role for the resource (resource is optional, if not specified clientId is used).

loadUserProfile()

Loads the users profile.

Returns a promise that resolves with the profile.

For example:

isTokenExpired(minValidity)

Returns true if the token has less than minValidity seconds left before it expires (minValidity is optional, if not specified 0 is used).

updateToken(minValidity)

If the token expires within minValidity seconds (minValidity is optional, if not specified 5 is used) the token is refreshed. If -1 is passed as the minValidity, the token will be forcibly refreshed. If the session status iframe is enabled, the session status is also checked.

Returns a promise that resolves with a boolean indicating whether or not the token has been refreshed.

clearToken()

Clear authentication state, including tokens. This can be useful if application has detected the session was expired, for example if updating token fails.

Invoking this results in onAuthLogout callback listener being invoked.

Callback Events

The adapter supports setting callback listeners for certain events. Keep in mind that these have to be set before the call to the init() method.

The available events are:

onReady(authenticated) - Called when the adapter is initialized.

onAuthSuccess - Called when a user is successfully authenticated.

onAuthError - Called if there was an error during authentication.

onAuthRefreshSuccess - Called when the token is refreshed.

onAuthRefreshError - Called if there was an error while trying to refresh the token.

onAuthLogout - Called if the user is logged out (will only be called if the session status iframe is enabled, or in Cordova mode).

onTokenExpired - Called when the access token is expired. If a refresh token is available the token can be refreshed with updateToken, or in cases where it is not (that is, with implicit flow) you can redirect to the login screen to obtain a new access token.

2.6. Keycloak Node.js adapter

Keycloak provides a Node.js adapter built on top of Connect to protect server-side JavaScript apps - the goal was to be flexible enough to integrate with frameworks like Express.js .

The library can be downloaded directly from Keycloak organization and the source is available at GitHub .

To use the Node.js adapter, first you must create a client for your application in the Keycloak Admin Console. The adapter supports public, confidential, and bearer-only access type. Which one to choose depends on the use-case scenario.

Once the client is created, click Action at the top right and choose Download adapter config . For Format, choose *Keycloak OIDC JSON and click Download . The downloaded keycloak.json file is at the root folder of your project.

Assuming you have already installed Node.js , create a folder for your application:

Use npm init command to create a package.json for your application. Now add the Keycloak connect adapter in the dependencies list:

The Keycloak class provides a central point for configuration and integration with your application. The simplest creation involves no arguments.

In the root directory of your project create a file called server.js and add the following code:

Install the express-session dependency:

To start the server.js script, add the following command in the 'scripts' section of the package.json :

Now we have the ability to run our server with following command:

By default, this will locate a file named keycloak.json alongside the main executable of your application, in our case on the root folder, to initialize Keycloak specific settings such as public key, realm name, various URLs.

In that case a Keycloak deployment is necessary to access Keycloak admin console.

Please visit links on how to deploy a Keycloak admin console with Podman or Docker

Now we are ready to obtain the keycloak.json file by visiting the Keycloak Admin Console → clients (left sidebar) → choose your client → Installation → Format Option → Keycloak OIDC JSON → Download

Paste the downloaded file on the root folder of our project.

Instantiation with this method results in all the reasonable defaults being used. As alternative, it’s also possible to provide a configuration object, rather than the keycloak.json file:

Applications can also redirect users to their preferred identity provider by using:

If you want to use web sessions to manage server-side state for authentication, you need to initialize the Keycloak(…​) with at least a store parameter, passing in the actual session store that express-session is using.

By default, the scope value openid is passed as a query parameter to Keycloak’s login URL, but you can add an additional custom value:

Once instantiated, install the middleware into your connect-capable app:

In order to do so, first we have to install Express:

then require Express in our project as outlined below:

and configure Keycloak middleware in Express, by adding at the code below:

Last but not least, let’s set up our server to listen for HTTP requests on port 3000 by adding the following code to main.js :

If the application is running behind a proxy that terminates an SSL connection Express must be configured per the express behind proxies guide. Using an incorrect proxy configuration can result in invalid redirect URIs being generated.

Example configuration:

To enforce that a user must be authenticated before accessing a resource, simply use a no-argument version of keycloak.protect() :

To secure a resource with an application role for the current app:

To secure a resource with an application role for a different app:

To secure a resource with a realm role:

Resource-Based Authorization allows you to protect resources, and their specific methods/actions, * * based on a set of policies defined in Keycloak, thus externalizing authorization from your application. This is achieved by exposing a keycloak.enforcer method which you can use to protect resources.*

The keycloak-enforcer method operates in two modes, depending on the value of the response_mode configuration option.

If response_mode is set to token , permissions are obtained from the server on behalf of the subject represented by the bearer token that was sent to your application. In this case, a new access token is issued by Keycloak with the permissions granted by the server. If the server did not respond with a token with the expected permissions, the request is denied. When using this mode, you should be able to obtain the token from the request as follows:

Prefer this mode when your application is using sessions and you want to cache previous decisions from the server, as well automatically handle refresh tokens. This mode is especially useful for applications acting as a client and resource server.

If response_mode is set to permissions (default mode), the server only returns the list of granted permissions, without issuing a new access token. In addition to not issuing a new token, this method exposes the permissions granted by the server through the request as follows:

Regardless of the response_mode in use, the keycloak.enforcer method will first try to check the permissions within the bearer token that was sent to your application. If the bearer token already carries the expected permissions, there is no need to interact with the server to obtain a decision. This is specially useful when your clients are capable of obtaining access tokens from the server with the expected permissions before accessing a protected resource, so they can use some capabilities provided by Keycloak Authorization Services such as incremental authorization and avoid additional requests to the server when keycloak.enforcer is enforcing access to the resource.

By default, the policy enforcer will use the client_id defined to the application (for instance, via keycloak.json ) to reference a client in Keycloak that supports Keycloak Authorization Services. In this case, the client can not be public given that it is actually a resource server.

If your application is acting as both a public client(frontend) and resource server(backend), you can use the following configuration to reference a different client in Keycloak with the policies that you want to enforce:

It is recommended to use distinct clients in Keycloak to represent your frontend and backend.

If the application you are protecting is enabled with Keycloak authorization services and you have defined client credentials in keycloak.json , you can push additional claims to the server and make them available to your policies in order to make decisions. For that, you can define a claims configuration option which expects a function that returns a JSON with the claims you want to push:

For more details about how to configure Keycloak to protected your application resources, please take a look at the Authorization Services Guide .

To secure resources based on parts of the URL itself, assuming a role exists for each section:

Advanced Login Configuration:

By default, all unauthorized requests will be redirected to the Keycloak login page unless your client is bearer-only. However, a confidential or public client may host both browsable and API endpoints. To prevent redirects on unauthenticated API requests and instead return an HTTP 401, you can override the redirectToLogin function.

For example, this override checks if the URL contains /api/ and disables login redirects:

By default, the middleware catches calls to /logout to send the user through a Keycloak-centric logout workflow. This can be changed by specifying a logout configuration parameter to the middleware() call:

When the user-triggered logout is invoked a query parameter redirect_url can be passed:

This parameter is then used as the redirect url of the OIDC logout endpoint and the user will be redirected to https://example.com/logged/out .

Also, the middleware supports callbacks from the Keycloak console to log out a single session or all sessions. By default, these type of admin callbacks occur relative to the root URL of / but can be changed by providing an admin parameter to the middleware() call:

A complete example using the Node.js adapter usage can be found in Keycloak quickstarts for Node.js

Keycloak does not provide any official support to mod_auth_openidc. The instructions below are best-effort and may not be up-to-date. We recommend that you stick to official mod_auth_openidc documentation for more details.

The mod_auth_openidc is an Apache HTTP plugin for OpenID Connect. If your language/environment supports using Apache HTTPD as a proxy, then you can use mod_auth_openidc to secure your web application with OpenID Connect. Configuration of this module is beyond the scope of this document. Please see the mod_auth_openidc GitHub repo for more details on configuration.

To configure mod_auth_openidc you’ll need

The client_id.

The client_secret.

The redirect_uri to your application.

The Keycloak openid-configuration url

mod_auth_openidc specific Apache HTTPD module config.

An example configuration would look like the following.

Further information on how to configure mod_auth_openidc can be found on the mod_auth_openidc project page.

2.8. Financial-grade API (FAPI) Support

Keycloak makes it easier for administrators to make sure that their clients are compliant with these specifications:

Financial-grade API Security Profile 1.0 - Part 1: Baseline

Financial-grade API Security Profile 1.0 - Part 2: Advanced

Financial-grade API: Client Initiated Backchannel Authentication Profile (FAPI CIBA)

FAPI 2.0 Security Profile (Draft)

FAPI 2.0 Message Signing (Draft)

This compliance means that the Keycloak server will verify the requirements for the authorization server, which are mentioned in the specifications. Keycloak adapters do not have any specific support for the FAPI, hence the required validations on the client (application) side may need to be still done manually or through some other third-party solutions.

To make sure that your clients are FAPI compliant, you can configure Client Policies in your realm as described in the Server Administration Guide and link them to the global client profiles for FAPI support, which are automatically available in each realm. You can use either fapi-1-baseline or fapi-1-advanced profile based on which FAPI profile you need your clients to conform with. You can use also profiles fapi-2-security-profile or fapi-2-message-signing for the compliance with FAPI 2 Draft specifications.

In case you want to use Pushed Authorization Request (PAR) , it is recommended that your client use both the fapi-1-baseline profile and fapi-1-advanced for PAR requests. Specifically, the fapi-1-baseline profile contains pkce-enforcer executor, which makes sure that client use PKCE with secured S256 algorithm. This is not required for FAPI Advanced clients unless they use PAR requests.

In case you want to use CIBA in a FAPI compliant way, make sure that your clients use both fapi-1-advanced and fapi-ciba client profiles. There is a need to use the fapi-1-advanced profile, or other client profile containing the requested executors, as the fapi-ciba profile contains just CIBA-specific executors. When enforcing the requirements of the FAPI CIBA specification, there is a need for more requirements, such as enforcement of confidential clients or certificate-bound access tokens.

Keycloak is compliant with the Open Finance Brasil Financial-grade API Security Profile 1.0 Implementers Draft 3 . This one is stricter in some requirements than the FAPI 1 Advanced specification and hence it may be needed to configure Client Policies in the more strict way to enforce some of the requirements. Especially:

If your client does not use PAR, make sure that it uses encrypted OIDC request objects. This can be achieved by using a client profile with the secure-request-object executor configured with Encryption Required enabled.

Make sure that for JWS, the client uses the PS256 algorithm. For JWE, the client should use the RSA-OAEP with A256GCM . This may need to be set in all the Client Settings where these algorithms are applicable.

Keycloak is compliant with the Australia Consumer Data Right Security Profile .

If you want to apply the Australia CDR security profile, you need to use fapi-1-advanced profile because the Australia CDR security profile is based on FAPI 1.0 Advanced security profile. If your client also applies PAR, make sure that client applies RFC 7637 Proof Key for Code Exchange (PKCE) because the Australia CDR security profile requires that you apply PKCE when applying PAR. This can be achieved by using a client profile with the pkce-enforcer executor.

As confidential information is being exchanged, all interactions shall be encrypted with TLS (HTTPS). Moreover, there are some requirements in the FAPI specification for the cipher suites and TLS protocol versions used. To match these requirements, you can consider configure allowed ciphers. This configuration can be done by setting the https-protocols and https-cipher-suites options. Keycloak uses TLSv1.3 by default and hence it is possibly not needed to change the default settings. However it may be needed to adjust ciphers if you need to fall back to lower TLS version for some reason. For more details, see Configuring TLS guide.

2.9. OAuth 2.1 Support

The OAuth 2.1 Authorization Framework - draft specification

This compliance means that the Keycloak server will verify the requirements for the authorization server, which are mentioned in the specifications. Keycloak adapters do not have any specific support for the OAuth 2.1, hence the required validations on the client (application) side may need to be still done manually or through some other third-party solutions.

To make sure that your clients are OAuth 2.1 compliant, you can configure Client Policies in your realm as described in the Server Administration Guide and link them to the global client profiles for OAuth 2.1 support, which are automatically available in each realm. You can use either oauth-2-1-for-confidential-client profile for confidential clients or oauth-2-1-for-public-client profile for public clients.

OAuth 2.1 specification is still a draft and it may change in the future. Hence the Keycloak built-in OAuth 2.1 client profiles can change as well.
When using OAuth 2.1 profile for public clients, it is recommended to use DPoP preview feature as described in the because DPoP binds an access token and a refresh token together with the public part of a client’s key pair. This binding prevents an attacker from using stolen tokens.

2.10. Recommendations

This section describes some recommendations when securing your applications with Keycloak.

If you need to manually validate access tokens issued by Keycloak, you can invoke the Introspection Endpoint . The downside to this approach is that you have to make a network invocation to the Keycloak server. This can be slow and possibly overload the server if you have too many validation requests going on at the same time. Keycloak issued access tokens are JSON Web Tokens (JWT) digitally signed and encoded using JSON Web Signature (JWS) . Because they are encoded in this way, you can locally validate access tokens using the public key of the issuing realm. You can either hard code the realm’s public key in your validation code, or lookup and cache the public key using the certificate endpoint with the Key ID (KID) embedded within the JWS. Depending on what language you code in, many third party libraries exist and they can help you with JWS validation.

When using the redirect based flows, be sure to use valid redirect uris for your clients. The redirect uris should be as specific as possible. This especially applies to client-side (public clients) applications. Failing to do so could result in:

Open redirects - this can allow attackers to create spoof links that looks like they are coming from your domain

Unauthorized entry - when users are already authenticated with Keycloak, an attacker can use a public client where redirect uris have not be configured correctly to gain access by redirecting the user without the users knowledge

In production for web applications always use https for all redirect URIs. Do not allow redirects to http.

A few special redirect URIs also exist:

This redirect URI is useful for native applications and allows the native application to create a web server on a random port that can be used to obtain the authorization code. This redirect uri allows any port. Note that per OAuth 2.0 for Native Apps , the use of localhost is not recommended and the IP literal 127.0.0.1 should be used instead.

If you cannot start a web server in the client (or a browser is not available), you can use the special urn:ietf:wg:oauth:2.0:oob redirect uri. When this redirect uri is used, Keycloak displays a page with the code in the title and in a box on the page. The application can either detect that the browser title has changed, or the user can copy and paste the code manually to the application. With this redirect uri, a user can use a different device to obtain a code to paste back to the application.

3. Using SAML to secure applications and services

This section describes how you can secure applications and services with SAML using either Keycloak client adapters or generic SAML provider libraries.

3.1. Keycloak Java adapters

Keycloak comes with a range of different adapters for Java application. Selecting the correct adapter depends on the target platform.

Each SAML client adapter supported by Keycloak can be configured by a simple XML text file. This is what one might look like:

Some of these configuration switches may be adapter specific and some are common across all adapters. For Java adapters you can use ${…​} enclosure as System property replacement. For example ${jboss.server.config.dir} .

Here is the explanation of the SP element attributes:

This is the identifier for this client. The IdP needs this value to determine who the client is that is communicating with it. This setting is REQUIRED .

This is the SSL policy the adapter will enforce. Valid values are: ALL , EXTERNAL , and NONE . For ALL , all requests must come in via HTTPS. For EXTERNAL , only non-private IP addresses must come over the wire via HTTPS. For NONE , no requests are required to come over via HTTPS. This setting is OPTIONAL . Default value is EXTERNAL .

SAML clients can request a specific NameID Subject format. Fill in this value if you want a specific format. It must be a standard SAML format identifier: urn:oasis:names:tc:SAML:2.0:nameid-format:transient . This setting is OPTIONAL . By default, no special format is requested.

SAML clients can request that a user is re-authenticated even if they are already logged in at the IdP. Set this to true to enable. This setting is OPTIONAL . Default value is false .

SAML clients can request that a user is never asked to authenticate even if they are not logged in at the IdP. Set this to true if you want this. Do not use together with forceAuthentication as they are opposite. This setting is OPTIONAL . Default value is false .

The session ID is changed by default on a successful login on some platforms to plug a security attack vector. Change this to true to disable this. It is recommended you do not turn it off. Default value is false .

This should be set to true if your application serves both a web application and web services (for example SOAP or REST). It allows you to redirect unauthenticated users of the web application to the Keycloak login page, but send an HTTP 401 status code to unauthenticated SOAP or REST clients instead as they would not understand a redirect to the login page. Keycloak auto-detects SOAP or REST clients based on typical headers like X-Requested-With , SOAPAction or Accept . The default value is false .

This sets the page to display after logout. If the page is a full URL, such as http://web.example.com/logout.html , the user is redirected after logout to that page using the HTTP 302 status code. If a link without scheme part is specified, such as /logout.jsp , the page is displayed after logout, regardless of whether it lies in a protected area according to security-constraint declarations in web.xml , and the page is resolved relative to the deployment context root.

This attribute should be set to true to make the adapter store the DOM representation of the assertion in its original form inside the SamlPrincipal associated to the request. The assertion document can be retrieved using the method getAssertionDocument inside the principal. This is specially useful when re-playing a signed assertion. The returned document is the one that was generated parsing the SAML response received by the Keycloak server. This setting is OPTIONAL and its default value is false (the document is not saved inside the principal).

Service Provider keys and key elements

If the IdP requires that the client application (or SP) sign all of its requests and/or if the IdP will encrypt assertions, you must define the keys used to do this. For client-signed documents you must define both the private and public key or certificate that is used to sign documents. For encryption, you only have to define the private key that is used to decrypt it.

There are two ways to describe your keys. They can be stored within a Java KeyStore or you can copy/paste the keys directly within keycloak-saml.xml in the PEM format.

The Key element has two optional attributes signing and encryption . When set to true these tell the adapter what the key will be used for. If both attributes are set to true, then the key will be used for both signing documents and decrypting encrypted assertions. You must set at least one of these attributes to true.

KeyStore element

Within the Key element you can load your keys and certificates from a Java Keystore. This is declared within a KeyStore element.

Here are the XML config attributes that are defined with the KeyStore element.

File path to the key store. This option is OPTIONAL . The file or resource attribute must be set.

WAR resource path to the KeyStore. This is a path used in method call to ServletContext.getResourceAsStream(). This option is OPTIONAL . The file or resource attribute must be set.

The password of the KeyStore. This option is REQUIRED .

If you are defining keys that the SP will use to sign document, you must also specify references to your private keys and certificates within the Java KeyStore. The PrivateKey and Certificate elements in the above example define an alias that points to the key or cert within the keystore. Keystores require an additional password to access private keys. In the PrivateKey element you must define this password within a password attribute.

Within the Key element you declare your keys and certificates directly using the sub elements PrivateKeyPem , PublicKeyPem , and CertificatePem . The values contained in these elements must conform to the PEM key format. You usually use this option if you are generating keys using openssl or similar command line tool.

SP PrincipalNameMapping element

This element is optional. When creating a Java Principal object that you obtain from methods such as HttpServletRequest.getUserPrincipal() , you can define what name is returned by the Principal.getName() method.

The policy attribute defines the policy used to populate this value. The possible values for this attribute are:

This policy just uses whatever the SAML subject value is. This is the default setting

This will pull the value from one of the attributes declared in the SAML assertion received from the server. You’ll need to specify the name of the SAML assertion attribute to use within the attribute XML attribute.

RoleIdentifiers element

The RoleIdentifiers element defines what SAML attributes within the assertion received from the user should be used as role identifiers within the Jakarta EE Security Context for the user.

By default Role attribute values are converted to Jakarta EE roles. Some IdPs send roles using a member or memberOf attribute assertion. You can define one or more Attribute elements to specify which SAML attributes must be converted into roles.

RoleMappingsProvider element

The RoleMappingsProvider is an optional element that allows for the specification of the id and configuration of the org.keycloak.adapters.saml.RoleMappingsProvider SPI implementation that is to be used by the SAML adapter.

When Keycloak is used as the IDP, it is possible to use the built-in role mappers to map any roles before adding them to the SAML assertion. However, the SAML adapters can be used to send SAML requests to third party IDPs and in this case it might be necessary to map the roles extracted from the assertion into a different set of roles as required by the SP. The RoleMappingsProvider SPI allows for the configuration of pluggable role mappers that can be used to perform the necessary mappings.

The configuration of the provider looks as follows:

The id attribute identifies which of the installed providers is to be used. The Property sub-element can be used multiple times to specify configuration properties for the provider.

Properties Based role mappings provider

Keycloak includes a RoleMappingsProvider implementation that performs the role mappings using a properties file. This provider is identified by the id properties-based-role-mapper and is implemented by the org.keycloak.adapters.saml.PropertiesBasedRoleMapper class.

This provider relies on two configuration properties that can be used to specify the location of the properties file that will be used. First, it checks if the properties.file.location property has been specified, using the configured value to locate the properties file in the filesystem. If the configured file is not located, the provider throws a RuntimeException . The following snippet shows an example of provider using the properties.file.configuration option to load the roles.properties file from the /opt/mappers/ directory in the filesystem:

If the properties.file.location configuration has not been set, the provider checks the properties.resource.location property, using the configured value to load the properties file from the WAR resource. If this configuration property is also not present, the provider attempts to load the file from /WEB-INF/role-mappings.properties by default. Failure to load the file from the resource will result in the provider throwing a RuntimeException . The following snippet shows an example of provider using the properties.resource.location to load the roles.properties file from the application’s /WEB-INF/conf/ directory:

The properties file can contain both roles and principals as keys, and a list of zero or more roles separated by comma as values. When invoked, the implementation iterates through the set of roles that were extracted from the assertion and checks, for each role, if a mapping exists. If the role maps to an empty role, it is discarded. If it maps to a set of one or more different roles, then these roles are set in the result set. If no mapping is found for the role then it is included as is in the result set.

Once the roles have been processed, the implementation checks if the principal extracted from the assertion contains an entry properties file. If a mapping for the principal exists, any roles listed as value are added to the result set. This allows the assignment of extra roles to a principal.

As an example, let’s assume the provider has been configured with the following properties file:

If the principal kc_user is extracted from the assertion with roles roleA , roleB and roleC , the final set of roles assigned to the principal will be roleC , roleX , roleY and roleZ because roleA is being mapped into both roleX and roleY , roleB was mapped into an empty role - thus being discarded, roleC is used as is and finally an additional role was added to the kc_user principal ( roleZ ).

Note: to use spaces in role names for mappings, use unicode replacements for space. For example, incoming 'role A' would appear as:

Adding your own role mappings provider

To add a custom role mappings provider one simply needs to implement the org.keycloak.adapters.saml.RoleMappingsProvider SPI. For more details see the SAML Role Mappings SPI section in Server Developer Guide .

IDP Element

Everything in the IDP element describes the settings for the identity provider (authentication server) the SP is communicating with.

Here are the attribute config options you can specify within the IDP element declaration.

This is the issuer ID of the IDP. This setting is REQUIRED .

If set to true , the client adapter will sign every document it sends to the IDP. Also, the client will expect that the IDP will be signing any documents sent to it. This switch sets the default for all request and response types, but you will see later that you have some fine grain control over this. This setting is OPTIONAL and will default to false .

This is the signature algorithm that the IDP expects signed documents to use. Allowed values are: RSA_SHA1 , RSA_SHA256 , RSA_SHA512 , and DSA_SHA1 . This setting is OPTIONAL and defaults to RSA_SHA256 . Note that SHA1 based algorithms are deprecated and can be removed in the future. We recommend the use of some more secure algorithm instead of *_SHA1 . Also, with *_SHA1 algorithms, verifying signatures do not work if the SAML server (usually Keycloak) runs on Java 17 or higher.

This is the signature canonicalization method that the IDP expects signed documents to use. This setting is OPTIONAL . The default value is http://www.w3.org/2001/10/xml-exc-c14n# and should be good for most IDPs.

The URL used to retrieve the IDP metadata, currently this is only used to pick up signing and encryption keys periodically which allow cycling of these keys on the IDP without manual changes on the SP side.

IDP AllowedClockSkew sub element

The AllowedClockSkew optional sub element defines the allowed clock skew between IDP and SP. The default value is 0.

It is possible to define the time unit attached to the value for this element. Allowed values are MICROSECONDS, MILLISECONDS, MINUTES, NANOSECONDS and SECONDS. This is OPTIONAL . The default value is SECONDS .

IDP SingleSignOnService sub element

The SingleSignOnService sub element defines the login SAML endpoint of the IDP. The client adapter will send requests to the IDP formatted via the settings within this element when it wants to log in.

Here are the config attributes you can define on this element:

Should the client sign authn requests? This setting is OPTIONAL . Defaults to whatever the IDP signaturesRequired element value is.

Should the client expect the IDP to sign the assertion response document sent back from an authn request? This setting OPTIONAL . Defaults to whatever the IDP signaturesRequired element value is.

This is the SAML binding type used for communicating with the IDP. This setting is OPTIONAL . The default value is POST , but you can set it to REDIRECT as well.

SAML allows the client to request what binding type it wants authn responses to use. The values of this can be POST or REDIRECT . This setting is OPTIONAL . The default is that the client will not request a specific binding type for responses.

URL of the assertion consumer service (ACS) where the IDP login service should send responses to. This setting is OPTIONAL . By default it is unset, relying on the configuration in the IdP. When set, it must end in /saml , for example http://sp.domain.com/my/endpoint/for/saml . The value of this property is sent in AssertionConsumerServiceURL attribute of SAML AuthnRequest message. This property is typically accompanied by the responseBinding attribute.

This is the URL for the IDP login service that the client will send requests to. This setting is REQUIRED .

IDP SingleLogoutService sub element

The SingleLogoutService sub element defines the logout SAML endpoint of the IDP. The client adapter will send requests to the IDP formatted via the settings within this element when it wants to log out.

Should the client sign logout requests it makes to the IDP? This setting is OPTIONAL . Defaults to whatever the IDP signaturesRequired element value is.

Should the client sign logout responses it sends to the IDP requests? This setting is OPTIONAL . Defaults to whatever the IDP signaturesRequired element value is.

Should the client expect signed logout request documents from the IDP? This setting is OPTIONAL . Defaults to whatever the IDP signaturesRequired element value is.

Should the client expect signed logout response documents from the IDP? This setting is OPTIONAL . Defaults to whatever the IDP signaturesRequired element value is.

This is the SAML binding type used for communicating SAML requests to the IDP. This setting is OPTIONAL . The default value is POST , but you can set it to REDIRECT as well.

This is the SAML binding type used for communicating SAML responses to the IDP. The values of this can be POST or REDIRECT . This setting is OPTIONAL . The default value is POST , but you can set it to REDIRECT as well.

This is the URL for the IDP’s logout service when using the POST binding. This setting is REQUIRED if using the POST binding.

This is the URL for the IDP’s logout service when using the REDIRECT binding. This setting is REQUIRED if using the REDIRECT binding.

IDP Keys sub element

The Keys sub element of IDP is only used to define the certificate or public key to use to verify documents signed by the IDP. It is defined in the same way as the SP’s Keys element . But again, you only have to define one certificate or public key reference. Note that, if both IDP and SP are realized by Keycloak server and adapter, respectively, there is no need to specify the keys for signature validation, see below.

It is possible to configure SP to obtain public keys for IDP signature validation from published certificates automatically, provided both SP and IDP are implemented by Keycloak. This is done by removing all declarations of signature validation keys in Keys sub element. If the Keys sub element would then remain empty, it can be omitted completely. The keys are then automatically obtained by SP from SAML descriptor, location of which is derived from SAML endpoint URL specified in the IDP SingleSignOnService sub element . Settings of the HTTP client that is used for SAML descriptor retrieval usually needs no additional configuration, however it can be configured in the IDP HttpClient sub element .

It is also possible to specify multiple keys for signature verification. This is done by declaring multiple Key elements within Keys sub element that have signing attribute set to true . This is useful for example in situation when the IDP signing keys are rotated: There is usually a transition period when new SAML protocol messages and assertions are signed with the new key but those signed by previous key should still be accepted.

It is not possible to configure Keycloak to both obtain the keys for signature verification automatically and define additional static signature verification keys.

IDP HttpClient sub element

The HttpClient optional sub element defines the properties of HTTP client used for automatic obtaining of certificates containing public keys for IDP signature verification via SAML descriptor of the IDP when enabled .

This config option defines how many connections to the Keycloak server should be pooled. This is OPTIONAL . The default value is 10 .

If the Keycloak server requires HTTPS and this config option is set to true you do not have to specify a truststore. This setting should only be used during development and never in production as it will disable verification of SSL certificates. This is OPTIONAL . The default value is false .

If the Keycloak server requires HTTPS and this config option is set to true the Keycloak server’s certificate is validated via the truststore, but host name validation is not done. This setting should only be used during development and never in production as it will partly disable verification of SSL certificates. This setting may be useful in test environments. This is OPTIONAL . The default value is false .

The value is the file path to a truststore file. If you prefix the path with classpath: , then the truststore will be obtained from the deployment’s classpath instead. Used for outgoing HTTPS communications to the Keycloak server. Client making HTTPS requests need a way to verify the host of the server they are talking to. This is what the truststore does. The keystore contains one or more trusted host certificates or certificate authorities. You can create this truststore by extracting the public certificate of the Keycloak server’s SSL keystore. This is REQUIRED unless disableTrustManager is true .

Password for the truststore. This is REQUIRED if truststore is set and the truststore requires a password.

This is the file path to a keystore file. This keystore contains client certificate for two-way SSL when the adapter makes HTTPS requests to the Keycloak server. This is OPTIONAL .

Password for the client keystore and for the client’s key. This is REQUIRED if clientKeystore is set.

URL to HTTP proxy to use for HTTP connections. This is OPTIONAL .

Timeout for socket waiting for data after establishing the connection in milliseconds. Maximum time of inactivity between two data packets. A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default if applicable). The default value is -1 . This is OPTIONAL .

Timeout for establishing the connection with the remote host in milliseconds. A timeout value of zero is interpreted as an infinite timeout. A negative value is interpreted as undefined (system default if applicable). The default value is -1 . This is OPTIONAL .

Connection time-to-live for client in milliseconds. A value less than or equal to zero is interpreted as an infinite value. The default value is -1 . This is OPTIONAL .

To be able to secure WAR apps deployed on JBoss EAP or WildFly, you must install and configure the Keycloak SAML Adapter Subsystem.

You then provide a keycloak config, /WEB-INF/keycloak-saml.xml file in your WAR and change the auth-method to KEYCLOAK-SAML within web.xml.

For the WildFly 29 or newer, the SAML adapter is provided as a Galleon feature pack. More details about this is in the WildFly documentation . The same option will be provided for JBoss EAP 8 GA.

Keycloak provided adapter ZIP download in the past, but it is not provided anymore. For the older WildFly versions, it is recommended to upgrade to newer WildFly/EAP and use Galleon. Otherwise, you will need to stick with the older Keycloak adapters, but those are not maintained and officially supported. For JBoss EAP 7, it is possible to stick with the Red Hat Single Sign-On 7.6 adapters, which is still supported.

For more details on how to integrate Keycloak with JakartaEE applications running on latest Wildfly/EAP, take a look at the Jakarta EE quickstart in the Keycloak Quickstart GitHub Repository .

Below are the details on how to configure the SAML adapter secured by Galleon.

Setting SameSite value for JSESSIONID cookie

Browsers are planning to set the default value for the SameSite attribute for cookies to Lax . This setting means that cookies will be sent to applications only if the request originates in the same domain. This behavior can affect the SAML POST binding which may become non-functional. To preserve full functionality of the SAML adapter, we recommend setting the SameSite value to None for the JSESSIONID cookie created by your container. Not doing so may result in resetting the container’s session with each request to Keycloak.

To avoid setting the attribute to , consider switching to the REDIRECT binding if it is acceptable, or to OIDC protocol where this workaround is not necessary.

To set the SameSite value to None for the JSESSIONID cookie in Wildfly/EAP, add a file undertow-handlers.conf with the following content to the WEB-INF directory of your application.

The support for this configuration is available in Wildfly from version 19.1.0.

Securing a WAR

This section describes how to secure a WAR directly by adding config and editing files within your WAR package.

The first thing you must do is create a keycloak-saml.xml adapter config file within the WEB-INF directory of your WAR. The format of this config file is described in the General Adapter Config section.

Next you must set the auth-method to KEYCLOAK-SAML in web.xml . You also have to use standard servlet security to specify role-base constraints on your URLs. Here’s an example web.xml file:

All standard servlet settings except the auth-method setting.

Securing WARs using the Keycloak SAML Subsystem

You do not have to open a WAR to secure it with Keycloak. Alternatively, you can externally secure it via the Keycloak SAML Adapter Subsystem. While you don’t have to specify KEYCLOAK-SAML as an auth-method , you still have to define the security-constraints in web.xml . You do not, however, have to create a WEB-INF/keycloak-saml.xml file. This metadata is instead defined within the XML in your server’s domain.xml or standalone.xml subsystem configuration section.

The secure-deployment name attribute identifies the WAR you want to secure. Its value is the module-name defined in web.xml with .war appended. The rest of the configuration uses the same XML syntax as keycloak-saml.xml configuration defined in General Adapter Config .

An example configuration:

For each servlet-based adapter, the endpoint you register for the assert consumer service URL and single logout service must be the base URL of your servlet application with /saml appended to it, that is, https://example.com/contextPath/saml .

There are multiple ways you can log out from a web application. For Jakarta EE servlet containers, you can call HttpServletRequest.logout() . For any other browser application, you can point the browser at any url of your web application that has a security constraint and pass in a query parameter GLO, i.e. http://myapp?GLO=true . This will log you out if you have an SSO session with your browser.

Logout in clustered environment

Internally, the SAML adapter stores a mapping between the SAML session index, principal name (when known), and HTTP session ID. This mapping can be maintained in JBoss application server family (WildFly 10/11, EAP 6/7) across cluster for distributable applications. As a precondition, the HTTP sessions need to be distributed across cluster (i.e. application is marked with <distributable/> tag in application’s web.xml ).

To enable the functionality, add the following section to your /WEB_INF/web.xml file:

For EAP 7, WildFly 10/11:

If the session cache of the deployment is named deployment-cache , the cache used for SAML mapping will be named as deployment-cache .ssoCache . The name of the cache can be overridden by a context parameter keycloak.sessionIdMapperUpdater.infinispan.cacheName . The cache container containing the cache will be the same as the one containing the deployment session cache, but can be overridden by a context parameter keycloak.sessionIdMapperUpdater.infinispan.containerName .

By default, the configuration of the SAML mapping cache will be derived from session cache. The configuration can be manually overridden in cache configuration section of the server just the same as other caches.

Currently, to provide reliable service, it is recommended to use replicated cache for the SAML session cache. Using distributed cache may lead to results where the SAML logout request would land to a node with no access to SAML session index to HTTP session mapping which would lead to unsuccessful logout.

Logout in cross-site scenario

The cross-site scenario only applies to WildFly 10 and higher, and EAP 7 and higher.

Special handling is needed for handling sessions that span multiple data centers. Imagine the following scenario:

Login requests are handled within cluster in data center 1.

Admin issues logout request for a particular SAML session, the request lands in data center 2.

The data center 2 has to log out all sessions that are present in data center 1 (and all other data centers that share HTTP sessions).

To cover this case, the SAML session cache described above needs to be replicated not only within individual clusters but across all the data centers for example via standalone Infinispan/JDG server :

A cache has to be added to the standalone Infinispan/JDG server.

The cache from previous item has to be added as a remote store for the respective SAML session cache.

Once remote store is found to be present on SAML session cache during deployment, it is watched for changes and the local SAML session cache is updated accordingly.

After a successful SAML login, your application code may want to obtain attribute values passed with the SAML assertion. HttpServletRequest.getUserPrincipal() returns a Principal object that you can typecast into a Keycloak specific class called org.keycloak.adapters.saml.SamlPrincipal . This object allows you to look at the raw assertion and also has convenience functions to look up attribute values.

Keycloak has some error handling facilities for servlet based client adapters. When an error is encountered in authentication, the client adapter will call HttpServletResponse.sendError() . You can set up an error-page within your web.xml file to handle the error however you want. The client adapter can throw 400, 401, 403, and 500 errors.

The client adapter also sets an HttpServletRequest attribute that you can retrieve. The attribute name is org.keycloak.adapters.spi.AuthenticationError . Typecast this object to: org.keycloak.adapters.saml.SamlAuthenticationError . This class can tell you exactly what happened. If this attribute is not set, then the adapter was not responsible for the error code.

The best way to troubleshoot problems is to turn on debugging for SAML in both the client adapter and Keycloak Server. Using your logging framework, set the log level to DEBUG for the org.keycloak.saml package. Turning this on allows you to see the SAML requests and response documents being sent to and from the server.

SAML offers Multi Tenancy, meaning that a single target application (WAR) can be secured with multiple Keycloak realms. The realms can be located on the same Keycloak instance or on different instances.

To do this, the application must have multiple keycloak-saml.xml adapter configuration files.

While you could have multiple instances of your WAR with different adapter configuration files deployed to different context-paths, this may be inconvenient and you may also want to select the realm based on something other than context-path.

Keycloak makes it possible to have a custom config resolver, so you can choose which adapter config is used for each request. In SAML, the configuration is only interesting in the login processing; once the user is logged in, the session is authenticated and it does not matter if the keycloak-saml.xml returned is different. For that reason, returning the same configuration for the same session is the correct way to go.

To achieve this, create an implementation of org.keycloak.adapters.saml.SamlConfigResolver . The following example uses the Host header to locate the proper configuration and load it and the associated elements from the applications' Java classpath:

You must also configure which SamlConfigResolver implementation to use with the keycloak.config.resolver context-param in your web.xml :

Migrating to 1.9.0

Saml sp client adapter changes.

Keycloak SAML SP Client Adapter now requires a specific endpoint, /saml to be registered with your IdP. The SamlFilter must also be bound to /saml in addition to any other binding it has. This had to be done because SAML POST binding would eat the request input stream and this would be really bad for clients that relied on it.

3.2. mod_auth_mellon Apache HTTPD Module

Keycloak does not provide any official support to mod_auth_mellon. The instructions below are best-effort and may not be up-to-date. We recommend that you stick to official mod_auth_mellon documentation for more details.

The mod_auth_mellon module is an Apache HTTPD plugin for SAML. If your language/environment supports using Apache HTTPD as a proxy, then you can use mod_auth_mellon to secure your web application with SAML. For more details on this module see the mod_auth_mellon GitHub repo.

To configure mod_auth_mellon you need:

An Identity Provider (IdP) entity descriptor XML file, which describes the connection to Keycloak or another SAML IdP

An SP entity descriptor XML file, which describes the SAML connections and configuration for the application you are securing.

A private key PEM file, which is a text file in the PEM format that defines the private key the application uses to sign documents.

A certificate PEM file, which is a text file that defines the certificate for your application.

mod_auth_mellon-specific Apache HTTPD module configuration.

If you have already defined and registered the client application within a realm on the Keycloak application server, Keycloak can generate all the files you need except the Apache HTTPD module configuration.

Perform the following procedure to generate the Apache HTTPD module configuration.

Go to the Installation page of your SAML client.

Select the Mod Auth Mellon files option.

mod auth mellon config download

Click Download to download a ZIP file that contains the XML descriptor and PEM files you need.

There are two hosts involved:

The host on which Keycloak is running, which will be referred to as $idp_host because Keycloak is a SAML identity provider (IdP).

The host on which the web application is running, which will be referred to as $sp_host. In SAML an application using an IdP is called a service provider (SP).

All of the following steps need to performed on $sp_host with root privileges.

Installing the packages

To install the necessary packages, you will need:

Apache Web Server (httpd)

Mellon SAML SP add-on module for Apache

Tools to create X509 certificates

To install the necessary packages, run this command:

Creating a configuration directory for Apache SAML

It is advisable to keep configuration files related to Apache’s use of SAML in one location.

Create a new directory named saml2 located under the Apache configuration root /etc/httpd:

Configuring the Mellon Service Provider

Configuration files for Apache add-on modules are located in the /etc/httpd/conf.d directory and have a file name extension of .conf. You need to create the /etc/httpd/conf.d/mellon.conf file and place Mellon’s configuration directives in it.

Mellon’s configuration directives can roughly be broken down into two classes of information:

Which URLs to protect with SAML authentication

What SAML parameters will be used when a protected URL is referenced.

Apache configuration directives typically follow a hierarchical tree structure in the URL space, which are known as locations. You need to specify one or more URL locations for Mellon to protect. You have flexibility in how you add the configuration parameters that apply to each location. You can either add all the necessary parameters to the location block or you can add Mellon parameters to a common location high up in the URL location hierarchy that specific protected locations inherit (or some combination of the two). Since it is common for an SP to operate in the same way no matter which location triggers SAML actions, the example configuration used here places common Mellon configuration directives in the root of the hierarchy and then specific locations to be protected by Mellon can be defined with minimal directives. This strategy avoids duplicating the same parameters for each protected location.

This example has just one protected location: https://$sp_host/private.

To configure the Mellon service provider, perform the following procedure.

Create the file /etc/httpd/conf.d/mellon.conf with this content:

Some of the files referenced in the code above are created in later steps.

Browsers are planning to set the default value for the SameSite attribute for cookies to Lax . This setting means that cookies will be sent to applications only if the request originates in the same domain. This behavior can affect the SAML POST binding which may become non-functional. To preserve full functionality of the mod_auth_mellon module, we recommend setting the SameSite value to None for the cookie created by mod_auth_mellon . Not doing so may result in an inability to login using Keycloak.

To set the SameSite value to None , add the following configuration to <Location / > tag within your mellon.conf file.

The support for this configuration is available in the mod_auth_mellon module from version 0.16.0.

Creating the Service Provider metadata

In SAML IdPs and SPs exchange SAML metadata, which is in XML format. The schema for the metadata is a standard, thus assuring participating SAML entities can consume each other’s metadata. You need:

Metadata for the IdP that the SP utilizes

Metadata describing the SP provided to the IdP

One of the components of SAML metadata is X509 certificates. These certificates are used for two purposes:

Sign SAML messages so the receiving end can prove the message originated from the expected party.

Encrypt the message during transport (seldom used because SAML messages typically occur on TLS-protected transports)

You can use your own certificates if you already have a Certificate Authority (CA) or you can generate a self-signed certificate. For simplicity in this example a self-signed certificate is used.

Because Mellon’s SP metadata must reflect the capabilities of the installed version of mod_auth_mellon, must be valid SP metadata XML, and must contain an X509 certificate (whose creation can be obtuse unless you are familiar with X509 certificate generation) the most expedient way to produce the SP metadata is to use a tool included in the mod_auth_mellon package (mellon_create_metadata.sh). The generated metadata can always be edited later because it is a text file. The tool also creates your X509 key and certificate.

SAML IdPs and SPs identify themselves using a unique name known as an EntityID. To use the Mellon metadata creation tool you need:

The EntityID, which is typically the URL of the SP, and often the URL of the SP where the SP metadata can be retrieved

The URL where SAML messages for the SP will be consumed, which Mellon calls the MellonEndPointPath.

To create the SP metadata, perform the following procedure.

Create a few helper shell variables:

Invoke the Mellon metadata creation tool by running this command:

Move the generated files to their destination (referenced in the /etc/httpd/conf.d/mellon.conf file created above):

Adding the Mellon Service Provider to the Keycloak Identity Provider

Assumption: The Keycloak IdP has already been installed on the $idp_host.

Keycloak supports multiple tenancy where all users, clients, and so on are grouped in what is called a realm. Each realm is independent of other realms. You can use an existing realm in your Keycloak, but this example shows how to create a new realm called test_realm and use that realm.

All these operations are performed using the Keycloak Admin Console. You must have the admin username and password for $idp_host to perform the following procedure.

Open the Admin Console and log on by entering the admin username and password.

After logging into the Admin Console, there will be an existing realm. When Keycloak is first set up a root realm, master, is created by default. Any previously created realms are listed in the upper left corner of the Admin Console in a drop-down list.

From the realm drop-down list select Add realm .

In the Name field type test_realm and click Create .

Adding the Mellon Service Provider as a client of the realm

In Keycloak SAML SPs are known as clients. To add the SP we must be in the Clients section of the realm.

Click the Clients menu item on the left and click Create in the upper right corner to create a new client.

Adding the Mellon SP client

To add the Mellon SP client, perform the following procedure.

Set the client protocol to SAML.

From the Client Protocol drop down list, select saml .

Provide the Mellon SP metadata file created above (/etc/httpd/saml2/mellon_metadata.xml).

Depending on where your browser is running you might have to copy the SP metadata from $sp_host to the machine on which your browser is running so the browser can find the file.

Click Save .

Editing the Mellon SP client

Use this procedure to set important client configuration parameters.

Ensure "Force POST Binding" is On.

Add paosResponse to the Valid Redirect URIs list:

Copy the postResponse URL in "Valid Redirect URIs" and paste it into the empty add text fields just below the "+".

Change "postResponse" to "paosResponse". (The paosResponse URL is needed for SAML ECP.)

Click Save at the bottom.

Many SAML SPs determine authorization based on a user’s membership in a group. The Keycloak IdP can manage user group information but it does not supply the user’s groups unless the IdP is configured to supply it as a SAML attribute.

Perform the following procedure to configure the IdP to supply the user’s groups as a SAML attribute.

Click the Mappers tab of the client.

In the upper right corner of the Mappers page, click Create .

From the Mapper Type drop-down list select Group list .

Set Name to "group list".

Set the SAML attribute name to "groups".

The remaining steps are performed on $sp_host.

Retrieving the Identity Provider metadata

Now that you have created the realm on the IdP you need to retrieve the IdP metadata associated with it so the Mellon SP recognizes it. In the /etc/httpd/conf.d/mellon.conf file created previously, the MellonIdPMetadataFile is specified as /etc/httpd/saml2/idp_metadata.xml but until now that file has not existed on $sp_host.

Use this procedure to retrieve that file from the IdP.

Use this command, substituting with the correct value for $idp_host:

Mellon is now fully configured.

To run a syntax check for Apache configuration files, use this command:

Configtest is equivalent to the -t argument to apachectl. If the configuration test shows any errors, correct them before proceeding.

Restart the Apache server:

You have now set up both Keycloak as a SAML IdP in the test_realm and mod_auth_mellon as SAML SP protecting the URL $sp_host/protected (and everything beneath it) by authenticating against the $idp_host IdP.

Keycloak server can send an error to the client application in the SAML response, which may contain a SAML status such as:

Keycloak sends this error when a user is authenticated and has an SSO session, but the authentication session expired in the current browser tab and hence Keycloak server cannot automatically do SSO re-authentication of the user and redirect back to client with successful response. When a client application receives this type of error, it is ideal to retry authentication immediately and send a new SAML request to the Keycloak server, which should typically always authenticate the user due to the SSO session and redirect back. More details in the Server Administration Guide .

4. Configuring a Docker registry to use Keycloak

Docker authentication is disabled by default. To enable see the guide.

This section describes how you can configure a Docker registry to use Keycloak as its authentication server.

For more information on how to set up and configure a Docker registry, see the Docker Registry Configuration Guide .

For users with more advanced Docker registry configurations, it is generally recommended to provide your own registry configuration file. The Keycloak Docker provider supports this mechanism via the Registry Config File Format Option. Choosing this option will generate output similar to the following:

This output can then be copied into any existing registry config file. See the registry config file specification for more information on how the file should be set up, or start with a basic example .

Don’t forget to configure the field with the location of the Keycloak realm’s public key. The auth configuration will not work without this argument.

Often times it is appropriate to use a simple environment variable override for develop or POC Docker registries. While this approach is usually not recommended for production use, it can be helpful when one requires quick-and-dirty way to stand up a registry. Simply use the Variable Override Format Option from the client details, and an output should appear like the one below:

Don’t forget to configure the override with the location of the Keycloak realm’s public key. The auth configuration will not work without this argument.
This installation method is meant to be an easy way to get a docker registry authenticating against a Keycloak server. It is intended for development purposes only and should never be used in a production or production-like environment.

The zip file installation mechanism provides a quickstart for developers who want to understand how the Keycloak server can interact with the Docker registry. In order to configure:

From the desired realm, create a client configuration. At this point you will not have a Docker registry - the quickstart will take care of that part.

Choose the "Docker Compose YAML" option from the from Action menu and select the Download adapter config option to download the ZIP file.

Unzip the archive to the desired location, and open the directory.

Start the Docker registry with docker-compose up

it is recommended that you configure the Docker registry client in a realm other than 'master', since the HTTP Basic auth flow will not present forms.

Once the above configuration has taken place, and the keycloak server and Docker registry are running, docker authentication should be successful:

5. Using the client registration service

In order for an application or service to utilize Keycloak it has to register a client in Keycloak. An admin can do this through the admin console (or admin REST endpoints), but clients can also register themselves through the Keycloak client registration service.

The Client Registration Service provides built-in support for Keycloak Client Representations, OpenID Connect Client Meta Data and SAML Entity Descriptors. The Client Registration Service endpoint is /realms/<realm>/clients-registrations/<provider> .

The built-in supported providers are:

default - Keycloak Client Representation (JSON)

install - Keycloak Adapter Configuration (JSON)

openid-connect - OpenID Connect Client Metadata Description (JSON)

saml2-entity-descriptor - SAML Entity Descriptor (XML)

The following sections will describe how to use the different providers.

5.1. Authentication

To invoke the Client Registration Services you usually need a token. The token can be a bearer token, an initial access token or a registration access token. There is an alternative to register new client without any token as well, but then you need to configure Client Registration Policies (see below).

The bearer token can be issued on behalf of a user or a Service Account. The following permissions are required to invoke the endpoints (see Server Administration Guide for more details):

create-client or manage-client - To create clients

view-client or manage-client - To view clients

manage-client - To update or delete client

If you are using a bearer token to create clients it’s recommend to use a token from a Service Account with only the create-client role (see Server Administration Guide for more details).

The recommended approach to registering new clients is by using initial access tokens. An initial access token can only be used to create clients and has a configurable expiration as well as a configurable limit on how many clients can be created.

An initial access token can be created through the admin console. To create a new initial access token first select the realm in the admin console, then click on Client in the menu on the left, followed by Initial access token in the tabs displayed in the page.

You will now be able to see any existing initial access tokens. If you have access you can delete tokens that are no longer required. You can only retrieve the value of the token when you are creating it. To create a new token click on Create . You can now optionally add how long the token should be valid, also how many clients can be created using the token. After you click on Save the token value is displayed.

It is important that you copy/paste this token now as you won’t be able to retrieve it later. If you forget to copy/paste it, then delete the token and create another one.

The token value is used as a standard bearer token when invoking the Client Registration Services, by adding it to the Authorization header in the request. For example:

When you create a client through the Client Registration Service the response will include a registration access token. The registration access token provides access to retrieve the client configuration later, but also to update or delete the client. The registration access token is included with the request in the same way as a bearer token or initial access token.

By default, registration access token rotation is enabled. This means a registration access token is only valid once. When the token is used, the response will include a new token. Note that registration access token rotation can be disabled by using Client Policies .

If a client was created outside of the Client Registration Service it won’t have a registration access token associated with it. You can create one through the admin console. This can also be useful if you lose the token for a particular client. To create a new token find the client in the admin console and click on Credentials . Then click on Generate registration access token .

The default client registration provider can be used to create, retrieve, update and delete a client. It uses Keycloak Client Representation format which provides support for configuring clients exactly as they can be configured through the admin console, including for example configuring protocol mappers.

To create a client create a Client Representation (JSON) then perform an HTTP POST request to /realms/<realm>/clients-registrations/default .

It will return a Client Representation that also includes the registration access token. You should save the registration access token somewhere if you want to retrieve the config, update or delete the client later.

To retrieve the Client Representation perform an HTTP GET request to /realms/<realm>/clients-registrations/default/<client id> .

It will also return a new registration access token.

To update the Client Representation perform an HTTP PUT request with the updated Client Representation to: /realms/<realm>/clients-registrations/default/<client id> .

To delete the Client Representation perform an HTTP DELETE request to: /realms/<realm>/clients-registrations/default/<client id>

The installation client registration provider can be used to retrieve the adapter configuration for a client. In addition to token authentication you can also authenticate with client credentials using HTTP basic authentication. To do this include the following header in the request:

To retrieve the Adapter Configuration then perform an HTTP GET request to /realms/<realm>/clients-registrations/install/<client id> .

No authentication is required for public clients. This means that for the JavaScript adapter you can load the client configuration directly from Keycloak using the above URL.

Keycloak implements OpenID Connect Dynamic Client Registration , which extends OAuth 2.0 Dynamic Client Registration Protocol and OAuth 2.0 Dynamic Client Registration Management Protocol .

The endpoint to use these specifications to register clients in Keycloak is /realms/<realm>/clients-registrations/openid-connect[/<client id>] .

This endpoint can also be found in the OpenID Connect Discovery endpoint for the realm, /realms/<realm>/.well-known/openid-configuration .

The SAML Entity Descriptor endpoint only supports using SAML v2 Entity Descriptors to create clients. It doesn’t support retrieving, updating or deleting clients. For those operations the Keycloak representation endpoints should be used. When creating a client a Keycloak Client Representation is returned with details about the created client, including a registration access token.

To create a client perform an HTTP POST request with the SAML Entity Descriptor to /realms/<realm>/clients-registrations/saml2-entity-descriptor .

The following example creates a client with the clientId myclient using CURL. You need to replace eyJhbGciOiJSUz…​ with a proper initial access token or bearer token.

The Client Registration Java API makes it easy to use the Client Registration Service using Java. To use include the dependency org.keycloak:keycloak-client-registration-api:>VERSION< from Maven.

For full instructions on using the Client Registration refer to the JavaDocs. Below is an example of creating a client. You need to replace eyJhbGciOiJSUz…​ with a proper initial access token or bearer token.

The current plans are for the Client Registration Policies to be removed in favor of the Client Policies described in the . Client Policies are more flexible and support more use cases.

Keycloak currently supports two ways how new clients can be registered through Client Registration Service.

Authenticated requests - Request to register new client must contain either Initial Access Token or Bearer Token as mentioned above.

Anonymous requests - Request to register new client doesn’t need to contain any token at all

Anonymous client registration requests are very interesting and powerful feature, however you usually don’t want that anyone is able to register new client without any limitations. Hence we have Client Registration Policy SPI , which provide a way to limit who can register new clients and under which conditions.

In Keycloak admin console, you can click to Client Registration tab and then Client Registration Policies sub-tab. Here you will see what policies are configured by default for anonymous requests and what policies are configured for authenticated requests.

The anonymous requests (requests without any token) are allowed just for creating (registration) of new clients. So when you register new client through anonymous request, the response will contain Registration Access Token, which must be used for Read, Update or Delete request of particular client. However using this Registration Access Token from anonymous registration will be then subject to Anonymous Policy too! This means that for example request for update client also needs to come from Trusted Host if you have policy. Also for example it won’t be allowed to disable when updating client and when policy is present etc.

Currently we have these policy implementations:

Trusted Hosts Policy - You can configure list of trusted hosts and trusted domains. Request to Client Registration Service can be sent just from those hosts or domains. Request sent from some untrusted IP will be rejected. URLs of newly registered client must also use just those trusted hosts or domains. For example it won’t be allowed to set Redirect URI of client pointing to some untrusted host. By default, there is not any whitelisted host, so anonymous client registration is de-facto disabled.

Consent Required Policy - Newly registered clients will have Consent Allowed switch enabled. So after successful authentication, user will always see consent screen when he needs to approve permissions (client scopes). It means that client won’t have access to any personal info or permission of user unless user approves it.

Protocol Mappers Policy - Allows to configure list of whitelisted protocol mapper implementations. New client can’t be registered or updated if it contains some non-whitelisted protocol mapper. Note that this policy is used for authenticated requests as well, so even for authenticated request there are some limitations which protocol mappers can be used.

Client Scope Policy - Allow to whitelist Client Scopes , which can be used with newly registered or updated clients. There are no whitelisted scopes by default; only the client scopes, which are defined as Realm Default Client Scopes are whitelisted by default.

Full Scope Policy - Newly registered clients will have Full Scope Allowed switch disabled. This means they won’t have any scoped realm roles or client roles of other clients.

Max Clients Policy - Rejects registration if current number of clients in the realm is same or bigger than specified limit. It’s 200 by default for anonymous registrations.

Client Disabled Policy - Newly registered client will be disabled. This means that admin needs to manually approve and enable all newly registered clients. This policy is not used by default even for anonymous registration.

6. Automating Client Registration with the CLI

The Client Registration CLI is a command-line interface (CLI) tool for application developers to configure new clients in a self-service manner when integrating with Keycloak. It is specifically designed to interact with Keycloak Client Registration REST endpoints.

It is necessary to create or obtain a client configuration for any application to be able to use Keycloak. You usually configure a new client for each new application hosted on a unique host name. When an application interacts with Keycloak, the application identifies itself with a client ID so Keycloak can provide a login page, single sign-on (SSO) session management, and other services.

You can configure application clients from a command line with the Client Registration CLI, and you can use it in shell scripts.

To allow a particular user to use Client Registration CLI , the Keycloak administrator typically uses the Admin Console to configure a new user with proper roles or to configure a new client and client secret to grant access to the Client Registration REST API.

Log in to the Admin Console (for example, http://localhost:8080/admin ) as admin .

Select a realm to administer.

If you want to use an existing user, select that user to edit; otherwise, create a new user.

Select Role Mapping , Assign role . From the option list, click Filter by clients . In the search bar, type manage-clients . Select the role, or if you are in the master realm, select the one with NAME-realm , where NAME is the name of the target realm. You can grant access to any other realm to users in the master realm.

Click Assign to grant a full set of client management permissions. Another option is to choose view-clients for read-only or create-client to create new clients.

Select Available Roles , manage-client to grant a full set of client management permissions. Another option is to choose view-clients for read-only or create-client to create new clients.

or .

It is possible to not assign any realm-management roles to a user. In that case, a user can still log in with the Client Registration CLI but cannot use it without an Initial Access Token. Trying to perform any operations without a token results in a 403 Forbidden error.

The administrator can issue Initial Access Tokens from the Admin Console in the Clients area on the Initial Access Token tab.

By default, the server recognizes the Client Registration CLI as the admin-cli client, which is configured automatically for every new realm. No additional client configuration is necessary when logging in with a user name.

Create a client (for example, reg-cli ) if you want to use a separate client configuration for the Client Registration CLI.

Uncheck Standard Flow Enabled .

Strengthen the security by toggling Client authentication to On .

Choose the type of account that you want to use.

If you want to use a service account associated with the client, check Service accounts roles .

If you prefer to use a regular user account, check Direct access grants .

Click Next .

Click the Credentials tab.

Configure either Client Id and Secret or Signed JWT .

If you are using service account roles, click the Service Account Roles tab.

Select the roles to configure the access for the service account. For the details on what roles to select, see Configuring a new regular user for use with Client Registration CLI .

When you run the kcreg config credentials , use the --secret option to supply the configured secret.

Specify which clientId to use (for example, --client reg-cli ) when running kcreg config credentials .

With the service account enabled, you can omit specifying the user when running kcreg config credentials and only provide the client secret or keystore information.

The Client Registration CLI is packaged inside the Keycloak Server distribution. You can find execution scripts inside the bin directory. The Linux script is called kcreg.sh , and the Windows script is called kcreg.bat .

Add the Keycloak server directory to your PATH when setting up the client for use from any location on the file system.

For example, on:

KEYCLOAK_HOME refers to a directory where the Keycloak Server distribution was unpacked.

6.4. Using the Client Registration CLI

Start an authenticated session by logging in with your credentials.

Run commands on the Client Registration REST endpoint.

to avoid exposing tokens to network sniffers.

If a server’s certificate is not issued by one of the trusted certificate authorities (CAs) that are included in Java’s default certificate truststore, prepare a truststore.jks file and instruct the Client Registration CLI to use it.

Specify a server endpoint URL and a realm when you log in with the Client Registration CLI.

Specify a user name or a client id, which results in a special service account being used. When using a user name, you must use a password for the specified user. When using a client ID, you use a client secret or a Signed JWT instead of a password.

Regardless of the login method, the account that logs in needs proper permissions to be able to perform client registration operations. Keep in mind that any account in a non-master realm can only have permissions to manage clients within the same realm. If you need to manage different realms, you can either configure multiple users in different realms, or you can create a single user in the master realm and add roles for managing clients in different realms.

You cannot configure users with the Client Registration CLI. Use the Admin Console web interface or the Admin Client CLI to configure users. See Server Administration Guide for more details.

When kcreg successfully logs in, it receives authorization tokens and saves them in a private configuration file so the tokens can be used for subsequent invocations. See Working with alternative configurations for more information on configuration files.

See the built-in help for more information on using the Client Registration CLI.

See kcreg config credentials --help for more information about starting an authenticated session.

By default, the Client Registration CLI automatically maintains a configuration file at a default location, ./.keycloak/kcreg.config , under the user’s home directory. You can use the --config option to point to a different file or location to maintain multiple authenticated sessions in parallel. It is the safest way to perform operations tied to a single configuration file from a single thread.

You might want to avoid storing secrets inside a configuration file by using the --no-config option with all of your commands, even though it is less convenient and requires more token requests to do so. Specify all authentication information with each kcreg invocation.

Developers who do not have an account configured at the Keycloak server they want to use can use the Client Registration CLI. This is possible only when the realm administrator issues a developer an Initial Access Token. It is up to the realm administrator to decide how and when to issue and distribute these tokens. The realm administrator can limit the maximum age of the Initial Access Token and the total number of clients that can be created with it.

Once a developer has an Initial Access Token, the developer can use it to create new clients without authenticating with kcreg config credentials . The Initial Access Token can be stored in the configuration file or specified as part of the kcreg create command.

When using an Initial Access Token, the server response includes a newly issued Registration Access Token. Any subsequent operation for that client needs to be performed by authenticating with that token, which is only valid for that client.

The Client Registration CLI automatically uses its private configuration file to save and use this token with its associated client. As long as the same configuration file is used for all client operations, the developer does not need to authenticate to read, update, or delete a client that was created this way.

See Client Registration for more information about Initial Access and Registration Access Tokens.

Run the kcreg config initial-token --help and kcreg config registration-token --help commands for more information on how to configure tokens with the Client Registration CLI.

The first task after authenticating with credentials or configuring an Initial Access Token is usually to create a new client. Often you might want to use a prepared JSON file as a template and set or override some of the attributes.

The following example shows how to read a JSON file, override any client id it may contain, set any other attributes, and print the configuration to a standard output after successful creation.

Run the kcreg create --help for more information about the kcreg create command.

You can use kcreg attrs to list available attributes. Keep in mind that many configuration attributes are not checked for validity or consistency. It is up to you to specify proper values. Remember that you should not have any id fields in your template and should not specify them as arguments to the kcreg create command.

You can retrieve an existing client by using the kcreg get command.

You can also retrieve the client configuration as an adapter configuration file, which you can package with your web application.

Run the kcreg get --help command for more information about the kcreg get command.

There are two methods for updating a client configuration.

One method is to submit a complete new state to the server after getting the current configuration, saving it to a file, editing it, and posting it back to the server.

The second method fetches the current client, sets or deletes fields on it, and posts it back in one step.

You can also use a file that contains only changes to be applied so you do not have to specify too many values as arguments. In this case, specify --merge to tell the Client Registration CLI that rather than treating the JSON file as a full, new configuration, it should treat it as a set of attributes to be applied over the existing configuration.

Run the kcreg update --help command for more information about the kcreg update command.

Use the following example to delete a client.

Run the kcreg delete --help command for more information about the kcreg delete command.

When performing a create, read, update, and delete (CRUD) operation using the --no-config mode, the Client Registration CLI cannot handle Registration Access Tokens for you. In that case, it is possible to lose track of the most recently issued Registration Access Token for a client, which makes it impossible to perform any further CRUD operations on that client without authenticating with an account that has manage-clients permissions.

If you have permissions, you can issue a new Registration Access Token for the client and have it printed to a standard output or saved to a configuration file of your choice. Otherwise, you have to ask the realm administrator to issue a new Registration Access Token for your client and send it to you. You can then pass it to any CRUD command via the --token option. You can also use the kcreg config registration-token command to save the new token in a configuration file and have the Client Registration CLI automatically handle it for you from that point on.

Run the kcreg update-token --help command for more information about the kcreg update-token command.

Q: When logging in, I get an error: Parameter client_assertion_type is missing [invalid_client] .

A: This error means your client is configured with Signed JWT token credentials, which means you have to use the --keystore parameter when logging in.

7. Using token exchange

and is not fully supported. This feature is disabled by default.

or

flow, also enable the feature. For details, see the guide.

7.1. How token exchange works

In Keycloak, token exchange is the process of using a set of credentials or token to obtain an entirely different token. A client may want to invoke on a less trusted application so it may want to downgrade the current token it has. A client may want to exchange a Keycloak token for a token stored for a linked social provider account. You may want to trust external tokens minted by other Keycloak realms or foreign IDPs. A client may have a need to impersonate a user. Here’s a short summary of the current capabilities of Keycloak around token exchange.

A client can exchange an existing Keycloak token created for a specific client for a new token targeted to a different client

A client can exchange an existing Keycloak token for an external token, i.e. a linked Facebook account

A client can exchange an external token for a Keycloak token.

A client can impersonate a user

Token exchange in Keycloak is a very loose implementation of the OAuth Token Exchange specification at the IETF. We have extended it a little, ignored some of it, and loosely interpreted other parts of the specification. It is a simple grant type invocation on a realm’s OpenID Connect token endpoint.

It accepts form parameters ( application/x-www-form-urlencoded ) as input and the output depends on the type of token you requested an exchange for. Token exchange is a client endpoint so requests must provide authentication information for the calling client. Public clients specify their client identifier as a form parameter. Confidential clients can also use form parameters to pass their client id and secret, Basic Auth, or however your admin has configured the client authentication flow in your realm.

REQUIRED MAYBE. This parameter is required for clients using form parameters for authentication. If you are using Basic Auth, a client JWT token, or client cert authentication, then do not specify this parameter.

REQUIRED MAYBE . This parameter is required for clients using form parameters for authentication and using a client secret as a credential. Do not specify this parameter if client invocations in your realm are authenticated by a different means.

REQUIRED. The value of the parameter must be urn:ietf:params:oauth:grant-type:token-exchange .

OPTIONAL. A security token that represents the identity of the party on behalf of whom the request is being made. It is required if you are exchanging an existing token for a new one.

OPTIONAL. Identifies the issuer of the subject_token . It can be left blank if the token comes from the current realm or if the issuer can be determined from the subject_token_type . Otherwise it is required to be specified. Valid values are the alias of an Identity Provider configured for your realm. Or an issuer claim identifier configured by a specific Identity Provider .

OPTIONAL. This parameter is the type of the token passed with the subject_token parameter. This defaults to urn:ietf:params:oauth:token-type:access_token if the subject_token comes from the realm and is an access token. If it is an external token, this parameter may or may not have to be specified depending on the requirements of the subject_issuer .

OPTIONAL. This parameter represents the type of token the client wants to exchange for. Currently only oauth and OpenID Connect token types are supported. The default value for this depends on whether it is urn:ietf:params:oauth:token-type:refresh_token in which case you will be returned both an access token and refresh token within the response. Other appropriate values are urn:ietf:params:oauth:token-type:access_token and urn:ietf:params:oauth:token-type:id_token

OPTIONAL. This parameter specifies the target client you want the new token minted for.

OPTIONAL. This parameter specifies that the client wants a token minted by an external provider. It must be the alias of an Identity Provider configured within the realm.

OPTIONAL. This specifies a username or user id if your client wants to impersonate a different user.

OPTIONAL. This parameter represents the target set of OAuth and OpenID Connect scopes the client is requesting. Returned scope is the Cartesian product of scope parameter and access token scope.

We currently only support OpenID Connect and OAuth exchanges. Support for SAML based clients and identity providers may be added in the future depending on user demand.

A successful response from an exchange invocation will return the HTTP 200 response code with a content type that depends on the requested-token-type and requested_issuer the client asks for. OAuth requested token types will return a JSON document as described in the OAuth Token Exchange specification.

Clients requesting a refresh token will get back both an access and refresh token in the response. Clients requesting only access token type will only get an access token in the response. Expiration information may or may not be included for clients requesting an external issuer through the requested_issuer parameter.

Error responses generally fall under the 400 HTTP response code category, but other error status codes may be returned depending on the severity of the error. Error responses may include content depending on the requested_issuer . OAuth based exchanges may return a JSON document as follows:

Additional error claims may be returned depending on the exchange type. For example, OAuth Identity Providers may include an additional account-link-url claim if the user does not have a link to an identity provider. This link can be used for a client initiated link request.

Token exchange setup requires knowledge of fine grain admin permissions (See the for more information). You will need to grant clients permission to exchange. This is discussed more later in this chapter.

The rest of this chapter discusses the setup requirements and provides examples for different exchange scenarios. For simplicity’s sake, let’s call a token minted by the current realm as an internal token and a token minted by an external realm or identity provider as an external token.

7.2. Internal token to internal token exchange

With an internal token to token exchange you have an existing token minted to a specific client and you want to exchange this token for a new one minted for a different target client. Why would you want to do this? This generally happens when a client has a token minted for itself, and needs to make additional requests to other applications that require different claims and permissions within the access token. Other reasons this type of exchange might be required is if you need to perform a "permission downgrade" where your app needs to invoke on a less trusted app and you don’t want to propagate your current access token.

Clients that want to exchange tokens for a different client need to be authorized in the Admin Console. You need to define a token-exchange fine grain permission in the target client you want permission to exchange to.

Target Client Permission

Toggle Permissions Enabled to On .

Target Client Exchange Permission Set

That page displays a token-exchange link.

Click that link to start defining the permission.

This setup page displays.

Target Client Exchange Permission Setup

Click Client details in the breadcrumbs at the top of the screen.

Define a policy for this permission.

Click Authorization in the breadcrumbs at the top of the screen.

Click the Policies tab.

Create a Client Policy by clicking Create policy button.

Client Policy Creation

Enter in the starting client that is the authenticated client that is requesting a token exchange.

After you create this policy, go back to the target client’s token-exchange permission and add the client policy you just defined.

Apply Client Policy

Your client now has permission to invoke. If you do not do this correctly, you will get a 403 Forbidden response if you try to make an exchange.

When your client is exchanging an existing token for a token targeting another client, you use the audience parameter. This parameter must be the client identifier for the target client that you configured in the Admin Console.

The subject_token parameter must be an access token for the target realm. If your requested_token_type parameter is a refresh token type, then the response will contain both an access token, refresh token, and expiration. Here’s an example JSON response you get back from this call.

When the audience parameter is not set, the value of the parameter defaults to the client making the token exchange request.

Unlike with confidential clients, public clients are not allowed to perform token exchanges using tokens from other clients. If you are passing a subject_token , the (confidential) client that was issued the token should either match the client making the request or, if issued to a different client, the client making the request should be among the audiences set to the token.

If you are explicitly setting a target audience (with a client different from the client making the request), you should also make sure that the token-exchange scope permission is configured for the client set to the audience parameter to allow the client making the request to successfully complete the exchange.

7.3. Internal token to external token exchange

You can exchange a realm token for an external token minted by an external identity provider. This external identity provider must be configured within the Identity Provider section of the Admin Console. Currently only OAuth/OpenID Connect based external identity providers are supported, this includes all social providers. Keycloak does not perform a backchannel exchange to the external provider. So if the account is not linked, you will not be able to get the external token. To be able to obtain an external token one of these conditions must be met:

The user must have logged in with the external identity provider at least once

The user must have linked with the external identity provider through the User Account Service

The user account was linked through the external identity provider using Client Initiated Account Linking API.

Finally, the external identity provider must have been configured to store tokens, or, one of the above actions must have been performed with the same user session as the internal token you are exchanging.

If the account is not linked, the exchange response will contain a link you can use to establish it. This is discussed more in the Making the Request section.

Internal to external token exchange requests will be denied with a 403, Forbidden response until you grant permission for the calling client to exchange tokens with the external identity provider. To grant permission to the client, you go to the identity provider’s configuration page to the Permissions tab.

Identity Provider Exchange Permission

The page displays token-exchange link.

Click the link to start defining the permission.

This setup page appears.

Identity Provider Exchange Permission Setup

Click Policies tab to create a client policy.

Client Policy Creation

Enter the starting client that is the authenticated client that is requesting a token exchange.

Return to the identity provider’s token-exchange permission and add the client policy you just defined.

Apply Client Policy

When your client is exchanging an existing internal token to an external one, you provide the requested_issuer parameter. The parameter must be the alias of a configured identity provider.

The subject_token parameter must be an access token for the target realm. The requested_token_type parameter must be urn:ietf:params:oauth:token-type:access_token or left blank. No other requested token type is supported at this time. Here’s an example successful JSON response you get back from this call.

If the external identity provider is not linked for whatever reason, you will get an HTTP 400 response code with this JSON document:

The error claim will be either token_expired or not_linked . The account-link-url claim is provided so that the client can perform Client Initiated Account Linking . Most, if not all, providers require linking through browser OAuth protocol. With the account-link-url just add a redirect_uri query parameter to it and you can forward browsers to perform the link.

7.4. External token to internal token exchange

You can trust and exchange external tokens minted by external identity providers for internal tokens. This can be used to bridge between realms or just to trust tokens from your social provider. It works similarly to an identity provider browser login in that a new user is imported into your realm if it doesn’t exist.

The current limitation on external token exchanges is that if the external token maps to an existing user an exchange will not be allowed unless the existing user already has an account link to the external identity provider.

When the exchange is complete, a user session will be created within the realm, and you will receive an access and or refresh token depending on the requested_token_type parameter value. You should note that this new user session will remain active until it times out or until you call the logout endpoint of the realm passing this new access token.

These types of changes required a configured identity provider in the Admin Console.

SAML identity providers are not supported at this time. Twitter tokens cannot be exchanged either.

Before external token exchanges can be done, you grant permission for the calling client to make the exchange. This permission is granted in the same manner as internal to external permission is granted .

If you also provide an audience parameter whose value points to a different client other than the calling one, you must also grant the calling client permission to exchange to the target client specific in the audience parameter. How to do this is discussed earlier in this section.

The subject_token_type must either be urn:ietf:params:oauth:token-type:access_token or urn:ietf:params:oauth:token-type:jwt . If the type is urn:ietf:params:oauth:token-type:access_token you specify the subject_issuer parameter and it must be the alias of the configured identity provider. If the type is urn:ietf:params:oauth:token-type:jwt , the provider will be matched via the iss (issuer) claim within the JWT which must be the alias of the provider, or a registered issuer within the providers configuration.

For validation, if the token is an access token, the provider’s user info service will be invoked to validate the token. A successful call will mean that the access token is valid. If the subject token is a JWT and if the provider has signature validation enabled, that will be attempted, otherwise, it will default to also invoking on the user info service to validate the token.

By default, the internal token minted will use the calling client to determine what’s in the token using the protocol mappers defined for the calling client. Alternatively, you can specify a different target client using the audience parameter.

If your requested_token_type parameter is a refresh token type, then the response will contain both an access token, refresh token, and expiration. Here’s an example JSON response you get back from this call.

7.5. Impersonation

For internal and external token exchanges, the client can request on behalf of a user to impersonate a different user. For example, you may have an admin application that needs to impersonate a user so that a support engineer can debug a problem.

The user that the subject token represents must have permission to impersonate other users. See the Server Administration Guide on how to enable this permission. It can be done through a role or through fine grain admin permissions.

Make the request as described in other chapters except additionally specify the requested_subject parameter. The value of this parameter must be a username or user id.

7.6. Direct Naked Impersonation

You can make an internal token exchange request without providing a subject_token . This is called a direct naked impersonation because it places a lot of trust in a client as that client can impersonate any user in the realm. You might need this to bridge for applications where it is impossible to obtain a subject token to exchange. For example, you may be integrating a legacy application that performs login directly with LDAP. In that case, the legacy app is able to authenticate users itself, but not able to obtain a token.

It is very risky to enable direct naked impersonation for a client. If the client’s credentials are ever stolen, that client can impersonate any user in the system.

If the audience parameter is provided, then the calling client must have permission to exchange to the client. How to set this up is discussed earlier in this chapter.

Additionally, the calling client must be granted permission to impersonate users.

Click Users in the menu.

Click the Permissions tab.

User Permissions

The page displays an impersonate link.

Users Impersonation Permission Setup

Go to the Policies tab and create a client policy.

Client Policy Creation

Return to the users' impersonation permission and add the client policy you just defined.

Apply Client Policy

Your client now has permission to impersonate users. If you do not do this correctly, you will get a 403 Forbidden response if you try to make this type of exchange.

Public clients are not allowed to do direct naked impersonations.

To make the request, simply specify the requested_subject parameter. This must be the username or user id of a valid user. You can also specify an audience parameter if you wish.

When granting clients permission to exchange, you don’t necessarily manually enable those permissions for each and every client. If the client has a service account associated with it, you can use a role to group permissions together and assign exchange permissions by assigning a role to the client’s service account. For example, you might define a naked-exchange role and any service account that has that role can do a naked exchange.

When you start allowing token exchanges, there are various things you have to both be aware of and careful of.

The first is public clients. Public clients do not have or require a client credential in order to perform an exchange. Anybody that has a valid token will be able to impersonate the public client and perform the exchanges that public client is allowed to perform. If there are any untrustworthy clients that are managed by your realm, public clients may open up vulnerabilities in your permission models. This is why direct naked exchanges do not allow public clients and will abort with an error if the calling client is public.

It is possible to exchange social tokens provided by Facebook, Google, etc. for a realm token. Be careful and vigilante on what the exchange token is allowed to do as it’s not hard to create fake accounts on these social websites. Use default roles, groups, and identity provider mappers to control what attributes and roles are assigned to the external social user.

Direct naked exchanges are quite dangerous. You are putting a lot of trust in the calling client that it will never leak out its client credentials. If those credentials are leaked, then the thief can impersonate anybody in your system. This is in direct contrast to confidential clients that have existing tokens. You have two factors of authentication, the access token and the client credentials, and you’re only dealing with one user. So use direct naked exchanges sparingly.

  • Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
  • Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
  • OverflowAI GenAI features for Teams
  • OverflowAPI Train & fine-tune LLMs
  • Labs The future of collective knowledge sharing
  • About the company Visit the blog

Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Get early access and see previews of new features.

Getting error "local variable referenced before assignment - how to fix?

I'm making a gambling program (i know this shouldn't be incredibly hard), and want to have multiple games which will be in subroutines. However, python seems to think my variables are being assigned in strange places.

I am semi-new to subroutines, and still have some issues here and there. Here is what I am working with:

And here is how it is called:

I expect it to just go through, add a tally into win or loss, then update the money. However, I am getting this error: UnboundLocalError: local variable 'losses' referenced before assignment If I win, it says the same thing with local variable 'wins' .

As shown all variables are assigned at the top, then referenced below in subroutines. I am completely unsure on how python thinks I referenced it before assignment?

I would appreciate any help, thank you in advance!

xupaii's user avatar

  • Can you post the whole code? –  Manuel Fedele Commented Mar 23, 2019 at 14:55
  • pastebin.com/WkrPRPfb - check this pastebin for the whole code –  xupaii Commented Mar 23, 2019 at 14:57

2 Answers 2

The reason is that losses is defined as a global variable. Within functions (local scope), you can, loosely speaking, read from global variables but not modify them.

This will work:

This won't:

You should assign to your variables within your function body if you want them to have local scope. If you explicitly want to modify global variables, you need to declare them with, for example, global losses in your function body.

gmds's user avatar

The variables wins , money and losses were declared outside the scope of the fiftyfifty() function, so you cannot update them from inside the function unless you explicitly declare them as global variables like this:

glhr's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged python subroutine or ask your own question .

  • The Overflow Blog
  • Ryan Dahl explains why Deno had to evolve with version 2.0
  • Featured on Meta
  • We've made changes to our Terms of Service & Privacy Policy - July 2024
  • Bringing clarity to status tag usage on meta sites
  • Feedback requested: How do you use tag hover descriptions for curating and do...
  • What does a new user need in a homepage experience on Stack Overflow?

Hot Network Questions

  • Can these statements really be arguments?
  • Why don't we observe protons deflecting in J.J. Thomson's experiment?
  • How old were Phineas and Ferb? What year was it?
  • Population impacts on temperature
  • One IO to control two LEDs. When one is lit, the other is not
  • Fantasy book with king/father who pretends to be insane
  • What might cause these striations in this solder joint?
  • What is the origin of this quote on telling a big lie?
  • How common is it for external contractors to manage internal teams, and how can we navigate this situation?
  • Who said "If you don't do politics, politics will do you"?
  • Is sudoku only one puzzle?
  • How can an Investigator get critical specialization effects on unarmed attacks?
  • How to make two alignments in the environment align?
  • How many people could we get off of the planet in a month?
  • Did anyone ever ask Neil Armstrong whether he said "for man" or "for a man?"
  • The Master Tetrist
  • I can't select a certain record with like %value%
  • Should I be able to see light from a IR Led with my own eyes?
  • LoginForm submission which sends sign in link to email and then sets value in localStorage
  • Why doesn't double jeopardy apply in this case where a woman was convicted of attempted murder, then manslaughter when the victim died years later?
  • How to remove a file named "."?
  • Fitting 10 pieces of pizza in a box
  • Series of discrete groups with a Lie group limit
  • Would it take less thrust overall to put an object into higher orbit?

unhandled exception local variable 'pwd' referenced before assignment

IMAGES

  1. UnboundLocalError: Local Variable Referenced Before Assignment

    unhandled exception local variable 'pwd' referenced before assignment

  2. mysql workbench

    unhandled exception local variable 'pwd' referenced before assignment

  3. Unhandled exception local variable pwd referenced before assignment

    unhandled exception local variable 'pwd' referenced before assignment

  4. "Fixing UnboundLocalError: Local Variable Referenced Before Assignment"

    unhandled exception local variable 'pwd' referenced before assignment

  5. UnboundLocalError: local variable referenced before assignment

    unhandled exception local variable 'pwd' referenced before assignment

  6. [SOLVED] Local Variable Referenced Before Assignment

    unhandled exception local variable 'pwd' referenced before assignment

COMMENTS

  1. Why am I getting "Unhandled exception: local variable 'pwd' referenced

    Unhandled exception: local variable 'pwd' referenced before assignment Check the log for more details. ... 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password if pwd is None: UnboundLocalError: local variable 'pwd' referenced before assignment 14:00:43 [ERR][wb_admin_utils.py:page_activated:329]: Exception activating the page ...

  2. MySQL Workbench: Cannot export a database

    Solution 1 - Provide correct config file to each mysqldump-call. This is more a workaround, but it will get you to the desired result. Just use the provided information to get a dump of your MySQL-Table from the CLI - basically it's just copy & paste: As you can see from the log mysqldump has the parameter --defaults-file.

  3. Bug #101300 local variable referenced before assignment

    File "C:\Program Files\MySQL\MySQL Workbench 8.0 CE\modules\wb_admin_export.py", line 963, in get_mysql_password. if pwd is None: UnboundLocalError: local variable 'pwd' referenced before assignment. How to repeat: PREREQUISITE: You must NOT have privilege to LOCK TABLES n the database in this test. Open workbench.

  4. MySQL Export

    Hi, the bug was that the server didn't execute the correct version of powershell, but thanks for your reply

  5. mysql

    Thanks I was trying to see if the MYSQL_PWD works for regular mysql client, which it doesn't appear to be working. Can you try making a new user with a very simple password no spaces and try setting that like MYSQL_PWD=abc123 mysql -u newuser I'm thinking some kind of quote trimming has changed

  6. Fix "local variable referenced before assignment" in Python

    Reliable monitoring for your app, databases, infrastructure, and the vendors they rely on. Ping Bot is a powerful uptime and performance monitoring tool that helps notify you and resolve issues before they affect your customers.

  7. Local variable referenced before assignment in Python

    If a variable is assigned a value in a function's body, it is a local variable unless explicitly declared as global. # Local variables shadow global ones with the same name. You could reference the global name variable from inside the function but if you assign a value to the variable in the function's body, the local variable shadows the ...

  8. How to fix UnboundLocalError: local variable 'x' referenced before

    The UnboundLocalError: local variable 'x' referenced before assignment occurs when you reference a variable inside a function before declaring that variable. To resolve this error, you need to use a different variable name when referencing the existing variable, or you can also specify a parameter for the function. I hope this tutorial is useful.

  9. How to Fix Local Variable Referenced Before Assignment Error in Python

    value = value + 1 print (value) increment() If you run this code, you'll get. BASH. UnboundLocalError: local variable 'value' referenced before assignment. The issue is that in this line: PYTHON. value = value + 1. We are defining a local variable called value and then trying to use it before it has been assigned a value, instead of using the ...

  10. [SOLVED] Local Variable Referenced Before Assignment

    DJANGO - Local Variable Referenced Before Assignment [Form] The program takes information from a form filled out by a user. Accordingly, an email is sent using the information. ... Therefore, we have examined the local variable referenced before the assignment Exception in Python. The differences between a local and global variable ...

  11. UnboundLocalError: local variable 'pwd' referenced before assignment

    Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

  12. How to Fix

    Output. Hangup (SIGHUP) Traceback (most recent call last): File "Solution.py", line 7, in <module> example_function() File "Solution.py", line 4, in example_function x += 1 # Trying to modify global variable 'x' without declaring it as global UnboundLocalError: local variable 'x' referenced before assignment Solution for Local variable Referenced Before Assignment in Python

  13. unhandled exception: local variable 'tables' referenced before assignment

    I choose more than one schema to export and immediately and dialog box occurs with the message: unhandled exception: local variable 'tables' referenced before assignment. It works fine selecting a single schema. How to repeat: Go to Data Dump tab and Export to Disk then select the following options: - Export to Self-Contained file.

  14. Python UnboundLocalError: local variable referenced before assignment

    UnboundLocalError: local variable referenced before assignment. Example #1: Accessing a Local Variable. Solution #1: Passing Parameters to the Function. Solution #2: Use Global Keyword. Example #2: Function with if-elif statements. Solution #1: Include else statement. Solution #2: Use global keyword. Summary.

  15. UnboundLocalError Local variable Referenced Before Assignment in Python

    Avoid Reassignment of Global Variables. Below, code calculates a new value (local_var) based on the global variable and then prints both the local and global variables separately.It demonstrates that the global variable is accessed directly without being reassigned within the function.

  16. UnboundLocalError: local variable 'cursor' referenced before assignment

    8. You only define conn and cursor inside the if block checking the form values. If the block is not entered, they're not defined, but you still try to reference them to close them anyway. You should only call close on both if you've defined them. Either move conn = and cursor = to before the if block, or move the close calls to within the block.

  17. [Solved] Why am I getting "Unhandled exception: local variable 'pwd

    Jossy Asks: Why am I getting "Unhandled exception: local variable 'pwd' referenced before assignment"? I'm trying to transfer a schema from my personal...

  18. Why am I getting "Unhandled exception: local variable 'pwd' referenced

    Unhandled exception: local variable 'pwd' referenced before assignment Check the log for more details. The log file has this: 14:05:01 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1 14:05:01 [ERR][ pymforms]: Unhandled exception in Python code: Traceback (most recent call last): File "C:\Program Files\MySQL\MySQL Workbench 8. ...

  19. mysql-workbench

    我已经导出了一个 SQL 转储文件,并试图将其导入 RDS。. 但是,我收到以下错误:. Unhandled exception: local variable 'pwd' referenced before assignment. Check the log for more details. 日志文件有这个:. 14:05:01 [WRN][wb_admin_export.py:process_db:277]: Task exited with code 1. 14:05:01 [ERR][ pymforms ...

  20. local variable referenced before assignment in strange condition

    local variable referenced before assignment in strange condition. Ask Question Asked 9 years, 1 month ago. Modified 9 years, 1 month ago. Viewed 830 times 0 I have some code that takes input from an open source database, then returns a report based on some of the tables. ... except Exception, e: connection_chili.rollback() print "ERROR: " + str ...

  21. Securing Applications and Services Guide

    Those typically reference Client scopes defined on a particular client. Note that the scope openid will always be added to the list of scopes by the adapter. For example, if you enter the scope options address phone , then the request to Keycloak will contain the scope parameter scope=openid address phone .

  22. python

    1. The variables wins, money and losses were declared outside the scope of the fiftyfifty() function, so you cannot update them from inside the function unless you explicitly declare them as global variables like this: def fiftyfifty(bet): global wins, money, losses. chance = random.randint(0,100)