Basic Authentication Required Dialog - java

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;
}

Related

Using the Firebase Admin SDK for Java, how can I authenticate a user with email and password? [duplicate]

I am trying to implement a feature for a user to change their password in their settings page when they are logged in, and I require the user's old password as well as the new password when they try to change it as an extra security measure. My problem is that I cannot find a way to verify if the user's old password is correct. Is there an easy way to do this?
I receive the entered form inputs on the server so the solution would have to be on the backend (node.js)
Many thanks
Though the accepted solution works, there is also a way to verify a user's password from the backend, using the Google Identity Kit REST API's "verifyPassword" endpoint (which has recently been renamed to "signInWithPassword", but works exactly the same):
HTTP POST https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=[YOUR_FIREBASE_API_KEY]
{
email,
password,
}
If that endpoint doesn't return an error, that means the password is valid.
See this thread for more information.
You have to do it client side. This is not an operation that the admin SDK is designed to handle. You will ask the current user for the password and reauthenticate with it and then update password:
const cred = firebase.auth.EmailAuthProvider.credential(
firebase.auth().currentUser.email, oldPass);
firebase.auth().currentUser.reauthenticateWithCredential(cred)
.then(() => {
return firebase.auth().currentUser.updatePassword(newPass);
})
.catch((error) => {
// Some error.
});

Is There an Authentication Token Stored in Active Directory? Single-Sign On and WAFFLE/KERBEROS

I am tasked with creating SSO (single-sign on) for my company's application. I am straight out of college so am still fresh to the majority of the things at play here. I have done tons of research, I don't fully understand all of it but am doing my best.
So the scenario I am in, I have a Windows Java Application(Swing) (NOT A WEB BASED APP), and a LINUX based server. Both have access to the same Active Directory(AD). I need to authenticate who the client is saying they are. I have attempted to use both Kerberos and WAFFLE to no avail. Kerberos has zero useful code examples or information online to even begin to try and use that form of authentication. WAFFLE I have set up but can't use because it requires a Windows server where mine is LINUX. What I am now trying to do is find out if there is some token that is stored in the AD that the server can authenticate against.
What I want to do is send the currently logged in Windows user along with a token to the server and the server to do a look up in the active directory to see if the username and token match. If they do then you are good to log in. Is this possible and does such a thing exist in the AD?
Does a Kerberos token get stored in the AD? If so am I able to access such a token to send to the server to authenticate with? Does an SSPI token get stored there because that is what this WAFFLE code I have working seems to be using but I haven't been able to find how to query such a token in AD.
In the following code WAFFLE does some authentication using SSPI. I don't fully understand how it works but I wanted to see if I could send the token it is using here to the LINUX server to look up in the AD to check if it is valid but it doesn't seem to be something stored in the AD.
Any help is greatly appreciated.
private void negotiate() {
IWindowsSecurityContext clientContext = WindowsSecurityContextImpl.getCurrent( "NTLM", "localhost" );
String securityPackage = "Kerberos";
int count = 0;
// initialize a security context on the client
clientContext = WindowsSecurityContextImpl.getCurrent( securityPackage, clientContext.getPrincipalName() );
// create an auth provider and a security context for the client
// on the server
WindowsAuthProviderImpl provider = new WindowsAuthProviderImpl();
// now you would send the byte[] token to the server and the server will
// response with another byte[] token, which the client needs to answer again
IWindowsSecurityContext serverContext = null;
// Step 1: accept the token on the server and build a security context
// representing the client on the server
byte[] tokenForTheServerOnTheClient = clientContext.getToken();
serverContext = provider.acceptSecurityToken("server-connection", tokenForTheServerOnTheClient, securityPackage);
do {
count++;
// Step 2: If you have already build an initial security context for the client
// on the server, send a token back to the client, which the client needs to
// accept and send back to the server again (a handshake)
if (serverContext != null) {
byte[] tokenForTheClientOnTheServer = serverContext.getToken();
SecBufferDesc continueToken = new SecBufferDesc(Sspi.SECBUFFER_TOKEN, tokenForTheClientOnTheServer);
clientContext.initialize(clientContext.getHandle(), continueToken, clientContext.getPrincipalName());
System.out.println(tokenForTheClientOnTheServer);
}
tokenForTheServerOnTheClient = clientContext.getToken();
serverContext = provider.acceptSecurityToken("server-connection", tokenForTheServerOnTheClient, securityPackage);
} while (clientContext.isContinue() && count < 5);
if(count >= 5) {
System.out.println("Unable to authenticate the user.");
}else {
// at the end of this handshake, we know on the server side who the
// client is, only by exchanging byte[] arrays
System.out.println(serverContext.getIdentity().getFqn());
}
}

error when using requestJWTUserToken, just replace my account info SDK project, junit code

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

How to check given domain name http or https in java?

My problem
In my android application I get url input from user, like "www.google.com".
I want to find out for the given url whether to use http or https.
What I have tried
after referring to some Stack Overflow questions I tried with getScheme()
try {
String url_name="www.google.com";
URI MyUri = new URI(url_name);
String http_or_https="";
http_or_https=MyUri.getScheme();
url_name=http_or_https+"://"+urlname;
Log.d("URLNAME",url_name);
}
catch (Exception e) {
e.printStackTrace();
}
But my above code throws an exception.
My question
Is above approach getScheme() correct or not?
If above approach is incorrect, how to find url http or https?
A domain name is a domain name, it has nothing to do with protocol. The domain is the WHERE, the protocol is the HOW.
The domain is the location you want to go, the protocol is how do you go there, by bus, by plane, by train or by boat. It makes no sense to ask 'I want to go to the store, how do I ask the store if I should go by train or by car?'
The reason this works in browsers is that the browser usually tries to connect using both http and https if no protocol is supplied.
If you know the URL, do this:
public void decideProtocol(URL url) throws IOException {
if ("https".equals(url.getProtocol())) {
// It is https
} else if ("http".equals(url.getProtocol())) {
// It is http
}
}
You can check, the given url is http or https by using URLUtils.
URLUtil.isHttpUrl(String url); returns True if the url is an http.
URLUtil.isHttpsUrl(String url); returns True if the url is an https.
You could use the Apache UrlValidator.
You can specify the allowed url schema and in your case the code look something like this:
String[] schema = {"https"};
UrlValidator urlValidator = new UrlValidator(schemes);
if (urlValidator.isValid("http://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
if (urlValidator.isValid("https://foo.bar.com/")) {
System.out.println("url is valid");
} else {
System.out.println("url is invalid");
}
A hierarchical URI is subject to further parsing according to the syntax
[scheme:][//authority][path][?query][#fragment]
so your url_name lack of scheme.
if url_name is "https://www.google.com", so the scheme is https.
refer: http://docs.oracle.com/javase/7/docs/api/java/net/URI.html
You can't get it from just URL. It doesn't make sense. Some websites can work with both http & https. It depends upon website itself whether they use SSL certificate or not.
As was pointed out, if a user didn't dare to provide full url including protocol type. The app might use kind of trial and error approach, try to establish connection using the list of available protocols. (http, https). The successful hit might be considered as a default. Again, all this about usability,this method is better than just annoying an inattentive user with ugly error message.
ranjith- I will store some sort of mapping between URI (main domain) and preferred protcol within application..can have pre-defined mappings based on what you know and then let that mapping grow as more Uris added..

Getting User details using servlet

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

Categories

Resources