Managing Security and Authentication
1. Enabling Security
Example: Enable Security in Jenkins
// Groovy script to enable security
import jenkins.model.Jenkins
import hudson.security.*
def jenkins = Jenkins.getInstance()
// Enable security
jenkins.setSecurityRealm(new HudsonPrivateSecurityRealm(false))
jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy())
// Save configuration
jenkins.save()
| Setting | Description | Default | Notes |
|---|---|---|---|
| Security Realm | Defines how users are authenticated | None |
Must be set to enable security |
| Authorization Strategy | Defines how users are authorized | None |
Must be set to enable security |
Note: After enabling security, all users must authenticate to access Jenkins.
Warning: Disabling security after enabling it will require manual configuration to re-enable.
Security Configuration Summary
- Enable security realm for user authentication
- Set authorization strategy for access control
- Save configuration to apply changes
2. Configuring Authentication Realms
| Realm Type | Description | Configuration | Notes |
|---|---|---|---|
| Jenkins' Internal | Default user database managed by Jenkins | Manage Jenkins > Configure Global Security |
Users created here are stored in users.xml |
| LDAP | Integrates with LDAP/Active Directory servers | Manage Jenkins > Configure Global Security > LDAP |
Supports multiple LDAP servers, group-based permissions |
| Active Directory | Specialized LDAP integration for Microsoft AD | Manage Jenkins > Configure Global Security > Active Directory |
Supports nested groups, domain trust, and GPO-based policies |
| OAuth | Authentication via OAuth providers (e.g., GitHub, Google) | Manage Jenkins > Configure Global Security > OAuth |
Requires plugin (e.g., github-branch-source-plugin) |
| SAML | Single Sign-On using SAML 2.0 | Manage Jenkins > Configure Global Security > SAML |
Requires saml-plugin; supports IdP-initiated login |
Example: LDAP Configuration
<securityRealm class="hudson.security.LDAPSecurityRealm">
<server>ldap.example.com</server>
<rootDN>dc=example,dc=com</rootDN>
<managerDn>cn=admin,dc=example,dc=com</managerDn>
<managerPassword>secret</managerPassword>
<userSearchBase>ou=people</userSearchBase>
<userSearchFilter>(uid={0})</userSearchFilter>
<groupSearchBase>ou=groups</groupSearchBase>
<groupSearchFilter>(member={0})</groupSearchFilter>
</securityRealm>
Note: Ensure the Jenkins server has network access to the LDAP server and that the required plugins (e.g.,
ldap-plugin) are installed.
Warning: Never store passwords in plain text in configuration files. Use Jenkins' credential store or external secret management tools.
3. Using Jenkins User Database
| Property | Values | Description |
|---|---|---|
| jenkins.users.database.enabled | true |
Enables the built-in user database for authentication |
| jenkins.users.database.allowSignup | false |
Controls whether users can sign up via the UI |
| jenkins.users.database.autoCreateUser | true |
Automatically creates user accounts when they log in |
Example: Configure User Database
// Groovy script to enable and configure user database
import jenkins.model.Jenkins
def jenkins = Jenkins.getInstance()
def securityRealm = new hudson.security.HudsonPrivateSecurityRealm(false)
jenkins.setSecurityRealm(securityRealm)
jenkins.save()
Note: The built-in user database is intended for small setups or testing. For production, consider integrating with LDAP or Active Directory.
Key Features of Jenkins User Database
- Stores user credentials locally in the Jenkins instance
- Supports role-based access control (RBAC) via plugins like Role-Based Authorization Strategy
- Can be extended with additional authentication methods using plugins
User Database vs External Authentication
- Local User DB: Simple setup, no external dependencies
- LDAP/Active Directory: Centralized user management, better for enterprise
4. Integrating with OAuth Providers
| Provider | Plugin | Configuration | Notes |
|---|---|---|---|
google-oauth |
|
Requires Google OAuth2 client credentials | |
| GitHub | github-oauth |
|
Uses GitHub App credentials |
| Azure AD | azure-ad |
|
Supports both OAuth and OpenID Connect |
Example: GitHub OAuth Configuration
security {
oauth2 {
clientId = 'ghp_abc123def456'
clientSecret = 'ghs_789xyz012'
redirectUrl = 'https://jenkins.example.com/securityRealm/oauth2/callback'
}
}
Note: Ensure the OAuth provider allows redirects to your Jenkins instance URL.
Warning: Store client secrets securely using Jenkins Credentials Store.
5. Configuring SAML Authentication
| Property | Value | Description |
|---|---|---|
| jenkins.url | https://jenkins.example.com |
Base URL of Jenkins instance |
| saml.idp.metadata.url | https://idp.example.com/metadata |
URL to SAML Identity Provider metadata |
| saml.idp.entity.id | https://idp.example.com |
Entity ID of the Identity Provider |
| saml.sp.entity.id | https://jenkins.example.com/saml |
Entity ID of the Service Provider (Jenkins) |
| saml.sp.signing.key | -----BEGIN PRIVATE KEY-----... |
Private key for signing SAML requests |
| saml.sp.signing.cert | -----BEGIN CERTIFICATE-----... |
Certificate for signing SAML requests |
Example: SAML Configuration in Jenkins
import jenkins.model.Jenkins
import org.jenkinsci.plugins.saml.SamlSecurityRealm
def jenkins = Jenkins.getInstance()
def realm = new SamlSecurityRealm(
"https://idp.example.com/metadata",
"https://jenkins.example.com/saml",
"https://idp.example.com",
"-----BEGIN PRIVATE KEY-----...",
"-----BEGIN CERTIFICATE-----..."
)
jenkins.setSecurityRealm(realm)
jenkins.save()
Note: Ensure that the SAML Identity Provider is configured to trust Jenkins as a Service Provider.
Warning: The SAML signing keys must be securely stored and managed to prevent unauthorized access.
SAML Authentication Setup Steps
- Obtain SAML metadata from Identity Provider
- Configure Jenkins to use the metadata URL
- Set up SP signing keys for SAML request signatures
- Map SAML attributes to Jenkins user roles
6. Setting Up Authorization Strategies
| Strategy | Description | Configuration | Notes |
|---|---|---|---|
| Role-Based Access Control (RBAC) | Assigns permissions based on user roles | Configure roles in Jenkins UI or via Jenkins Script Console | Supports fine-grained permissions for jobs, nodes, and system settings |
| Matrix-Based Security | Uses matrix-style permissions for users and groups | Defined in config.xml or via UI under "Manage Jenkins" → "Configure Global Security" |
Allows granular control over individual permissions |
| LDAP/Active Directory Integration | Authenticates users via external directory services | Configure under "Manage Jenkins" → "Configure Global Security" → "Security Realm" | Supports group-based permissions and single sign-on (SSO) |
| OAuth / SAML | Enables authentication through OAuth or SAML providers | Requires plugins like "OAuth Plugin" or "SAML Plugin" | Useful for enterprise environments with centralized identity management |
Example: Configuring RBAC in Jenkins Script Console
import jenkins.model.Jenkins
import hudson.security.*
def jenkins = Jenkins.getInstance()
def strategy = new RoleMap()
// Define roles and permissions
def adminRole = new Role("admin", "Admin role with full access")
def developerRole = new Role("developer", "Developer role with read and build access")
// Assign permissions to roles
adminRole.addPermission("hudson.model.Hudson.Administer")
developerRole.addPermission("hudson.model.Item.Read")
developerRole.addPermission("hudson.model.Item.Build")
strategy.addRole(adminRole)
strategy.addRole(developerRole)
// Apply to Jenkins
jenkins.setAuthorizationStrategy(strategy)
jenkins.save()
Note: RBAC is best suited for teams with well-defined roles and minimal overlap in permissions.
Warning: Matrix-based security can become complex to manage as the number of users and permissions increases.
Summary of Authorization Strategies
- RBAC is ideal for teams with clear role definitions.
- Matrix-Based offers granular control but requires more maintenance.
- LDAP/AD integrates with existing enterprise identity systems.
- OAuth/SAML supports modern authentication flows and SSO.
7. Configuring Project-Based Security
| Option | Values | Description |
|---|---|---|
| project.matrix.auth | true |
Enables matrix-based security for projects |
| project.inherit.global | false |
Prevents inheriting global security settings |
Example: Configure Project-Based Security
import jenkins.model.Jenkins
import hudson.security.AuthorizationStrategy
import hudson.security.ProjectMatrixAuthorizationStrategy
def jenkins = Jenkins.instance
def authStrategy = new ProjectMatrixAuthorizationStrategy()
// Define permissions for users and groups
authStrategy.add("user1", "hudson.model.Item.Read")
authStrategy.add("user2", "hudson.model.Item.Read")
authStrategy.add("user2", "hudson.model.Item.Build")
jenkins.setAuthorizationStrategy(authStrategy)
jenkins.save()
Note: Project-based security allows fine-grained control over individual project permissions, separate from global settings.
8. Using Role-Based Access Control
| Role | Description | Permissions | Assigned Users |
|---|---|---|---|
| Admin | Full system access and configuration | All permissions including managing users, plugins, and jobs | System administrators |
| Read-only | View access to jobs and build results | Read access to jobs, builds, and configuration | Developers, QA team |
| Job Creator | Create and manage jobs within defined scope | Create, configure, and run jobs | Developers, CI/CD engineers |
| Build Executor | Execute builds and view build results | Run builds, view logs, access build artifacts | Build servers, CI agents |
Example: Configure RBAC in Jenkins
// Groovy script to define roles and assign users
import jenkins.model.Jenkins
import hudson.security.*
def jenkins = Jenkins.getInstance()
def securityRealm = jenkins.getSecurityRealm()
def authorizationStrategy = jenkins.getAuthorizationStrategy()
// Define roles and permissions
def roleMap = new RoleMap()
roleMap.addRole(new Role("Admin", "Full system access"))
roleMap.addRole(new Role("Read-only", "View only access"))
roleMap.addRole(new Role("Job Creator", "Create and manage jobs"))
// Assign users to roles
roleMap.assignRole("Admin", "adminUser")
roleMap.assignRole("Read-only", "developer1")
roleMap.assignRole("Job Creator", "devUser")
// Apply the role map
authorizationStrategy.setRoleMap(roleMap)
jenkins.save()
Note: RBAC in Jenkins is managed through the
Role-Based Strategy plugin. Ensure the plugin is installed and enabled before configuring roles.
Key RBAC Concepts
- Role defines a set of permissions
- Scope determines where the role applies (global or specific jobs)
- User Assignment links users to roles
- Permission Matrix maps roles to specific actions
RBAC vs Traditional ACL
- RBAC: Centralized role management, easier to maintain
- Traditional ACL: Per-user permission settings, more granular but harder to manage
9. Managing API Tokens
| Token Type | Description | Usage | Notes |
|---|---|---|---|
| User API Token | Unique identifier for authenticating Jenkins API requests | curl -H "Jenkins-Crumb=abc123" -H "Authorization: Bearer abcdef123456" http://jenkins.example.com/api/json |
Generated per user, can be revoked individually |
| System API Token | Global token for system-wide operations (e.g., CI/CD pipelines) | curl -H "Authorization: Bearer system-token-123456" http://jenkins.example.com/api/json |
Can be used across multiple jobs and agents |
Example: Creating a User API Token
curl -u "username:password" \
-X POST "http://jenkins.example.com/user/username/apiToken" \
-d "newToken=MyNewToken"
Note: API tokens should be stored securely and rotated regularly to maintain security.
Warning: Never embed API tokens directly in scripts or configuration files exposed to version control systems.
Token Management Best Practices
- Use short-lived tokens where possible
- Revoke unused or compromised tokens immediately
- Store tokens in secure credential stores like HashiCorp Vault or Jenkins Credentials Plugin
- Implement token scopes to limit access rights
10. Configuring CSRF Protection
| Property | Default Value | Description |
|---|---|---|
| hudson.security.csrf.GlobalCrumbIssuer | Enabled | Enables or disables CSRF protection globally in Jenkins. |
| crumbIssuer.className | DefaultCrumbIssuer | Class name of the crumb issuer implementation used for CSRF tokens. |
Example: Enabling CSRF Protection via Jenkins Configuration
import jenkins.model.Jenkins
import hudson.security.csrf.GlobalCrumbIssuer
def jenkins = Jenkins.getInstance()
def crumbIssuer = new GlobalCrumbIssuer()
jenkins.setCrumbIssuer(crumbIssuer)
jenkins.save()
Note: CSRF protection is enabled by default in Jenkins. Disabling it can pose a security risk.
11. Setting Agent-to-Master Security
| Configuration | Description | Default Value | Notes |
|---|---|---|---|
| jenkins.agent.port | Port for agents to connect to master | 50000 |
Must be accessible from agents |
| jenkins.agent.host | Host address for agent connection | 0.0.0.0 |
Use 127.0.0.1 for local only |
| jenkins.agent.secret | Secret key for agent authentication | auto-generated |
Required for secure agent connection |
Example: Configure Agent Port and Secret
import jenkins.model.Jenkins
def jenkins = Jenkins.instance
jenkins.setAgentPort(50001)
jenkins.setSlaveAgentSecret("secure-secret-key")
jenkins.save()
Note: Ensure the agent port is open in firewall rules and accessible from agent machines.
Warning: Changing the agent port or secret requires reconfiguration of all agents.