I am working with JWT api , i have generated a token using:
public void addAuthentication(HttpServletResponse response, String name) {
// We generate a token now.
String JWT = Jwts.builder()
.setSubject(name)
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
response.addHeader(headerString, tokenPrefix + " " + JWT);
}
abd secret token prefix being string , however it does generate token, but when i copy it into
https://jwt.io/#debugger
It does undecode it and reveal all informations stored inside it , did i do something wrong or its as it should be? This does not seem secure at all.
Thanks for answers
This is secure at all. Don't worry about it. Just store your key in a secure way.
The remarkable point is decoded information can not be changed or token can not be generated without the key.
Avoid storing essential information in token like credit card number or password etc. I'm sure that you are not using the JWT for this purpose.
If you want to hide the payload, the JWT specification allows use encryption (see Json Web Encryption-JWE at RFC). If auth0 does not support it, you have a lot of libraries listed in jwt.io
Check this topics
Is JWT that secure?
Why are JWT's secure?
It's secure in the sense it tells you who the user is and what claims they have. You can verify that the user's identity and claims are valid by checking the JWTs signature.
Also, see this: https://stackoverflow.com/a/38459231/2115684
If you want to hide the payload, the JWT specification allows use encryption (see Json Web Encryption-JWE at RFC). If auth0 does not support it, you have a lot of libraries listed in jwt.io
Related
As we know Rest services are stateless, General strategies to authenticate is using a token based authentication.
In login service it takes credentials which returns a token.
This token might be set in client cookies, and all subsequent requests uses this token to be validated and process new request if token is valid.
Now my question is how one can validate the token ? If someone has stolen the token and tries to access rest services with stolen token by just editing cookies then how can it be identified and restricted ?
We can never know if the token is fetched by valid user and same user is trying to access subsequent request. but what are the possible ways to make it more hard, like to verify if the request has came from same source ?
One general suggestion is to set aging for token/cookies, but it still not helpful till the age of that token/cookies.
Any suggestions would be appreciated.
I don’t believe there are any 100% fool proof methods of preventing access with stolen user tokens. How do you even know that the token is stolen in the first place? But from the top of my head you might want to consider following:
Accessing a REST service with the same token but a different user agent is suspicious. This can be recognized with the value of the User-Agent header. You might want to consider dropping such requests.
What if the IP address changes but the token is still the same? Well, maybe someone is using a load balancer and accesses the network over different IP addresses? Or he accessed a VPN with the same token/cookie as before? If you have no compunction dropping such requests, you might level up the security by checking the source IP address too.
In case of – say – JWT tokens, you will need a bit of infrastructure to handle the blacklisting. Follow this.
My current understand of the "most secure" approach to authorizing requests in the browser is to require validation of an HttpOnly SameSite cookie AND HTTP header (e.g. Authorization or X-CSRF-Token) in combination.
For example, when issuing the JWT to a browser, send the JWT signature in an HttpOnly SameSite cookie, and send the body (without signature) to the client to store in localStorage and submit in the Authorization header. When authorizing a request, combine the two back into the complete JWT and validate it as normal after that.
Alternatively, you can generate two JWTs with a field to distinguish them (e.g. the client one has "browser" in it, the cookie has "cookie") and require that both are valid and both identify the same user. One is sent in the Authorization header and stored in localStorage and the other uses the SameSite HttpOnly cookie.
Another popular approach is to store a CSRF token in a field in the JWT, and put the JWT into a cookie and require the client to send a matching token in a header (e.g. X-CSRF-Token).
All of the solutions effectively prevent XSS and CSRF attacks: XSS cannot retrieve the HttpOnly cookie, and CSRF does not include the HTTP header, so this blocks both attacks.
Note that you probably only want to apply this rule for requests from web browsers. For server-to-server communication, requests are not subject to CSRF and XSS attacks.
After struggling through various approach We found a solution explained below:
We store token (encrypted) in cookies on login request and for each subsequent request this cookie gets validated.
The problem was if someone replace the token in cookie with another valid token, as cookies are maintained by client browser.
Solution :-> Though token values were encrypted, it was representing only one value, So if one replace whole encrypted value with another valid encrypted value it can be hacked.
So to solve this we have added another cookie which was combination of multiple values.
e.g.
Cookie 1 -> encrypted token
Cookie 2 -> An encrypted object containing information like username+ some other user context details+token
So in case of Cookie 1, it was easy to replace with another encrypted value as it was representing only one token though it was encrypted.
But in case of Cookie 2, it was containing object with multiple values, so only token value can not be modified, encrypted and set back in same cookie.
Before authentication We are doing decryption whole cookie 2, fetch token part from it and validate the token part of it against cookie 1.
That has solved our problem !!
Thanks all for your time and guidance.
You can use jwt is an Internet standard for creating JSON-based access tokens that assert some number of claims. For example, a server could generate a token that has the claim "logged in as admin" and provide that to a client. The client could then use that token to prove that it is logged in as admin .
How it's working ?
First it's contain private key generated by developer :
let us have this key :sfcqw#sav%$#fvcxv*s_s515 and this one called private key , and we also have a public key this the public key generated depended on user data and private key and it's impossible to know what is contain if you don't know the private key .
to more explain :
public key :
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.plpJkAcgrgCIsoRyV2kjGsvWF6OsXU1mD785OSWTH4o
we have the above key generated by our private key : sfcqw#sav%$#fvcxv*s_s515
To be more clear going to this website : https://jwt.io/ and try to past the public key without put secrite key like picture and you will understand everything .
To me, there was no way to prevent the access from being stolen JWT token except
setting a short timeout for the token
more secured at the HTTP request level by only allowing specific `User-Agent. See more
more secured at the HTTP request level by customizing the header key for the organization, e.g My-X-Auth = Bearer <token> instead of Authorization= Bearer <token>
more secured at the HTTP request level by restricting trusted urls/domains, e.g X-Content-Security-Policy. See more
I am currently using Identity Server 4 which is .Net Core based to issue JWT tokens. I have a .Net Core web api that has middleware in order for the JWT to be validated in the Startup.cs:
services.AddAuthentication("Bearer")
.AddJwtBearer("Bearer", options =>
{
options.Authority = "http://localhost:5005";
options.Audience = "api1";
});
As we can see, its not asking for much except the location of the token server and who the api is which is `api1. Obviously, its doing some more complex things under the hood.
I found a Java based equivalent to the middleware above, which validates a JWT:
String token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJhdXRoMCJ9.AbIJTDMFc7yUa5MhvcP03nJPyCPzZtQcGEp-zWfOkEE";
RSAPublicKey publicKey = //Get the key instance
RSAPrivateKey privateKey = //Get the key instance
try {
Algorithm algorithm = Algorithm.RSA256(publicKey, privateKey);
JWTVerifier verifier = JWT.require(algorithm)
.withIssuer("auth0")
.build(); //Reusable verifier instance
DecodedJWT jwt = verifier.verify(token);
} catch (JWTVerificationException exception){
//Invalid signature/claims
}
This is from HERE as was recommended by the jwt.io site.
Basically I want to be able to implement something in Java that is doing the same thing as the .Net Core code above, but its clearly asking for things like a Public and Private key that I have no idea how to provide at this point, as the JWT is coming through the header of the request.
Under the hood, the Microsoft JWT middleware is going to IdentityServer's discovery endpoint and loading in configuration such as the issuer and JWKS (public keys). The discovery document is always hosted on /.well-known/openid-configuration.
To validate the token, you will at least need the public keys from the JWKS. In the past I've loaded it it using the jwks-rsa library: https://www.scottbrady91.com/Kotlin/JSON-Web-Token-Verification-in-Ktor-using-Kotlin-and-Java-JWT
When validating the access token, as a minimum, you'll also need to check the token's audience (is the token intended for you) and if it has expired.
if (jsonresponse == 'SESSION_ALREADY_LOGGED_IN' || jsonresponse == 'USER_ALREADY_LOGGED_IN'){
window.location.replace("${pageContext.request.contextPath}/TrialUser.jsp?rsUsername=" +
getURLParameter("rsUsername") + "&rsPassword" + getURLParameter("rsPassword") + "&rsUse=" +
getURLParameter("rsUse") +"&HOOK_URL=" + getURLParameter("HOOK_URL"));
}
Simple is to Encrypt it and send it in the "Authentication" in the Request header, you can use a simple http base with username/password in Base64, or make it more complicated using Bearer and JWT (JSON Web Token) with a token, hash and at least 256-bit.
If you are considering using MD5 then you should know it was cracked in 1991 and is not secure in over 25 years.
Why are you sending the username and password on get request, it should be on post request always.
In case if you have to do it at least encrypt your password or user details through javascript before sending it
window.location.href = "index.php?Id=" + encrypt(5)+ "&No=" +encrypt( 5);
I strongly recement don't do it
It seems like the overall architecture design should change regarding the log in functionality. Might be a good idea to rethink how you'd like to implement the process.
Also, why sending username/password as GET parameters? GET-requests is also usually logged in various webservers/application servers, which poses a security risk. Uses POST for this whilst performing login sequences.
If GET should be used, look into other solutions regarding identification possibilities.
I am trying to use txtwire (for sending SMS) and they provide a httppost service mentioned below. I know it is "https" but still.. is it OK to pass my API key, userName & Password in the URL?
There is no Basic Auth Mechanism because service expects everything in URL.
https://api.txtwire.com/httppost?phone=18885554433,18885554422&username={username}&password={password}&api_key={api_key}&code=12345&keyword={Group Keyword}&message=testMessage
My only other option is to user their SOAP web service. which is cumbersome and i would prefer RESTful. would SOAP be better if passing credentials in URL is not preferred?
Here is the API : https://api.txtwire.com/documentation/class_w_s___message.html#a99faeee5de80610649b184f180098982
will appreciate any help.
Is it permitted? Well, this is a question that API service provider should answer. It looks like that textWire API doesn't have any issue with it.
For the sake of security, personally, I don't like to post/get credentials without being encrypted. Even with Basic Authorization, there is a way to add encrypted username and password as request header "Authorization". Something similar to the following:
headers['Authorization'] = 'Basic '+ <encoded Base 64 String (username + password)>
Perhaps you want to find out if textWire API support such approach.
You should be ok for both of them, from what I can see they're using an SSL+TLS certificate.
From a more technical point of view, passing the password as part of the query string (RESTful), passing it in the request body (SOAP) or passing it as a request header is actually the same approach (don't forget that basic authentication trasmits the credentials as username:password sequence encoded with base64), because the password itself is being transmitted along with the message itself.
It's a possibile practice, but I would not raccomend it. If I were to expose an authenticated service I would use a username+HMAC signature combination, or maybe an autentication token of some sort.
I'm working on project which is required SSO implementation between WebShpere and PHP web application.
However after i take a look at possible ways to implement SSO i find the LTPA token which is used to implement SSO between different IBM technologies.
but LTPA token 2 is encrypted cookie file. which i should decrypt if i want to use information inside this file such as (userid, username, email ... etc).
i have make deep search about LTPA token 2 and below is the best definition i find from IBM.
LTPA2 signatures are generated using SHA-1 as the hash algorithm, and
RSA (1024-bit key) as the encryption algorithm. After the digital
signature has been attached, the user data and signature are encrypted
with a 3DES or AES key obtained from the LTPA key file (refer to
“Consuming LTPA tokens” and “Generating LTPA tokens”).
But i'm still trying to decrypt this token with no luck.
Any help ?
The Alfresco project did this. Take a look at this blog post for pointers, including working code.
To clarify things, the contents of LTPA tokens are strings that are more or less like "uid=user,cn=users,ou=myorg,dc=com#ldaprealm%timeout%[RSA signature]", encrypted with the shared AES key and encoded with Base64. LTPA v2 will not use 3DES, but only AES. So what you need really to do is to AES decrypt the cookie, and you can already read the username. You don't have to verify the RSA signature.
Why do you need to decrypt it from file? Isn't the token passed along with the calls that you made? When passed, LTPA token is encoded via Base64 and you can easily decode it. Below is an example of how to obtain information from token:
import javax.security.auth.Subject;
import javax.xml.bind.DatatypeConverter;
import com.ibm.websphere.security.cred.WSCredential;
import com.ibm.wsspi.security.token.Token;
Subject subject = ...; // obtain current JAAS subject
Set<?> publicCredentials = subject.getPublicCredentials();
for (Object credential : publicCredentials) {
if (credential instanceof Token) {
System.out.println(DatatypeConverter.printBase64Binary(((Token) credential).getBytes()));
System.out.println(((Token) credential).getName());
System.out.println(((Token) credential).getUniqueID());
System.out.println(((Token) credential).getAttributeNames());
}
}