I'm trying to retrieve the username of user who recently logged in. I used .getRemoteUser() method to read the username. But it was not displaying the user infromation.
my code is :
response.setContentType("text/plain");
PrintWriter out= response.getWriter();
// Some introductory HTML...
String remoteUser = request.getRemoteUser();
// See if the client is allowed
if(remoteUser == null) {
out.println("Welcome");
} else {
out.println("Welcome " + remoteUser + "!");
}
I don't know why it was not giving the correct result. It always produces the result "Welcome". Which means request.getRemoteUser()==null. Please anyone tell me how to retrieve the remote user information. Thanks in advance....
request.getRemoteUser() will return the user logged in else it will return null. It depends upon what kind of authentication you are using.
Another reason would be the client (browser) is not sending the user name with the request. That can happen if you are outside the URL tree that asked for the authentication
use HTTP basic authentication only then you will have Remote User populated.
Here is simple tutorial on setting up a basic HTTP authentication in Java
For a fact you can use any one of the below standard authentication mechanism
static String BASIC_AUTH
String identifier for Basic authentication.
static String CLIENT_CERT_AUTH
String identifier for Client Certificate authentication.
static String DIGEST_AUTH
String identifier for Digest authentication.
static String FORM_AUTH
Related
I am running the official SDK Junit codes, and it works fine. But when I change the account info into mine, exception occur.
Debug says it return http status of 400 when posting to endpoint "/oauth/token",
I have save my private key generated in docusign admin page, into "docusign_private_key.txt"
ApiClient apiClient = new ApiClient (BaseUrl);
//String currentDir = System.getProperty("user.dir");
try
{
// IMPORTANT NOTE:
// the first time you ask for a JWT access token, you should grant access by making the following call
// get DocuSign OAuth authorization url:
//String oauthLoginUrl = apiClient.getJWTUri(IntegratorKey, RedirectURI, OAuthBaseUrl);
// open DocuSign OAuth authorization url in the browser, login and grant access
//Desktop.getDesktop().browse(URI.create(oauthLoginUrl));
// END OF NOTE
byte[] privateKeyBytes = null;
try
{
privateKeyBytes = Files.readAllBytes (Paths.get (privateKeyFullPath) );
}
catch (IOException ioExcp)
{
Assert.assertEquals (null, ioExcp);
}
if (privateKeyBytes == null)
{
return;
}
java.util.List<String> scopes = new ArrayList<String>();
scopes.add (OAuth.Scope_SIGNATURE);
scopes.add (OAuth.Scope_IMPERSONATION);
OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken (IntegratorKey, UserId, scopes, privateKeyBytes, 3600);
}
Problem solved.
The SDK JUnit code defines a parameter called "UserId", it should be filled by "API Username" , not "API Account ID" from Admin page.
Thanks for all you kind people.
Per the note in the comments, you need to grant one-time user consent per key for your app to use it, have you done that? If you have Organizations enabled (which is an enterprise feature) then you can do it across the entire account, otherwise you'll need to grant consent manually on a one-by-one (ie user by user) basis.
If granting consent manually (which is what most integrations do) you need to configure your Integrator Key with the Redirect URI you will be passing through code, then redirect your user to the following URL in a web browser (the "-d" part of the URL means this would be for the demo environment):
https://account-d.docusign.com/oauth/auth?
response_type=YOUR_RESPONSE_TYPE
&scope=open_id
&client_id=YOUR_INTEGRATOR_KEY
&state=YOUR_CUSTOM_STATE
&redirect_uri=YOUR_REDIRECT_URI
&admin_consent_scope=YOUR_REQUESTED_SCOPES
If done correctly the user will be taken to the standard DocuSign login page. After successful login they can explicitly grant consent to your app and will then be re-directed back to your app through the Redirect URI param you configured.
Here is a guide that explains how to obtain consent using either method:
https://developers.docusign.com/esign-rest-api/guides/authentication/obtaining-consent
This might be a duplicate, but I haven't found the answer that exactly resolves my problem... Sorry in advance if it's a duplicate.
I have an html form that takes a user name and password, and when I press Run request, it creates a post request to a servlet.
HTML page screenshot here.
The servlet itself doesn't need authentication. Instead, it uses the parameters to run another program in a process, which needs the user and password.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String user = request.getParameter("user")
String password = request.getParameter("password");
String command = "cmd /c someprogram --user=\"" + user + "\" --password=\"" + password + "\"";
RunTime.getRuntime().exec(command);
...
}
But when I run this, the browser will show the http post request with the my password. Is there anyway that I can hide this?
RequestScreenshot
Thanks alot!!!!
To Simply hide from browser address bar, use POST instead of GET.
==========
If you really want to secure your password,then SSL is a must.
POST is not more secure than GET as it’s also send unencrypted.
SSL will cover the whole HTTP communication and encrypt the HTTP data send between the client and server.
Your HTML form element should have an attribute with method = post . (Formatting lacking as I'm on my phone)
Consider below scenerio
A.com/security is the login application.Once the user is authenticated here he needs to be redirected to B.com/myapp application. B.com/myapp does not have any authentication logic,but it has a sessionfilter which checks for security token in the session if its not it will redirect to A.com/security.
I have researched on how to implement this and came to know Single sign on will be the best solution.
Keeping SSO implementation aside,can the below logic work.
Once User is authenticated in A.com/security,the security object(username,roles,token..) will be sent to B.com/myapp via rest api call.now in B.com/myapp we create a session and dump these values and return the sessionId as response. A.com/security uses this sessionId and redirects user to B.com/myapp with jsessionId.Is this approach correct?
Implementation issue - How to redirect user and assign him the session that got created.
Few of my tries below
Not Working
#RequestMapping("home2/{sessionID}")
public void redirect(#PathVariable String sessionID,HttpServletResponse response) throws IOException{
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionID + "; Path=/myapp/; HttpOnly");
response.sendRedirect("http://B.com/myapp/home");
}
Working - But subsequent requests are not connected to this session(redirects back to login),dont know what i am missing here
#RequestMapping("home2/{sessionID}")
public void redirect(#PathVariable String sessionID,HttpServletResponse response) throws IOException{
response.sendRedirect("http://B.com/myapp/home;jsessionid="+sessionID);
}
I am new to REST and am trying to figure out an issue with giving access to users to the REST API data
I have an application where Users have limited rights to what they can see based on their user ID.
I do this through something similar to below:
#Component
public class StudentsResource{
#Path("students")
#GET
#Produces(MediaType.APPLICATION_JSON_VALUE)
public Students getStudents(#Context HttpServletRequest request){
final HttpSession session = request.getSession();
User user = (User) session.getAttribute(RestConstants.USER);
if(user == null){
throw new NotLoggedInException(RestConstants.USER_NOT_LOGGED_IN);
}
Students students = new Students();
return students;
}
}
If I login to the application, and then paste the URL for the REST URL into the browser localhost:8080/api/students I get the JSON response of /students. If I don't login to the application first and instead just navigate to the URL localhost:8080/api/students in the browser, I get the error that I am not authorized because I am not logged into the application. (So that works just as I want)
However, if I build a webpage in the app that uses client code to call the API where pressing a button will run:
String restURL = "http://localhost:8080/localhost:8080/api/students";
final RestTemplate rest = new RestTemplate();
Students response = rest.getForObject(restURL,Students.class);
I then login to the app, and run the above code by pressing the button (instead of just navigating to the URL in the browser), I get an error that I am not logged in, so I do not have permission to see the data.
Upon further investigation, I saw that this is because the session that I am getting in my server side code has null for the logged in user when pressing the button on the client side, but it has the correct user when just navigating to the URL in the browser.
Why is this value null when using the client code if I logged in, but it works by navigating to the URL?
How can I get the correct Session data to get the logged in user when using the Client code/button?
You can achieve client/server communication by token based authentication mechanism, basically what you do is after user login into our system, we generate a random UUid and concatenate it with userid,Encode it with Base64 algorithm and send it back to client as a token,
Then from the next request onward the user need to send the token in the header, form the header we can identify which user is accessing the service.
for more information chekout the below link, it is a good blog for all the details regarding Jax-Rs
https://abhirockzz.wordpress.com/
For starters; Im not so literate in coding.
I am pretty interested in a script on how to trigger/ or throw a Basic/Standard "Authentication Required" Dialog on a specific directory or site and the credentials that would be inputed there by the users, to be checked against another database thats on another website.
i.e. Like those "Check who blocked you on msn" websites that they get your credentials from their website and they check against the Hotmail database or servers and tell you if the credentials are incorrect (try again) or if its correct it redirects you to the specific website that is implemented by the Administrator. (in this situation Hotmail Contact List)
And also when it checks that the credentials are correct how do I make the script to store those credentials into a specific .txt file or folder?!
The only difference is that I just want it to be Basic Authentication Dialog Like This Example Here But I want this to implement on my sites.
I hope Im comprehensible.
Thank you very much in advance.
You will need to send a 401 response code to the browser which will make the browser prompt for a username and password. Here's an example in PHP taken from the PHP manual:
<?php
if (!isset($_SERVER['PHP_AUTH_USER'])) {
header('WWW-Authenticate: Basic realm="My Realm"');
header('HTTP/1.0 401 Unauthorized');
echo 'Text to send if user hits Cancel button';
exit;
} else {
echo "<p>Hello {$_SERVER['PHP_AUTH_USER']}.</p>";
echo "<p>You entered {$_SERVER['PHP_AUTH_PW']} as your password.</p>";
}
?>
You should be able to do the same thing in the language of your choice, although you will need to research where the username and password variables are stored in the language you use.
As an alternative, you may also be able to configure this in your web server. That way the web server handles authentication and you only need to program your application to get the current user name which is usually found in the "REMOTE_USER" environment variable. In Apache you might restrict access to a specific folder as follows:
<Directory /usr/local/apache/htdocs/secret>
AuthType Basic
AuthName "Restricted Files"
# (Following line optional)
AuthBasicProvider file
AuthUserFile /usr/local/apache/passwd/passwords
Require user rbowen
</Directory>
See the Apache documentation on authentication and access control for more information. Even if you are using a different web server, rest assured that this is a common feature in web servers. I'm sure you will be able to find the equivalent functionality in whatever web server you are using.
Java imports have been excluded...
To show the username/password dialog...
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("WWW-Authenticate", "Basic realm=\"My Realm\"");
httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "");
To decode the request...
private boolean authenticateRequestOk(HttpServletRequest request)
{
String authorizationHeader = request.getHeader("Authorization");
if (authorizationHeader != null)
{
byte[] decodedUsernamePassword;
try
{
decodedUsernamePassword = Base64.decode(authorizationHeader.substring("Basic ".length()));
}
catch (IOException e)
{
log.error("Error decoding authorization header \"" + authorizationHeader + "\"", e);
return false;
}
String usernameAndPassword = new String(decodedUsernamePassword);
String username = StringUtils.substringBefore(usernameAndPassword, ":");
String password = StringUtils.substringAfter(usernameAndPassword, ":");
if (USERNAME.equalsIgnoreCase(username) && PASSWORD.equalsIgnoreCase(password))
{
return true;
}
}
return false;
}