Unit testing with Spring Session JDBC - spring

I developed a Java servlet that allows 2-Factor authentication.
First, I set up an endpoint (Web/authenticate/credentials) that accepts user credentials, checks if they exist in the database, in which case it returns the corresponding user challenge in the response, and set the user account ID in the session attribute.
Then, when the user receives the challenge, they provide a secret and send a request to a different endpoint (Web/authenticate/secret), which first checks if the requests is associated with any session, and then retrieves the user account ID from the session attribute to complete the authentication.
All this works well, when testing with Postman, but when I write some unit tests with MockMvc, a new session is always created as I send the secret to the second endpoint (Web/authenticate/secret), even when I explicitly set the SESSION cookie header.
Below is a snippet of the unit test that fails:
MvcResult preAuthMvcResult = preAuthenticateUser(deviceAlias, userPin);//This calls the first endpoint
// Get session cookie to send in next request header
String sessionCookie = preAuthMvcResult.getResponse().getHeader(HttpHeaders.SET_COOKIE);
JSONObject userCredentialsJson = new JSONObject();
userCredentialsJson.put("secret", secret);
// HTTP request
HttpHeaders httpHeader = new HttpHeaders();
httpHeader.add("x-api-key", apiKey);
httpHeader.add(PRE_AUTH_HEADER, accountIdHash);
httpHeader.add(HttpHeaders.COOKIE, sessionCookie);
// Act
MvcResult mvcResult = mockMvc
.perform(post("/Web/authenticate/secret").contentType(MediaType.APPLICATION_JSON_VALUE)
.headers(httpHeader).content(userCredentialsJson.toString()))
.andReturn();
// Assert
int responseStatus = mvcResult.getResponse().getStatus();
// This fails the test because a new session is created, and the authication cannot proceed, as the server lost track of the authenticating user
assertThat(responseStatus == HttpStatus.OK.value()).isTrue();

Related

How to Implement SAML Single Logout request from a microservice

I have implemented the multi-tenant SAML SSO in my application. I am using a Single Page Application application with the UI in AngularJS, Web API (for assertion URL), and a microservice for creating and handling the SAML requests. I am using the Itfoxtech library in my microservice.
I have implemented the SAML SSO Login successfully and it is working fine. However, I am facing issues while implementing the SAML Single Logout. On SAML Assertion, I am just extracting few claims and returning these to Web API. On Logout, it seems that I need the ClaimsIdentity and HttpContext. I have persisted ClaimsIdentity during the SAML Assertion and re-using it during the Logout but I don't have access to HttpContext. I have created a custom httpContext from DefaultHttpContext and tried to execute the following line of code,
var saml2LogoutRequest = await new Saml2LogoutRequest(config, User).DeleteSession(HttpContext);
but it gives an error,
No sign-out authentication handlers are registered. Did you forget to call AddAuthentication().AddCookies
My question is that how to perform a single logout without using the HttpContext or if it is required then how to manually create it?
Doing logout SAML 2.0 need NameID, NameID format and session index. To achive this you can polulate the ClaimsIdentity with the claims: Saml2ClaimTypes.NameId, Saml2ClaimTypes.NameIdFormat and Saml2ClaimTypes.SessionIndex.
In the case of single logout you only need to validate the request:
Saml2StatusCodes status;
var requestBinding = new Saml2PostBinding();
var logoutRequest = new Saml2LogoutRequest(config, User);
try
{
requestBinding.Unbind(Request.ToGenericHttpRequest(), logoutRequest);
status = Saml2StatusCodes.Success;
//TODO handle logout
}
catch (Exception exc)
{
// log exception
Debug.WriteLine("SingleLogout error: " + exc.ToString());
status = Saml2StatusCodes.RequestDenied;
}
and respond:
var responsebinding = new Saml2PostBinding();
responsebinding.RelayState = requestBinding.RelayState;
var saml2LogoutResponse = new Saml2LogoutResponse(config)
{
InResponseToAsString = logoutRequest.IdAsString,
Status = status,
};
return responsebinding.Bind(saml2LogoutResponse).ToActionResult();
You do not need to call the DeleteSession(HttpContext) but you need to handle logout somehow.

How does SpringBoot get current user from ReactJS?

I trying to understand the codes of Full-stack web-application at https://github.com/callicoder/spring-security-react-ant-design-polls-app
but I do not understand how does spring-boot know which current user is logging in.
this is ReactJS (front-end) code that calls the api.
export function getUserCreatedPolls(username, page, size) {
page = page || 0;
size = size || POLL_LIST_SIZE;
return request({
url: API_BASE_URL + "/users/" + username + "/polls?page=" + page + "&size=" + size,
method: 'GET'
});
}
And, this is spring-boot(back-end) code that receives variables from front-end
#GetMapping("/users/{username}/polls")
public PagedResponse<PollResponse> getPollsCreatedBy(#PathVariable(value = "username") String username,
#CurrentUser UserPrincipal currentUser,
#RequestParam(value = "page", defaultValue = AppConstants.DEFAULT_PAGE_NUMBER) int page,
#RequestParam(value = "size", defaultValue = AppConstants.DEFAULT_PAGE_SIZE) int size) {
return pollService.getPollsCreatedBy(username, currentUser, page, size);
}
how does spring-boot get {UserPrincipal currentUser} from front-end?
how does ReactJs sent {UserPrincipal currentUser} to back-end?
It's a spring boot oauth jwt provider + resource server and ReactJs as the consumer
ReactJs can consume the server resources ( rest api ) by sending and HTTP request, but it should first get an authorization for that (Token)
The server will send JWT token after a success login
then when reacteJs send an HTTP request, it actually inject extra information to the HTTP request which is the authorization token
when the server get this request and before it reach the controller, the request pass throw a chain of filter ( spring security filter chain ) , look at this filter class method in the code link , after a success user authentication calling the SecurityContextHolder class to fill the security context with the current authenticated user ( User Principle ), and finally when the request reach the controller, our security context is filled up
#CurrentUser UserPrincipal currentUser , when you added UserPrincipal currentUser parameter to spring Controller methods, it will fill the object from the context automatically, you can do it by your self by calling the SecurityContextHolder class and get the current authenticated User
...
// Get The Jwt token from the HTTP Request
String jwt = getJwtFromRequest(request);
// Check The validation of JWT - if true the user is trusted
if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
Long userId = tokenProvider.getUserIdFromJWT(jwt);
/*
Note that you could also encode the user's username and roles inside JWT claims
and create the UserDetails object by parsing those claims from the JWT.
That would avoid the following database hit. It's completely up to you.
*/
// Get the user object
UserDetails userDetails = customUserDetailsService.loadUserById(userId);
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// Fill the security context with this user
SecurityContextHolder.getContext().setAuthentication(authentication);
...

RestAssured testing, get user token

What I want to do: I want to test my endpoint using RestAssured. The key is that the endpoint is available only for users who are logged in. For logging in I'm using spring security default endpoint with custom successHandler in which I'm setting some random token, saving it to database and returning in header "User-Token". I'm not creating a session on the back end. When I want to access a secured endpoint, front-end makes a call to it, with "User-Token" header. Then I'm using the token for checking in the database. Each token is different and random. Also I don't use any spring-security things for token. Now I want to test this behavior.
Technologies: React & Redux, Spring Boot, RestAssured, JUnit, Tomcat
What's not working: First of all, I'm not really sure how to obtain the token. I mean I can force it by hand to database to some test user, but AFAIK it's a bad bad practice. I read the documentation and come across part about auth().form. But below it was mentioned that it's not the best approach as have to made to the server in order to retrieve the webpage with the login details and it's not possible - webpage is totally separated from backend. I did try the approach nevertheless but it didn't work.
#Before
public void LogInUser(){
String loginUrl = "http://localhost:8080/login";
userToken =
given().auth().form("username","password").
when().get(loginUrl).getHeader("User-Token");
System.out.println(userToken);
}
So then I thought that maybe I don't need auth() at all - I don't need session, so calling the endpoint itself with data should be enough. I checked how data is passed from front-end to back-end and did this:
Form Data: username=something&password=something
#Before
public void LogInUser(){
String loginUrl = "http://localhost:8080/login";
userToken =
given().parameter("username=oliwka&password=jakies")
.when().get(loginUrl).getHeader("User-Token");
System.out.println(userToken);
}
And while it's passing, userToken is null. It's declared as class variable not method variable and it's String.
How can I obtain token for user and test my endpoint for which I need a token?
You can use below procedure to get the access token.
Step 1 : Create a method that will accept a json string and parse the data and return the access token. below is the method. You can use your preferable json parser library.
public String getAccessToken(String jsonStr) {
JSONParser parser = new JSONParser();
Object obj = null;
try {
obj = parser.parse(jsonStr);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JSONObject jsonObject = (JSONObject) obj;
String accessToken = (String) jsonObject.get("access_token");
System.out.println("access_token : " + accessToken);
return accessToken;
}
Step 2 : Now call your login api with username and password like below
String loginUrl = "http://localhost:8080/login";
Response res = null;
String returnValue = "";
response = given().param("username", "yourUserName")
.param("password", "yourpassword")
.param("client_id", "If Any otherwise skip it")
.param("grant_type", "If Any otherwise skip it")
.param("clear_all", "true")
.post(loginUrl);
returnValue = response.body().asString();
String accessToken = getAccessToken(returnValue);
Please let me know if you can get your desired access token.

ServiceStack user session not found when using sessionId in client Headers or Cookies

I am using ServiceStack v4 with custom Authentication. This is setup and working correctly. I can call the /auth service and get a returned AuthorizationResponse with unique SessionId.
I also have swagger-ui plugin setup. Using it, I can authenticate via /auth and then call one of my other services which require authentication without issue.
Now, from a secondary MVC application using the c# JsonServiceClient I can again successfully make a call to /auth and then secured services using the same client object. However, if I dispose of that client (after saving the unique sessionId to a cookie), then later create a new client, and either add the sessionId as a Cookie or via headers using x-ss-pid as documented, calling a services returns 401. If I call a non-secure service, but then try to access the unique user session, it returns a new session.
If I look at the request headers in that service, the cookie or Header is clearly set with the sessionId. The sessionId also exists in the sessionCache. The problem seems to be that the code which tries to get the session from the request isn't finding it.
To be more specific, it appears that ServiceExtensions.GetSessionId is looking at the HostContext and not the calling Request. I'm not sure why. Perhaps I misunderstand something along the way here.
If I directly try and fetch my expected session with the following code it's found without issue.
var req = base.Request;
var sessionId = req.GetHeader("X-" + SessionFeature.PermanentSessionId);
var sessionKey = SessionFeature.GetSessionKey(sessionId);
var session = (sessionKey != null ? Cache.Get<IAuthSession>(sessionKey) : null)?? SessionFeature.CreateNewSession(req, sessionId);
So, am I missing something obvious here? Or maybe not so obvious in creating my secondary client?
Sample code of client calls
Here is my authorization code. It's contained in a Controller class. This is just the relevant parts.
using (var client = new JsonServiceClient(WebHelper.BuildApiUrl(Request)))
{
try
{
loginResult = client.Post(new Authenticate()
{
UserName = model.Email,
Password = model.Password,
RememberMe = model.RememberMe
});
Response.SetCookie(new HttpCookie(SessionFeature.PermanentSessionId, loginResult.SessionId));
return true;
}
}
Here is my secondary client setup and service call, contained in it's own controller class in another area of the MVC application
using (var client = new JsonServiceClient(WebHelper.BuildApiUrl(Request)))
{
var cCookie = HttpContext.Request.Cookies.Get(SessionFeature.PermanentSessionId);
if (cCookie != null)
{
client.Headers.Add("X-" + SessionFeature.PermanentSessionId, cCookie.Value);
client.Headers.Add("X-" + SessionFeature.SessionOptionsKey, "perm");
}
response = client.Get(new SubscriptionStatusRequest());
}
Additional Update
During the Authenticate process the following function is called from HttpRequestExtensions with the name = SessionFeature.PermanentSessionId
public static class HttpRequestExtensions
{
/// <summary>
/// Gets string value from Items[name] then Cookies[name] if exists.
/// Useful when *first* setting the users response cookie in the request filter.
/// To access the value for this initial request you need to set it in Items[].
/// </summary>
/// <returns>string value or null if it doesn't exist</returns>
public static string GetItemOrCookie(this IRequest httpReq, string name)
{
object value;
if (httpReq.Items.TryGetValue(name, out value)) return value.ToString();
Cookie cookie;
if (httpReq.Cookies.TryGetValue(name, out cookie)) return cookie.Value;
return null;
}
Now what occurs is the httpReq.Items contains a SessionFeature.PermanentSessionId value, but I have no clue why and where this gets set. I don't even understand at this point what the Items container is on the IRequest. The code thus never gets to the functionality to check my cookies or headers
The Session wiki describes the different cookies used by ServiceStack Session.
If the client wants to use a Permanent SessionId (i.e. ss-pid), it also needs to send a ss-opt=perm Cookie to indicate it wants to use the permanent Session. This Cookie is automatically set when authenticating with the RememberMe=true option during Authentication.
There was an issue in the Session RequestFilter that was used to ensure Session Id's were attached to the current request weren't using the public IRequest.GetPermanentSessionId() API's which also looks for SessionIds in the HTTP Headers. This has been resolved with this commit which now lets you make Session requests using HTTP Headers, e.g:
//First Authenticate to setup an Authenticated Session with the Server
var client = new JsonServiceClient(BaseUrl);
var authResponse = client.Send(new Authenticate
{
provider = CredentialsAuthProvider.Name,
UserName = "user",
Password = "p#55word",
RememberMe = true,
});
//Use new Client instance without Session Cookies populated
var clientWithHeaders = new JsonServiceClient(BaseUrl);
clientWithHeaders.Headers["X-ss-pid"] = authResponse.SessionId;
clientWithHeaders.Headers["X-ss-opt"] = "perm";
var response = clientWithHeaders.Send(new AuthOnly()); //success
This fix is available from v4.0.37+ that's now available on MyGet.
However, if I dispose of that client (after saving the unique sessionId to a cookie)
If the client is disposed where is the cookie you are saving the sessionId located? This answer might provide some additional information.
then later create a new client, and either add the sessionId as a Cookie or via headers using x-ss-pid as documented, calling a services returns 401
If you store/save a valid sessionId as a string you should be able to supply it within a CookieContainer of a new client (given the sessionId is still authenticated). I know you said you tried adding the sessionId as a Cookie but I don't a see sample within your question using the CookieContainer so it should look something like...
using (var client = new JsonServiceClient(WebHelper.BuildApiUrl(Request)))
{
var cCookieId = savedCookieId; //a string that I believe you saved from a successfully authenticated client that is now disposed
if (cCookieId != null)
{
var cookie = new Cookie(SessionFeature.PermanentSessionId, cCookieId);
//cookie.Domian = "somedomain.com" //you will probably need to supply this as well
client.CookieContainer.Add(cookie)
}
response = client.Get(new SubscriptionStatusRequest());
}

OAuth 2.0. No session? (stateless)

I'm going to implement OAuth 2.0 and REST API with it
to grant different permissions per users and also to scale well.
To scale well, stateless is easier because there is
NO file, database, in-memory based session with it.
Below is how I understand OAuth 2.
OAuth Server give an access token to a user.
The user's access token is stored in cookie.
When user access to REST API, user sends with the access token.
Server receives request with access token.
Server find out whether access token is valid and the user has permission to do request.
Do or reject based on user's privilege.
So I do not have to worry about session storage. Right?
What you are describing here, is the OAuth 2 Implicit Grant flow. OAuth 2 also includes three other flows, but as it seems that your ressource owner (the user) is initiating requests using browser side Javascript (you were talking about cookies), this is the flow you should go for.
On client side, OAuth only requires you to store the access_token for accessing protected ressources (and a refresh_token if you're going for an expiring access_token).
A more recent innovation is JWT - JSON Web Token.
Here is a link to the spec:
JWT - JSON Web Token
JWT is a method of using Hashed tokens using a Hashing method such as HMAC which stands for a Hash-based Message Authentication Code. Because the token is hashed using a secret key, the server can determine if the token has been tampered with.
Here is an example method to create a Hashed token for JWT:
public String createTokenForUser(User user) {
byte[] userBytes = toJSON(user);
byte[] hash = createHmac(userBytes);
final StringBuilder sb = new StringBuilder(170);
sb.append(toBase64(userBytes));
sb.append(SEPARATOR);
sb.append(toBase64(hash));
return sb.toString();
}
Here is an example of decoding a token to ensure it was not tampered with:
public User parseUserFromToken(String token) {
final String[] parts = token.split(SEPARATOR_SPLITTER);
if (parts.length == 2 && parts[0].length() > 0 && parts[1].length() > 0) {
try {
final byte[] userBytes = fromBase64(parts[0]);
final byte[] hash = fromBase64(parts[1]);
boolean validHash = Arrays.equals(createHmac(userBytes), hash);
if (validHash) {
final User user = fromJSON(userBytes);
if (new Date().getTime() < user.getExpires()) {
return user;
}
}
} catch (IllegalArgumentException e) {
//log tampering attempt here
}
}
return null;
}
Here is an article with a more complete example: Stateless Authentication

Resources