Skip to Content
0

X-CSRF-Token logic implementation for Java application

Nov 30, 2017 at 11:51 AM

88

avatar image
Former Member

Hello,

We have developed common utilities functionality in Java application having few RESTful web services and now planning to implement X-CSRF-Token implementation to make it REST webservices more secured.

I found some information at

https://help.sap.com/viewer/65de2977205c403bbc107264b8eccf4b/Cloud/en-US/3756f3fc7b4342d39db1bbe57d1b2d57.html

but some how as per the instruction given in this link is not working.

Could you please provide some Java example to generate csrf token and to consume it from UI5 application ?

Thanks.

10 |10000 characters needed characters left characters exceeded
* Please Login or Register to Answer, Follow or Comment.

2 Answers

Richard Zhao
Dec 01, 2017 at 01:45 AM
0

Hello, Ashutosh.To pass CSRF as a parameter by using Ajax. My solution is base on JQuery. thanks

$(document).ready(function(){
    function getCookie(c_name) {
        if(document.cookie.length > 0) {
            c_start = document.cookie.indexOf(c_name + "=");
            if(c_start != -1) {
                c_start = c_start + c_name.length + 1;
                c_end = document.cookie.indexOf(";", c_start);
                if(c_end == -1) c_end = document.cookie.length;
                return unescape(document.cookie.substring(c_start,c_end));
            }
        }
        return "";
    }

    $(function () {
        $.ajaxSetup({
            headers: {
                "X-CSRFToken": getCookie("csrftoken")
            }
        });
    });
});

it is being fetched from the request header at the server side.

Show 1 Share
10 |10000 characters needed characters left characters exceeded
Former Member

Hello Richard,

Thank you for your quick response.

Could you please provide some Java application example to generate csrf token and to consume it from UI5 application?

Best regards,

Ashutosh Bharambe

0
avatar image
Former Member Dec 01, 2017 at 06:59 AM
0

Hello Richard,

Thank you for your quick response.

Could you please provide some Java example to generate csrf token and to consume it from UI5 application?

Best regards,

Ashutosh Bharambe

Show 1 Share
10 |10000 characters needed characters left characters exceeded

Hello, Ashutosh. I would like to show you a simple example how Java generate a Token. Actually, Tokens are created base on your business requirement.

 import java.security.MessageDigest;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Map.Entry;
 import java.util.concurrent.Executors;
 import java.util.concurrent.ScheduledExecutorService;
 import java.util.concurrent.TimeUnit;
 import org.apache.log4j.Logger;


 public class TokenUtil {
       private static final String YAN = "testMRf1$789787aadfjkds//*-+'[]jfeu;384785*^*&%^%$%";

private static Map<Integer, Token> tokenMap = new HashMap<Integer, Token>();

 	public static void main(String[] args) {
         System.out.println(generateToken( "s",1));
     }


	public static Token generateToken(String uniq,int id) {
          Token token = new Token(MD5(System.currentTimeMillis()+YAN+uniq+id), System.currentTimeMillis());
          synchronized (tokenMap) {
              tokenMap.put(id, token);
          }
          return token;
    }




	public final static String MD5(String s) {
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            return byte2hex(mdInst.digest());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }




    private static String byte2hex(byte[] b) {
        StringBuilder sbDes = new StringBuilder();
        String tmp = null;
        for (int i = 0; i < b.length; i++) {
            tmp = (Integer.toHexString(b[i] & 0xFF));
            if (tmp.length() == 1) {
                sbDes.append("0");
            }
            sbDes.append(tmp);
        }
        return sbDes.toString();
    }
 }
<br>

After the token created, All you have to do is provide restful web service so that the frontend are able to get this token by using Javascript and storage the token in browser localstorage or sessionstorage. thanks.

0