1 package org.opendaylight.controller.security;
3 import java.security.Principal;
6 import org.apache.catalina.realm.GenericPrincipal;
7 import org.apache.catalina.realm.RealmBase;
8 import org.opendaylight.controller.sal.authorization.AuthResultEnum;
9 import org.opendaylight.controller.sal.utils.ServiceHelper;
10 import org.opendaylight.controller.usermanager.IUserManager;
11 import org.slf4j.Logger;
12 import org.slf4j.LoggerFactory;
14 public class ControllerCustomRealm extends RealmBase {
16 private static final String name = "ControllerCustomRealm";
18 private static final Logger logger = LoggerFactory
19 .getLogger(ControllerCustomRealm.class);
22 protected String getName() {
27 protected String getPassword(String username) {
28 IUserManager userManager = (IUserManager) ServiceHelper
29 .getGlobalInstance(IUserManager.class, this);
30 if (userManager != null) {
31 return userManager.getPassword(username);
33 throw new RuntimeException("User Manager reference is null");
37 protected Principal getPrincipal(String username) {
38 IUserManager userManager = (IUserManager) ServiceHelper
39 .getGlobalInstance(IUserManager.class, this);
40 if (userManager != null) {
41 final List<String> roles = userManager.getUserRoles(username);
42 return new GenericPrincipal(username, getPassword(username), roles);
44 throw new RuntimeException("User Manager reference is null");
49 public Principal authenticate(String username, String credentials) {
51 IUserManager userManager = (IUserManager) ServiceHelper
52 .getGlobalInstance(IUserManager.class, this);
53 if (userManager != null) {
54 AuthResultEnum result = userManager.authenticate(username,
56 if (result.equals(AuthResultEnum.AUTHOR_PASS)
57 || result.equals(AuthResultEnum.AUTH_ACCEPT_LOC)
58 || result.equals(AuthResultEnum.AUTH_ACCEPT)) {
59 return this.getPrincipal(username);
61 logger.error("Authentication failed for user " + username);
65 throw new RuntimeException("User Manager reference is null");