few changes after testing with authoriser

revert-70aa11f8
ayyoob 8 years ago
parent fe263efe60
commit fede8ec409

@ -78,10 +78,12 @@
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>
<artifactId>org.wso2.carbon.base</artifactId> <artifactId>org.wso2.carbon.base</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.googlecode.json-simple.wso2</groupId> <groupId>com.googlecode.json-simple.wso2</groupId>
<artifactId>json-simple</artifactId> <artifactId>json-simple</artifactId>
<scope>provided</scope>
</dependency> </dependency>
<dependency> <dependency>
<groupId>org.wso2.carbon</groupId> <groupId>org.wso2.carbon</groupId>

@ -92,7 +92,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
if (registrationProfile.getTags() == null || registrationProfile.getTags().length == 0) { if (registrationProfile.getTags() == null || registrationProfile.getTags().length == 0) {
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Tags should not be empty").build(); return Response.status(Response.Status.NOT_ACCEPTABLE).entity("Tags should not be empty").build();
} }
if (APIUtil.getAllowedApisTags().containsAll(Arrays.asList(registrationProfile.getTags()))) { if (!APIUtil.getAllowedApisTags().containsAll(Arrays.asList(registrationProfile.getTags()))) {
return Response.status(Response.Status.NOT_ACCEPTABLE).entity("APIs(Tags) are not allowed to this user." return Response.status(Response.Status.NOT_ACCEPTABLE).entity("APIs(Tags) are not allowed to this user."
).build(); ).build();
} }

@ -92,6 +92,6 @@ public class APIUtil {
//Todo get allowed cdmf service tags from config. //Todo get allowed cdmf service tags from config.
List<String> allowedApisTags = getDeviceManagementProviderService().getAvailableDeviceTypes(); List<String> allowedApisTags = getDeviceManagementProviderService().getAvailableDeviceTypes();
allowedApisTags.add(DEFAULT_CDMF_API_TAG); allowedApisTags.add(DEFAULT_CDMF_API_TAG);
return getAllowedApisTags(); return allowedApisTags;
} }
} }

@ -47,17 +47,25 @@ public class DeviceAccessAuthorizationAdminServiceImpl implements DeviceAccessAu
@POST @POST
@Override @Override
public Response isAuthorized(AuthorizationRequest authorizationRequest) { public Response isAuthorized(AuthorizationRequest authorizationRequest) {
try { int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId();
int currentTenantId = CarbonContext.getThreadLocalCarbonContext().getTenantId(); String loggedinUserTenantDomain = CarbonContext.getThreadLocalCarbonContext().getTenantDomain();
if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) { if (authorizationRequest.getTenantDomain() != null) {
return Response.status(Response.Status.UNAUTHORIZED).entity( if (!loggedinUserTenantDomain.equals(authorizationRequest.getTenantDomain())) {
new ErrorResponse.ErrorResponseBuilder().setMessage( if (MultitenantConstants.SUPER_TENANT_ID != currentTenantId) {
"Current logged in user is not authorized to perform this operation").build()).build(); return Response.status(Response.Status.UNAUTHORIZED).entity(
} new ErrorResponse.ErrorResponseBuilder().setMessage(
if (authorizationRequest.getTenantDomain() == null || authorizationRequest.getTenantDomain().isEmpty()) { "Current logged in user is not authorized to perform this operation").build())
authorizationRequest.setTenantDomain( .build();
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain()); }
} }
} else {
authorizationRequest.setTenantDomain(loggedinUserTenantDomain);
}
if (authorizationRequest.getTenantDomain() == null || authorizationRequest.getTenantDomain().isEmpty()) {
authorizationRequest.setTenantDomain(
PrivilegedCarbonContext.getThreadLocalCarbonContext().getTenantDomain());
}
try {
PrivilegedCarbonContext.startTenantFlow(); PrivilegedCarbonContext.startTenantFlow();
PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain(
authorizationRequest.getTenantDomain(), true); authorizationRequest.getTenantDomain(), true);

@ -110,6 +110,12 @@
<url>/admin/devices</url> <url>/admin/devices</url>
<method>GET</method> <method>GET</method>
</Permission> </Permission>
<Permission>
<name>Verify device authorization</name>
<path>/device-mgt/devices</path>
<url>/admin/authorization</url>
<method>POST</method>
</Permission>
<Permission> <Permission>
<name>View device types</name> <name>View device types</name>
<path>/device-mgt/devices/Admin-DeviceType-View</path> <path>/device-mgt/devices/Admin-DeviceType-View</path>

@ -27,6 +27,7 @@
<jaxrs:serviceBeans> <jaxrs:serviceBeans>
<ref bean="deviceManagementService"/> <ref bean="deviceManagementService"/>
<ref bean="deviceManagementAdminService"/> <ref bean="deviceManagementAdminService"/>
<ref bean="deviceAccessAuthorizationAdminService"/>
<ref bean="deviceTypeManagementService"/> <ref bean="deviceTypeManagementService"/>
<ref bean="activityProviderService"/> <ref bean="activityProviderService"/>
<ref bean="notificationManagementService"/> <ref bean="notificationManagementService"/>
@ -80,6 +81,7 @@
<bean id="userManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.UserManagementAdminServiceImpl"/> <bean id="userManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.UserManagementAdminServiceImpl"/>
<bean id="dashboardServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DashboardImpl"/> <bean id="dashboardServiceBean" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DashboardImpl"/>
<bean id="deviceTypeManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementServiceImpl"/> <bean id="deviceTypeManagementAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.DeviceTypeManagementServiceImpl"/>
<bean id="deviceAccessAuthorizationAdminService" class="org.wso2.carbon.device.mgt.jaxrs.service.impl.admin.DeviceAccessAuthorizationAdminServiceImpl"/>
<bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/> <bean id="jsonProvider" class="org.wso2.carbon.device.mgt.jaxrs.common.GsonMessageBodyHandler"/>
<!--<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>--> <!--<bean id="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>-->

@ -129,6 +129,7 @@ public class DeviceAccessAuthorizationServiceImpl implements DeviceAccessAuthori
DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult(); DeviceAuthorizationResult deviceAuthorizationResult = new DeviceAuthorizationResult();
if (isAdmin(username, tenantId)) { if (isAdmin(username, tenantId)) {
deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers); deviceAuthorizationResult.setAuthorizedDevices(deviceIdentifiers);
return deviceAuthorizationResult;
} }
for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) { for (DeviceIdentifier deviceIdentifier : deviceIdentifiers) {
//check for admin and ownership permissions //check for admin and ownership permissions

@ -80,14 +80,14 @@ var utils = function () {
return dynamicClientAppCredentials; return dynamicClientAppCredentials;
}; };
publicMethods["getTenantBasedClientAppCredentials"] = function (username, jwtToken) { publicMethods["getTenantBasedClientAppCredentials"] = function (username) {
if (!username || !jwtToken) { if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username or jwt token is found " + "based client app credentials. No username " +
"as input - getTenantBasedClientAppCredentials(x, y)"); "as input - getTenantBasedClientAppCredentials(x)");
return null; return null;
} else { } else {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable //noinspection JSUnresolvedFunction, JSUnresolvedVariable
var tenantDomain = carbon.server.tenantDomain({username: username}); var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) { if (!tenantDomain) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " + log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
@ -100,6 +100,12 @@ var utils = function () {
if (cachedTenantBasedClientAppCredentials) { if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials; return cachedTenantBasedClientAppCredentials;
} else { } else {
var adminUsername = deviceMgtProps["adminUser"];
//claims required for jwtAuthenticator.
var claims = {"http://wso2.org/claims/enduserTenantId": "-1234",
"http://wso2.org/claims/enduser": adminUsername};
var jwtToken = publicMethods.getJwtToken(adminUsername, claims);
// register a tenant based client app at API Manager // register a tenant based client app at API Manager
var applicationName = "webapp_" + tenantDomain; var applicationName = "webapp_" + tenantDomain;
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"] var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
@ -109,7 +115,7 @@ var utils = function () {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false); xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json"); xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "X-JWT-Assertion " + jwtToken); xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken);
xhr.send(); xhr.send();
if (xhr["status"] == 201 && xhr["responseText"]) { if (xhr["status"] == 201 && xhr["responseText"]) {
@ -291,7 +297,7 @@ var utils = function () {
} }
}; };
publicMethods["getJwtToken"] = function (username) { publicMethods["getJwtToken"] = function (username, claims) {
if (!username) { if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new jwt token"); log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new jwt token");
return null; return null;
@ -303,7 +309,12 @@ var utils = function () {
//noinspection JSUnresolvedFunction //noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient(); var jwtClient = JWTClientManagerService.getJWTClient();
// returning access token by JWT grant type // returning access token by JWT grant type
return jwtClient.getJwtToken(username); if (claims) {
return jwtClient.getJwtToken(username, claims);
} else {
return jwtClient.getJwtToken(username);
}
} }
}; };

@ -137,27 +137,19 @@ var handlers = function () {
"input - setUpEncodedTenantBasedClientAppCredentials(x)"); "input - setUpEncodedTenantBasedClientAppCredentials(x)");
} else { } else {
if (devicemgtProps["apimgt-gateway"]) { if (devicemgtProps["apimgt-gateway"]) {
var jwtToken = tokenUtil.getJwtToken(username); var tenantBasedClientAppCredentials = tokenUtil.getTenantBasedClientAppCredentials(username);
if (!jwtToken) { if (!tenantBasedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " + throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
"client credentials to session context as the server is unable to obtain " + "based client credentials to session context as the server is unable " +
"a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)"); "to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
} else { } else {
var tenantBasedClientAppCredentials = tokenUtil. var encodedTenantBasedClientAppCredentials =
getTenantBasedClientAppCredentials(username, jwtToken); tokenUtil.encode(tenantBasedClientAppCredentials["clientId"] + ":" +
if (!tenantBasedClientAppCredentials) { tenantBasedClientAppCredentials["clientSecret"]);
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " + // setting up encoded tenant based client credentials to session context.
"based client credentials to session context as the server is unable " + session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"],
"to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)"); encodedTenantBasedClientAppCredentials);
} else { }
var encodedTenantBasedClientAppCredentials =
tokenUtil.encode(tenantBasedClientAppCredentials["clientId"] + ":" +
tenantBasedClientAppCredentials["clientSecret"]);
// setting up encoded tenant based client credentials to session context.
session.put(constants["ENCODED_TENANT_BASED_CLIENT_APP_CREDENTIALS"],
encodedTenantBasedClientAppCredentials);
}
}
} else { } else {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials(); var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials();
if (!dynamicClientAppCredentials) { if (!dynamicClientAppCredentials) {

@ -43,6 +43,7 @@ import java.security.KeyManagementException;
import java.security.KeyStoreException; import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@ -164,6 +165,10 @@ public class JWTClient {
return JWTClientUtil.generateSignedJWTAssertion(username, jwtConfig, isDefaultJWTClient); return JWTClientUtil.generateSignedJWTAssertion(username, jwtConfig, isDefaultJWTClient);
} }
public String getJwtToken(String username, Map<String, String> claims) throws JWTClientException {
return JWTClientUtil.generateSignedJWTAssertion(username, jwtConfig, isDefaultJWTClient, claims);
}
} }

@ -33,6 +33,7 @@ import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy; import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.impl.client.HttpClients; import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils; import org.apache.http.util.EntityUtils;
import org.apache.solr.common.util.Hash;
import org.wso2.carbon.base.MultitenantConstants; import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext; import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.KeyStoreManager; import org.wso2.carbon.core.util.KeyStoreManager;
@ -55,7 +56,9 @@ import java.security.*;
import java.security.cert.CertificateException; import java.security.cert.CertificateException;
import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPrivateKey;
import java.util.Date; import java.util.Date;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
import java.util.Properties; import java.util.Properties;
/** /**
@ -193,8 +196,13 @@ public class JWTClientUtil {
tenantRegistryLoader.loadTenantRegistry(tenantId); tenantRegistryLoader.loadTenantRegistry(tenantId);
} }
public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig, boolean isDefaultJWTClient) public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig, boolean isDefaultJWTClient)
throws JWTClientException { throws JWTClientException {
return generateSignedJWTAssertion(username, jwtConfig, isDefaultJWTClient, null);
}
public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig, boolean isDefaultJWTClient,
Map<String, String> customClaims) throws JWTClientException {
try { try {
String subject = username; String subject = username;
long currentTimeMillis = System.currentTimeMillis(); long currentTimeMillis = System.currentTimeMillis();
@ -222,6 +230,11 @@ public class JWTClientUtil {
claimsSet.setNotBeforeTime(new Date(nbf)); claimsSet.setNotBeforeTime(new Date(nbf));
claimsSet.setJWTID(jti); claimsSet.setJWTID(jti);
claimsSet.setAudience(aud); claimsSet.setAudience(aud);
if (customClaims != null && !customClaims.isEmpty()) {
for (String key : customClaims.keySet()) {
claimsSet.setClaim(key, customClaims.get(key));
}
}
// get Keystore params // get Keystore params
String keyStorePath = jwtConfig.getKeyStorePath(); String keyStorePath = jwtConfig.getKeyStorePath();

@ -21,17 +21,25 @@ package org.wso2.carbon.webapp.authenticator.framework.authenticator;
import org.apache.catalina.connector.Request; import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response; import org.apache.catalina.connector.Response;
import org.apache.catalina.util.Base64; import org.apache.catalina.util.Base64;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.ByteChunk;
import org.apache.tomcat.util.buf.CharChunk; import org.apache.tomcat.util.buf.CharChunk;
import org.apache.tomcat.util.buf.MessageBytes; import org.apache.tomcat.util.buf.MessageBytes;
import org.wso2.carbon.user.api.UserStoreException;
import org.wso2.carbon.user.api.UserStoreManager;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationException;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticatorFrameworkDataHolder;
import org.wso2.carbon.webapp.authenticator.framework.Constants; import org.wso2.carbon.webapp.authenticator.framework.Constants;
import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo; import org.wso2.carbon.webapp.authenticator.framework.AuthenticationInfo;
import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils;
import java.util.Properties; import java.util.Properties;
public class BasicAuthAuthenticator implements WebappAuthenticator { public class BasicAuthAuthenticator implements WebappAuthenticator {
private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth"; private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth";
private static final Log log = LogFactory.getLog(BasicAuthAuthenticator.class);
@Override @Override
public void init() { public void init() {
@ -54,7 +62,27 @@ public class BasicAuthAuthenticator implements WebappAuthenticator {
@Override @Override
public AuthenticationInfo authenticate(Request request, Response response) { public AuthenticationInfo authenticate(Request request, Response response) {
return new AuthenticationInfo(); AuthenticationInfo authenticationInfo = new AuthenticationInfo();
Credentials credentials = getCredentials(request);
try {
int tenantId = Utils.getTenantIdOFUser(credentials.getUsername());
UserStoreManager userStore = AuthenticatorFrameworkDataHolder.getInstance().getRealmService().
getTenantUserRealm(tenantId).getUserStoreManager();
boolean authenticated = userStore.authenticate(credentials.getUsername(), credentials.getPassword());
if (authenticated) {
authenticationInfo.setStatus(Status.CONTINUE);
authenticationInfo.setUsername(credentials.getUsername());
authenticationInfo.setTenantDomain(Utils.getTenantDomain(tenantId));
authenticationInfo.setTenantId(tenantId);
} else {
authenticationInfo.setStatus(Status.FAILURE);
}
} catch (UserStoreException e) {
log.error("Error occurred while authenticating the user." + credentials.getUsername(), e);
} catch (AuthenticationException e) {
log.error("Error occurred while obtaining the tenant Id for user." + credentials.getUsername(), e);
}
return authenticationInfo;
} }
@Override @Override

@ -17,13 +17,13 @@
# #
#issuer of the JWT #issuer of the JWT
iss=CDMF_DEFAULT_IDP iss=iot_default
TokenEndpoint=https://localhost:${carbon.https.port}/oauth2/token TokenEndpoint=https://localhost:${carbon.https.port}/oauth2/token
#audience of JWT claim #audience of JWT claim
#comma seperated values #comma seperated values
aud=JwtIdentityAudience aud=wso2.org/products/iot
#expiration time of JWT (number of minutes from the current time) #expiration time of JWT (number of minutes from the current time)
exp=1000 exp=1000

Loading…
Cancel
Save