1 package org.opendaylight.controller.security;
3 import java.security.Principal;
4 import java.util.ArrayList;
7 import org.apache.catalina.realm.GenericPrincipal;
8 import org.apache.catalina.realm.RealmBase;
9 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
10 import org.opendaylight.controller.sal.authorization.UserLevel;
11 import org.opendaylight.controller.sal.utils.ServiceHelper;
12 import org.opendaylight.controller.usermanager.IUserManager;
13 import org.slf4j.Logger;
14 import org.slf4j.LoggerFactory;
16 public class ControllerCustomRealm extends RealmBase {
18 private static final String name = "ControllerCustomRealm";
20 private static final Logger logger = LoggerFactory
21 .getLogger(ControllerCustomRealm.class);
24 protected String getName() {
29 protected String getPassword(String username) {
30 IUserManager userManager = (IUserManager) ServiceHelper
31 .getGlobalInstance(IUserManager.class, this);
32 if (userManager != null) {
33 return userManager.getPassword(username);
35 throw new RuntimeException("User Manager reference is null");
40 protected Principal getPrincipal(String username) {
41 IUserManager userManager = (IUserManager) ServiceHelper
42 .getGlobalInstance(IUserManager.class, this);
43 if (userManager != null) {
44 List<String> controllerRoles = new ArrayList<String>();
45 for (UserLevel level : userManager.getUserLevels(username)) {
46 controllerRoles.add(level.toString());
48 return new GenericPrincipal(username, "", controllerRoles);
50 throw new RuntimeException("User Manager reference is null");
55 public Principal authenticate(String username, String credentials) {
57 IUserManager userManager = (IUserManager) ServiceHelper
58 .getGlobalInstance(IUserManager.class, this);
59 if (userManager != null) {
60 AuthResultEnum result = userManager.authenticate(username,
62 if (result.equals(AuthResultEnum.AUTHOR_PASS)
63 || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC)
64 || result.equals(AuthResultEnum.AUTH_ACCEPT)) {
65 return this.getPrincipal(username);
67 logger.error("Authentication failed for user " + username);
71 throw new RuntimeException("User Manager reference is null");