2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.controller.security;
10 import java.security.Principal;
11 import java.util.ArrayList;
12 import java.util.List;
14 import org.apache.catalina.realm.GenericPrincipal;
15 import org.apache.catalina.realm.RealmBase;
16 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
17 import org.opendaylight.controller.sal.authorization.UserLevel;
18 import org.opendaylight.controller.sal.utils.ServiceHelper;
19 import org.opendaylight.controller.usermanager.IUserManager;
20 import org.slf4j.Logger;
21 import org.slf4j.LoggerFactory;
23 public class ControllerCustomRealm extends RealmBase {
25 private static final String name = "ControllerCustomRealm";
27 private static final Logger logger = LoggerFactory
28 .getLogger(ControllerCustomRealm.class);
31 protected String getName() {
36 protected String getPassword(String username) {
37 IUserManager userManager = (IUserManager) ServiceHelper
38 .getGlobalInstance(IUserManager.class, this);
39 if (userManager != null) {
40 return userManager.getPassword(username);
42 throw new RuntimeException("User Manager reference is null");
47 protected Principal getPrincipal(String username) {
48 IUserManager userManager = (IUserManager) ServiceHelper
49 .getGlobalInstance(IUserManager.class, this);
50 if (userManager != null) {
51 List<String> controllerRoles = new ArrayList<String>();
52 for (UserLevel level : userManager.getUserLevels(username)) {
53 controllerRoles.add(level.toString());
55 return new GenericPrincipal(username, "", controllerRoles);
57 throw new RuntimeException("User Manager reference is null");
62 public Principal authenticate(String username, String credentials) {
64 IUserManager userManager = (IUserManager) ServiceHelper
65 .getGlobalInstance(IUserManager.class, this);
66 if (userManager != null) {
67 AuthResultEnum result = userManager.authenticate(username,
69 if (result.equals(AuthResultEnum.AUTHOR_PASS)
70 || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC)
71 || result.equals(AuthResultEnum.AUTH_ACCEPT)) {
72 return this.getPrincipal(username);
74 logger.debug("Authentication failed for user " + username);
78 throw new RuntimeException("User Manager reference is null");