few changes after testing with authoriser

4.x.x
ayyoob 8 years ago
parent fe263efe60
commit fede8ec409

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

@ -92,7 +92,7 @@ public class ApiApplicationRegistrationServiceImpl implements ApiApplicationRegi
if (registrationProfile.getTags() == null || registrationProfile.getTags().length == 0) {
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."
).build();
}

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

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

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

@ -27,6 +27,7 @@
<jaxrs:serviceBeans>
<ref bean="deviceManagementService"/>
<ref bean="deviceManagementAdminService"/>
<ref bean="deviceAccessAuthorizationAdminService"/>
<ref bean="deviceTypeManagementService"/>
<ref bean="activityProviderService"/>
<ref bean="notificationManagementService"/>
@ -80,6 +81,7 @@
<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="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="errorHandler" class="org.wso2.carbon.device.mgt.jaxrs.common.ErrorHandler"/>-->

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

@ -80,14 +80,14 @@ var utils = function () {
return dynamicClientAppCredentials;
};
publicMethods["getTenantBasedClientAppCredentials"] = function (username, jwtToken) {
if (!username || !jwtToken) {
publicMethods["getTenantBasedClientAppCredentials"] = function (username) {
if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
"based client app credentials. No username or jwt token is found " +
"as input - getTenantBasedClientAppCredentials(x, y)");
"based client app credentials. No username " +
"as input - getTenantBasedClientAppCredentials(x)");
return null;
} else {
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
//noinspection JSUnresolvedFunction, JSUnresolvedVariable
var tenantDomain = carbon.server.tenantDomain({username: username});
if (!tenantDomain) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving tenant " +
@ -100,6 +100,12 @@ var utils = function () {
if (cachedTenantBasedClientAppCredentials) {
return cachedTenantBasedClientAppCredentials;
} 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
var applicationName = "webapp_" + tenantDomain;
var requestURL = deviceMgtProps["oauthProvider"]["appRegistration"]
@ -109,7 +115,7 @@ var utils = function () {
var xhr = new XMLHttpRequest();
xhr.open("POST", requestURL, false);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Authorization", "X-JWT-Assertion " + jwtToken);
xhr.setRequestHeader("X-JWT-Assertion", "" + jwtToken);
xhr.send();
if (xhr["status"] == 201 && xhr["responseText"]) {
@ -291,7 +297,7 @@ var utils = function () {
}
};
publicMethods["getJwtToken"] = function (username) {
publicMethods["getJwtToken"] = function (username, claims) {
if (!username) {
log.error("{/app/modules/oauth/token-handler-utils.js} Error in retrieving new jwt token");
return null;
@ -303,7 +309,12 @@ var utils = function () {
//noinspection JSUnresolvedFunction
var jwtClient = JWTClientManagerService.getJWTClient();
// 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)");
} else {
if (devicemgtProps["apimgt-gateway"]) {
var jwtToken = tokenUtil.getJwtToken(username);
if (!jwtToken) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant based " +
"client credentials to session context as the server is unable to obtain " +
"a jwt token - setUpEncodedTenantBasedClientAppCredentials(x)");
} else {
var tenantBasedClientAppCredentials = tokenUtil.
getTenantBasedClientAppCredentials(username, jwtToken);
if (!tenantBasedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " +
"to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
} 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);
}
}
var tenantBasedClientAppCredentials = tokenUtil.getTenantBasedClientAppCredentials(username);
if (!tenantBasedClientAppCredentials) {
throw new Error("{/app/modules/oauth/token-handlers.js} Could not set up encoded tenant " +
"based client credentials to session context as the server is unable " +
"to obtain such credentials - setUpEncodedTenantBasedClientAppCredentials(x)");
} 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 {
var dynamicClientAppCredentials = tokenUtil.getDynamicClientAppCredentials();
if (!dynamicClientAppCredentials) {

@ -43,6 +43,7 @@ import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ -164,6 +165,10 @@ public class JWTClient {
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.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.solr.common.util.Hash;
import org.wso2.carbon.base.MultitenantConstants;
import org.wso2.carbon.context.PrivilegedCarbonContext;
import org.wso2.carbon.core.util.KeyStoreManager;
@ -55,7 +56,9 @@ import java.security.*;
import java.security.cert.CertificateException;
import java.security.interfaces.RSAPrivateKey;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
/**
@ -193,8 +196,13 @@ public class JWTClientUtil {
tenantRegistryLoader.loadTenantRegistry(tenantId);
}
public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig, boolean isDefaultJWTClient)
throws JWTClientException {
public static String generateSignedJWTAssertion(String username, JWTConfig jwtConfig, boolean isDefaultJWTClient)
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 {
String subject = username;
long currentTimeMillis = System.currentTimeMillis();
@ -222,6 +230,11 @@ public class JWTClientUtil {
claimsSet.setNotBeforeTime(new Date(nbf));
claimsSet.setJWTID(jti);
claimsSet.setAudience(aud);
if (customClaims != null && !customClaims.isEmpty()) {
for (String key : customClaims.keySet()) {
claimsSet.setClaim(key, customClaims.get(key));
}
}
// get Keystore params
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.Response;
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.CharChunk;
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.AuthenticationInfo;
import org.wso2.carbon.webapp.authenticator.framework.Utils.Utils;
import java.util.Properties;
public class BasicAuthAuthenticator implements WebappAuthenticator {
private static final String BASIC_AUTH_AUTHENTICATOR = "BasicAuth";
private static final Log log = LogFactory.getLog(BasicAuthAuthenticator.class);
@Override
public void init() {
@ -54,7 +62,27 @@ public class BasicAuthAuthenticator implements WebappAuthenticator {
@Override
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

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

Loading…
Cancel
Save