enhanced logon procedures and fixed test cases

This commit is contained in:
Axel Uhl committed 2015-02-25 00:53:43 +01:00
1 parent cf010e8c02
commit 6076f03c60
5 files changed
+70 -73

No files matched your search

@@ -19,7 +19,7 @@ upRealm.permissionsForRoleProvider = $permissionsForRoleProvider
oauthRealm = com.sap.sse.security.OAuthRealm
oauthRealm.permissionsForRoleProvider = $permissionsForRoleProvider
bearerTokenRealm = com.sap.sse.security.BearerTokenRealm
accessTokenRealm.permissionsForRoleProvider = $permissionsForRoleProvider
bearerTokenRealm.permissionsForRoleProvider = $permissionsForRoleProvider
securityManager.realms = $upRealm, $oauthRealm, $bearerTokenRealm
@@ -1,12 +1,10 @@
package com.sap.sse.security.test;
package com.sap.sse.security.jaxrs.api;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import javax.ws.rs.core.Response;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
@@ -17,11 +15,12 @@ import org.junit.Before;
import org.junit.Test;
import com.sap.sse.common.mail.MailException;
import com.sap.sse.security.BearerAuthenticationToken;
import com.sap.sse.security.SecurityService;
import com.sap.sse.security.User;
import com.sap.sse.security.UsernamePasswordRealm;
import com.sap.sse.security.impl.Activator;
import com.sap.sse.security.impl.SecurityServiceImpl;
import com.sap.sse.security.jaxrs.api.SecurityResource;
import com.sap.sse.security.shared.UserManagementException;
import com.sap.sse.security.userstore.mongodb.PersistenceFactory;
import com.sap.sse.security.userstore.mongodb.UserStoreImpl;
@@ -59,7 +58,7 @@ public class SecurityResourceTest {
}
private String createAccessToken() throws ParseException {
String responseJsonString = (String) servlet.accessToken("admin", "admin").getEntity();
String responseJsonString = (String) servlet.respondWithAccessTokenForUser("admin").getEntity();
JSONObject responseJson = (JSONObject) new JSONParser().parse(responseJsonString);
assertEquals("admin", responseJson.get("username"));
String accessToken = (String) responseJson.get("access_token");
@@ -70,10 +69,11 @@ public class SecurityResourceTest {
@Test
public void createAccessTokenAndAuthenticate() throws ParseException {
String accessToken = createAccessToken();
Response response = servlet.authenticate(accessToken);
JSONObject responseJson = (JSONObject) new JSONParser().parse((String) response.getEntity());
assertEquals("admin", responseJson.get("username"));
User user = service.getUserByAccessToken(accessToken);
assertNotNull(user);
assertEquals("admin", user.getName());
final Subject subject = SecurityUtils.getSubject();
subject.login(new BearerAuthenticationToken(accessToken));
assertTrue(subject.isAuthenticated());
assertEquals("admin", subject.getPrincipal());
assertTrue(subject.isPermitted("can do"));
@@ -21,6 +21,8 @@ customGwt = com.sap.sse.security.CustomFilter
customGwt.loginUrl = /security/ui/Login.html
customGwt.successUrl = /UserManagement.html
authc.loginUrl=/api/restsecurity/login
bearerToken = com.sap.sse.security.BearerTokenAuthenticationFilter
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
@@ -30,6 +32,8 @@ cacheManager = com.sap.sse.security.SessionCacheManager
securityManager.cacheManager = $cacheManager
[urls]
/api/restsecurity/login = anon
/api/restsecurity/login = authc
/api/restsecurity/logout = logout
/api/restsecurity/access_token = bearerToken
/api/restsecurity/hello = bearerToken
/api/restsecurity/hello_post = bearerToken
@@ -5,14 +5,24 @@ import java.util.Locale;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import com.sap.sse.security.impl.FormAuthenticationFilterWithPublicCreateToken;
import com.sap.sse.security.jaxrs.api.SecurityResource;
/**
* Looks for an "Authorization: Bearer <token>" HTTP header. If found, tries to authenticate a user
* with the bearer token presented. If instead an "Authorization: Basic ..." header field is found, HTTP
* basic authentication is attempted using a regular username/password token.
* basic authentication is attempted using a regular username/password token. If that isn't found, looks
* for username/password fields in the POST parameters, like the {@link FormAuthenticationFilter} does.<p>
*
* This filter can be used for securing REST requests, in conjunction with the {@link SecurityResource}'s
* {@link SecurityResource#accessToken(String, String)} through which a bearer token can be obtained using
* basic authentication.
*
* @author Axel Uhl (D043530)
*
@@ -20,22 +30,36 @@ import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
public class BearerTokenAuthenticationFilter extends BasicHttpAuthenticationFilter {
private static final String BEARER = "Bearer";
/**
* Used to delegate requests to in case no bearer token and no basic authentication is found
* in the "Authorization:" header field.
*/
private final FormAuthenticationFilterWithPublicCreateToken formAuthenticationFilter;
public BearerTokenAuthenticationFilter() {
formAuthenticationFilter = new FormAuthenticationFilterWithPublicCreateToken();
}
@Override
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
String authorizationHeader = getAuthzHeader(request);
if (authorizationHeader != null && !authorizationHeader.isEmpty()) {
String[] authTokens = authorizationHeader.split(" ");
if (authTokens[0].equals(BEARER)) {
if (authTokens[0].equalsIgnoreCase(BEARER)) {
return new BearerAuthenticationToken(authTokens[1]);
} else if (authTokens[0].equalsIgnoreCase(HttpServletRequest.BASIC_AUTH)) {
return super.createToken(request, response);
}
}
return super.createToken(request, response);
return formAuthenticationFilter.createToken(request, response);
}
@Override
protected boolean isLoginAttempt(String authzHeader) {
protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
String authzScheme = BEARER.toLowerCase(Locale.ENGLISH);
return authzHeader.toLowerCase(Locale.ENGLISH).startsWith(authzScheme) || super.isLoginAttempt(authzHeader);
final String authzHeader = getAuthzHeader(request);
return (authzHeader != null && authzHeader.toLowerCase(Locale.ENGLISH).startsWith(authzScheme)) ||
super.isLoginAttempt(request, response) || formAuthenticationFilter.isLoginSubmission(request, response);
}
}
@@ -1,31 +1,19 @@
package com.sap.sse.security.jaxrs.api;
import java.util.logging.Logger;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import org.apache.shiro.SecurityUtils;
import org.json.simple.JSONObject;
import com.sap.sse.security.User;
import com.sap.sse.security.jaxrs.AbstractSecurityResource;
import com.sap.sse.security.shared.UserManagementException;
@Path("/restsecurity")
public class SecurityResource extends AbstractSecurityResource {
private static final Logger logger = Logger.getLogger(SecurityResource.class.getName());
private Response getSecurityErrorResponse(String msg) {
return Response.status(Status.BAD_REQUEST).entity(msg).type(MediaType.TEXT_PLAIN_TYPE).build();
}
@GET
@Path("/hello")
@Produces("text/plain;charset=UTF-8")
@@ -38,62 +26,43 @@ public class SecurityResource extends AbstractSecurityResource {
}
return Response.ok(messageText, MediaType.TEXT_PLAIN_TYPE).build();
}
@POST
@Path("/login")
@Path("/hello")
@Produces("text/plain;charset=UTF-8")
public Response login(@FormParam("username") String username, @FormParam("password") String password) {
try {
getService().login(username, password);
logger.info("Successfully logged in " + username + " with password");
} catch (UserManagementException e) {
logger.info("Logging in " + username + " with password failed: "+e.getMessage());
return getSecurityErrorResponse(e.getMessage());
public Response sayHelloPost() {
final String messageText;
if (SecurityUtils.getSubject().isAuthenticated()) {
messageText = "Hello "+SecurityUtils.getSubject().getPrincipal();
} else {
messageText = "Hello!";
}
return Response.ok("Logged in!", MediaType.TEXT_PLAIN_TYPE).build();
return Response.ok(messageText, MediaType.TEXT_PLAIN_TYPE).build();
}
@GET
@Path("/access_token")
@Produces("application/json;charset=UTF-8")
public Response accessToken() {
return respondWithAccessTokenForAuthenticatedSubject();
}
@POST
@Path("/access_token")
@Produces("application/json;charset=UTF-8")
public Response accessToken(@FormParam("username") String username, @FormParam("password") String password) {
try {
getService().login(username, password);
logger.info("Successfully logged in " + username + " with password");
JSONObject response = new JSONObject();
response.put("username", username);
response.put("access_token", getService().createAccessToken(username));
return Response.ok(response.toJSONString(), MediaType.APPLICATION_JSON_TYPE).build();
} catch (UserManagementException e) {
logger.info("Logging in " + username + " with password failed: "+e.getMessage());
return getSecurityErrorResponse(e.getMessage());
}
public Response accessTokenPost() {
return respondWithAccessTokenForAuthenticatedSubject();
}
@POST
@Path("/authenticate")
@Produces("application/json;charset=UTF-8")
public Response authenticate(@FormParam("access_token") String accessToken) {
User user = getService().loginByAccessToken(accessToken);
if (user == null) {
logger.info("Invalid access token " + accessToken);
return Response.status(Status.UNAUTHORIZED).entity("Access token " + accessToken + " not recognized")
.build();
} else {
logger.info("Authenticated " + user.getName() + " with access token");
}
private Response respondWithAccessTokenForAuthenticatedSubject() {
final String username = SecurityUtils.getSubject().getPrincipal().toString();
return respondWithAccessTokenForUser(username);
}
Response respondWithAccessTokenForUser(final String username) {
JSONObject response = new JSONObject();
response.put("username", user.getName());
response.put("email", user.getEmail());
response.put("username", username);
response.put("access_token", getService().createAccessToken(username));
return Response.ok(response.toJSONString(), MediaType.APPLICATION_JSON_TYPE).build();
}
@GET
@Path("/logout")
@Produces("text/plain;charset=UTF-8")
public Response logout() {
getService().logout();
return Response.ok("Logged out", MediaType.TEXT_PLAIN_TYPE).build();
}
}
}