text
stringlengths 64
2.99M
|
---|
You should put all your code logic inside document.ready, so the entire document will be ready and then only you will get the popup for authentication / authorization. you can get a valid app key here : https://trello.com/app-key See the code example :
<html>
<head>
<title>A Trello Dashboard</title>
<link rel="stylesheet" media="screen" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</head>
<body>
<div class="container">
<h1>Trello Dashboard</h1>
</div>
<div id="loggedin">
<div id="header">
Logged in to as <span id="fullName"></span>
</div>
<div id="output"></div>
</div>
</body>
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="https://api.trello.com/1/client.js?key=[appKeygoeshere]"></script>
<script type="text/javascript">
$(window).load(function(){
Trello.authorize({
type: 'popup',
name: 'A Trello Dashboard',
scope: {
read: 'true',
write: 'true'
},
expiration: 'never',
success: function() { console.log("Successful authentication");
Trello.members.get("me", function(member){
$("#fullName").text(member.fullName);
var $cards = $("<div>")
.text("Loading Cards...")
.appendTo("#output");
// Output a list of all of the cards that the member
// is assigned to
Trello.get("members/senthil192/cards/all", function(cards) {
$cards.empty();
$.each(cards, function(ix, card) {
//alert(card.name);
$("<a>")
.attr({href: card.url, target: "trello"})
.addClass("card")
.text(card.name)
.appendTo($cards);
});
});
});
},
error: function() { console.log("Failed authentication"); }
});
});
</script>
</html>
code ref url : http://jsfiddle.net/danlec/nNesx/ |
I faced the same problem on Windows 10, resolved it with ljsg's suggestion.
In Console with elevated privileges (Run as Admin):
cd %SYSTEMROOT%\System32\Inetsrv\Config
copy *.clean.install *.
ren *.config *.back
ren *.config.clean *.
@powershell -Command "Disable-WindowsOptionalFeature -Online –All -FeatureName @('IIS-ApplicationDevelopment','IIS-ApplicationInit','IIS-ASP','IIS-ASPNET','IIS-ASPNET45','IIS-BasicAuthentication','IIS-CertProvider','IIS-CGI','IIS-ClientCertificateMappingAuthentication','IIS-CommonHttpFeatures','IIS-DefaultDocument','IIS-DigestAuthentication','IIS-DirectoryBrowsing','IIS-FTPServer','IIS-FTPSvc','IIS-HealthAndDiagnostics','IIS-HostableWebCore','IIS-HttpCompressionDynamic','IIS-HttpCompressionStatic','IIS-HttpErrors','IIS-HttpLogging','IIS-HttpRedirect','IIS-HttpTracing','IIS-IIS6ManagementCompatibility','IIS-IISCertificateMappingAuthentication','IIS-IPSecurity','IIS-ISAPIExtensions','IIS-ISAPIFilter','IIS-LegacyScripts','IIS-LegacySnapIn','IIS-LoggingLibraries','IIS-ManagementConsole','IIS-ManagementScriptingTools','IIS-ManagementService','IIS-Metabase','IIS-NetFxExtensibility','IIS-NetFxExtensibility45','IIS-Performance','IIS-RequestFiltering','IIS-RequestMonitor','IIS-Security','IIS-ServerSideIncludes','IIS-StaticContent','IIS-URLAuthorization','IIS-WebDAV','IIS-WebServer','IIS-WebServerManagementTools','IIS-WebServerRole','IIS-WebSockets','IIS-WindowsAuthentication','IIS-WMICompatibility','WCF-HTTP-Activation','WCF-HTTP-Activation45','WCF-NonHTTP-Activation','WCF-Pipe-Activation45','WCF-Services45','WCF-TCP-Activation45','WCF-TCP-PortSharing45','WAS-ConfigurationAPI','WAS-NetFxEnvironment','WAS-ProcessModel','WAS-WindowsActivationService')"
Then reboot, and follow with:
@powershell -Command "Enable-WindowsOptionalFeature -Online –All -FeatureName @('IIS-ApplicationDevelopment','IIS-ApplicationInit','IIS-ASP','IIS-ASPNET','IIS-ASPNET45','IIS-BasicAuthentication','IIS-CertProvider','IIS-CGI','IIS-ClientCertificateMappingAuthentication','IIS-CommonHttpFeatures','IIS-DefaultDocument','IIS-DigestAuthentication','IIS-DirectoryBrowsing','IIS-FTPServer','IIS-FTPSvc','IIS-HealthAndDiagnostics','IIS-HostableWebCore','IIS-HttpCompressionDynamic','IIS-HttpCompressionStatic','IIS-HttpErrors','IIS-HttpLogging','IIS-HttpRedirect','IIS-HttpTracing','IIS-IIS6ManagementCompatibility','IIS-IISCertificateMappingAuthentication','IIS-IPSecurity','IIS-ISAPIExtensions','IIS-ISAPIFilter','IIS-LegacyScripts','IIS-LegacySnapIn','IIS-LoggingLibraries','IIS-ManagementConsole','IIS-ManagementScriptingTools','IIS-ManagementService','IIS-Metabase','IIS-NetFxExtensibility','IIS-NetFxExtensibility45','IIS-Performance','IIS-RequestFiltering','IIS-RequestMonitor','IIS-Security','IIS-ServerSideIncludes','IIS-StaticContent','IIS-URLAuthorization','IIS-WebDAV','IIS-WebServer','IIS-WebServerManagementTools','IIS-WebServerRole','IIS-WebSockets','IIS-WindowsAuthentication','IIS-WMICompatibility','WCF-HTTP-Activation','WCF-HTTP-Activation45','WCF-NonHTTP-Activation','WCF-Pipe-Activation45','WCF-Services45','WCF-TCP-Activation45','WCF-TCP-PortSharing45','WAS-ConfigurationAPI','WAS-NetFxEnvironment','WAS-ProcessModel','WAS-WindowsActivationService')"
..of course features to install should be adjusted as needed. |
UPDATE
Given that you want to get the user's autogenerated ID you can simply import the FirebaseAuth and with a few lines of code have the unique id for each user. There is no need to worry about explicity sending that to the server as data is automatically synchronized. You can simply use the user-id whenever you need it in your code as you build out your JSON tree. If you want to add it to your data then that is also an easy process that you are already using for other data points. Most of what you mention in comments are already functional within the SDK. So there is no need to reinvent those features from scratch.
The code below is used to enable Auth within your activity.
private FirebaseAuth mAuth;
// ...
mAuth = FirebaseAuth.getInstance();
EmailPasswordActivity.java
This simple example from the docs show how to authenticate someone using an email and password...
private FirebaseAuth.AuthStateListener mAuthListener;
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
// ...
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
EmailPasswordActivity.java
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInWithEmail:failed", task.getException());
Toast.makeText(EmailPasswordActivity.this, R.string.auth_failed,
Toast.LENGTH_SHORT).show();
}
// ...
}
});
EmailPasswordActivity.java
This sample code shows how to authenticate users anonymously witho requiring any password.
private FirebaseAuth.AuthStateListener mAuthListener;
// ...
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
// ...
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
AnonymousAuthActivity.java
mAuth.signInAnonymously()
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
Log.d(TAG, "signInAnonymously:onComplete:" + task.isSuccessful());
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
if (!task.isSuccessful()) {
Log.w(TAG, "signInAnonymously", task.getException());
Toast.makeText(AnonymousAuthActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
// ...
}
});
AnonymousAuthActivity.java
(FirebaseAuth Guide)
Enabling offline data synchronization:
(Data offline info)
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
If you want to force a particular branch of the data tree to be stored locally you can also make a referece to that location and call the keepSynced function passing true. The comments in the header indicate:
/**
* By calling keepSynced:YES on a location, the data for that location will automatically be downloaded and
* kept in sync, even when no listeners are attached for that location. Additionally, while a location is kept
* synced, it will not be evicted from the persistent disk cache.
*
* @param keepSynced Pass YES to keep this location synchronized, pass NO to stop synchronization.
*/
ORIGINAL ANSWER
I think you may want to checkout the sample code for Android on the website. Basically, I think the push().getKey() should return the autogenerated id as noted. My take away from this is that the act of posting will generate the key automatically.
private void writeNewPost(String userId, String username, String title, String body) {
// Create new post at /user-posts/$userid/$postid and at
// /posts/$postid simultaneously
String key = mDatabase.child("posts").push().getKey();
Post post = new Post(userId, username, title, body);
Map<String, Object> postValues = post.toMap();
Map<String, Object> childUpdates = new HashMap<>();
childUpdates.put("/posts/" + key, postValues);
childUpdates.put("/user-posts/" + userId + "/" + key, postValues);
mDatabase.updateChildren(childUpdates);
}
|
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Store;
@SuppressWarnings("unused")
public class Read {
public static void check(String host, String storeType, String username,
String password)
{
try {
// create properties field
Properties properties = new Properties();
properties.put("mail.imaps.host", host);
properties.put("mail.imaps.port", "993");
properties.put("mail.imaps.starttls.enable", "true");
// Setup authentication, get session
Session emailSession = Session.getInstance(properties,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
emailSession.setDebug(true);
// create the IMAP store object and connect with the IMAP server
Store store = emailSession.getStore("imaps");
store.connect();
// create the folder object and open it
Folder emailFolder = store.getFolder("INBOX");
emailFolder.open(Folder.READ_ONLY);
// retrieve the messages from the folder in an array and print it
Message[] messages = emailFolder.getMessages();
System.out.println("messages.length---" + messages.length);
for (int i = 0, n = messages.length; i < n; i++) {
Message message = messages[i];
System.out.println("---------------------------------");
System.out.println("Email Number " + (i + 1));
System.out.println("Subject: " + message.getSubject());
System.out.println("From: " + message.getFrom()[0]);
System.out.println("Text: " + message.getContent().toString());
}
// close the store and folder objects
emailFolder.close(false);
store.close();
} catch (NoSuchProviderException e) {
e.printStackTrace();
} catch (MessagingException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String host = "imap.gmail.com";// change accordingly
String mailStoreType = "imap";
String username = "*******@gmail.com";// change accordingly
String password = "********";// change accordingly
check(host, mailStoreType, username, password);
}
}
Here is my code. |
I did template overriding for FosUserBundle in one of my project developed in symfony2.3 version.
Please try below code that may help you
config.yml
twig:
debug: "%kernel.debug%"
strict_variables: "%kernel.debug%"
FrontBundle/Controller/LoginController.php
<?php
namespace Dhi\UserBundle\Controller;
use FOS\UserBundle\Controller\SecurityController as Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\RedirectResponse;
class LoginController extends Controller
{
protected function loginController(array $data)
{
$request = $this->get('request');
return $this->render('FrontBundle:login:login.html.twig');
}
}
FrontBundle/Resources/views/login/login.html.twig
{% extends "DhiUserBundle::layout.html.twig" %}
{% trans_default_domain 'FOSUserBundle' %}
{% block body %}
{% block fos_user_content %}
{% trans_default_domain 'FOSUserBundle' %}
// Your login form code here
{% endblock fos_user_content %}
{% endblock body %}
|
Maybe you should try to catch it in your view directly:
views.py
from rest_framework import viewsets
from customers.models import Customer
from customers.serializers import CustomerSerializer
from api.permissions import IsOwnerOrAdmin
from rest_framework import authentication, permissions, status
from rest_framework.response import Response
class CustomerViewSet(viewsets.ModelViewSet):
serializer_class = CustomerSerializer
queryset = Customer.objects.all()
authentication_classes = (authentication.TokenAuthentication,
authentication.SessionAuthentication,
authentication.SessionAuthentication, )
def get_permissions(self):
if self.action == 'list':
self.permission_classes = (permissions.IsAdminUser,)
elif self.action == 'create':
self.permission_classes = (permissions.AllowAny,)
return super(self.__class__, self).get_permissions()
def create(self, request, *args, **kwargs):
print "This is view create -----------------------------"
serializer = self.get_serializer(data=request.data)
# print serializer
try:
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
except ValidationError as e:
if e.detail.get('username') == ['user with this username already exists.']:
raise Custom409()
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
And removing the logic you put in the serializer create. DRF exceptions are meant to be used in views not serializer. |
Sorry, but what you are asking is not achievable (in terms of your needs).
At first, certificate selection UI dialog MAY or MAY NOT appear only when server requests client certificate for mutual authentication.
Two problems here:
Web browser MAY decide to not pop-up the dialog. This may happen when only one client certificate is installed in the user certificate store. In other words, it is up to browser (or its configuration) to show or not to show the certificate selection dialog.
Even if it shown, it is displayed on client side and is not part of DOM, as the result, you cannot have any interactions with certificate selection dialog from JavaScript.
(1) cannot be solved by server configuration, because it is client behvaiour you have no control over.
(2) can be solved by calling web-enabled client interfaces (similar to ActiveX controls in Internet Explorer), but there must be such support and client must agree to allow such calls. Unfortunately, there is no universal built-in framework that would work even on major browsers and operating systems. The closest is Java, but it is not built-in, client must have installed Java engine. |
I created a hybrid site that utilizes both the ForgeRock session token and the default Spring Security HttpSession. To provide CSRF and session hijack protection, it's very challenging to create a totally session-less application.
So, my app utilizes the Spring session to provide CSRF and session hijack projection and to also act as a cache. The Spring session lasts for 30 seconds, during which time, all requests utilized the stored principal information and don't need to query ForgeRock to validate it. After 30 seconds, the Spring session expires and re-validates the ForgeRock session and acquires updated principal information from OpenAM.
I implemented a few hooks in the Spring Security app to enable this functionality. I utilized Spring Boot, Spring Security, and the Java Configuration way of wiring it all together.
I replaced the AbstractPreAuthenticatedProcessingFilter filter with my own OpenAmCookieAuthentication filter. In the doFilter() method it checks the duration of the HttpSession if it exists. If longer than 'x' seconds, it invalidates the session. This forces future filters to re-validate the OpenAM cookie and get the OpenAM principal info.
I replaced the UsernamePasswordAuthenticationFilter filter with my own filter. To be clear, I didn't implement my own filter here, I just configured an UsernamePasswordAuthenticationFilter instance. I set my own custom success and failure handlers
I created my own success handler that sets the OpenAM session cookie upon successful authentication with OpenAM. It extended SavedRequestAwareAuthenticationSuccessHandler
I created my own failure handler to handled failed logins which clears cookies. It extended ExceptionMappingAuthenticationFailureHandler
Overrode the authenticationManagerBean(). It still utilizes the ProviderManager class, but I pass in my own list of authentication providers
Create a UserDetailsService that implements the AuthenticationUserDetailsService<PreAuthenticatedAuthenticationToken> interface. It is used when there is an OpenAM session token that needs to be validated (after Spring session expires after 30 seconds)
Create authentication provider that implements the AuthenticationProvider interface. This is utilized during the standard login processes to validate the user credentials with OpenAM.
Finally, since I couldn't make the app totally stateless, I implemented simple session replication using the embedded Tomcat instance. This implementation was inspired by this post: enter link description here |
I discarded the idea of accessing Azure Ad from Auth0. I rollbacked to my previous steps where I had options to choose between the duo (Auth0 or Azure AD).
For anyone who is looking out for the answer, well, I tried editing the interceptors. I don't know if I should edit the interceptors but I did a very little and it worked out for me.
So here it goes. I created an angular value and named it loginOption with a property value at the very onset of the module creation. loginOption could hold either Auth 0 or Azure AD as the value.
app.value('loginOption', {value: null});
loginOption.value is populated when a user selects a loginOption.
For Auth 0 I edited the file auth0-angular.js. I injected loginOption in this.$get of authUtilsProvider and conditioned $stateChangeStart
$rootScope.$on('$stateChangeStart', function (e, to) {
if (!config.initialized) {
return;
}
//prevent state change only when the state change is in the favor of Auth0 or login option is yet to be selected
//now, it won't prevent state change when done by Azure AD
if (to.data && to.data.requiresLogin && (!loginOption.value || loginOption.value === 'Auth 0')) {
if (!auth.isAuthenticated && !auth.refreshTokenPromise) {
e.preventDefault();
$injector.get('$state').go(config.loginState);
}
}
});
For Azure AD I edited the file adal-angular.js. I injected loginOption in ProtectedResourceInterceptor and conditioned a few codes.
//to prevent adding token of Azure Ad into header of Auth 0 requests
if (tokenStored && (loginOption.value === loginOptions.AZURE_AD)) {
authService.info('Token is available for this url ' + config.url);
// check endpoint mapping if provided
config.headers.Authorization = 'Bearer ' + tokenStored;
return config;
}
and
if (loginOption.value === loginOptions.AZURE_AD) {
// delayed request to return after iframe completes
var delayedRequest = $q.defer();
authService.acquireToken(resource).then(function (token) {
authService.verbose('Token is available');
config.headers.Authorization = 'Bearer ' + token;
delayedRequest.resolve(config);
}, function (err) {
config.data = err;
delayedRequest.reject(config);
});
return delayedRequest.promise;
}
Nothing has to be done at the back-end. Be sure to add Token Validators for both Auth0 and Azure Ad in Startup.cs
//for Azure Ad
UseWindowsAzureActiveDirectoryBearerAuthentication
//for Auth0
UseJwtBearerAuthentication
And last but not the least, the Claims. For Auth0, email could be retrieved from ClaimTypes.Email and for Azure Ad, email could be retrieved from ClaimTypes.Name.
public static Claim GetClaim(string claimType)
{
return ClaimsPrincipal.Current.FindFirst(claimType);
}
public static string GetLoggedInUserEmail()
{
//Email comes up for Auth0
var claimEmail = GetClaim(ClaimTypes.Email);
//if claimEmail comes out to be null from ClaimTypes.Email then try it out for ClaimTypes.Name
if (claimEmail == null)
//Name comes up for Azure AD
claimEmail = GetClaim(ClaimTypes.Name);
var email = (claimEmail == null ? string.Empty : claimEmail.Value); //gets the email of the user
return email;
}
I am not sure whether this is a solution for my problem but this is what worked for me. Please do correct me if I am wrong at any point while answering. Thanks |
What's the point of allowing a user to connect if they don't have the key to decrypt, and all tables are encrypted? You need to edit your question to describe your use case in more detail.
Controlling access per user is more flexible. Suppose you use encryption, and one day you want to disable access for one particular user. You'd have to change the key, and that means you must re-encrypt all the data with the new key, and then notify all other users of the updated key. That's very inconvenient.
Whereas if you just use their login or their GRANT privileges to control access, you can disable any single user's account and/or use REVOKE to change their privileges. All other users would continue to have the access they did before. That's much easier.
Besides, MySQL has no global "encrypt all tables" option. It doesn't even have an option to encrypt all data inserted into a given table.
MySQL has some encryption functions like AES_ENCRYPT() but it's handled at the level of individual SQL expressions:
INSERT INTO MyTable
SET someColumn = AES_ENCRYPT('Something sensitive', 'thePassword');
You would have to do this every time you insert or update a row.
Then decrypt similarly every time you SELECT:
SELECT AES_DECRYPT(someColumn, 'thePassword') FROM MyTable...
Someone above mentioned MariaDB encryption. This doesn't do what you want. It means the tablespace file on disk is encrypted, but still the MariaDB server automatically decrypts it for anyone who connects to the server. So it's no better than SQL access privileges. It also fails to encrypt query logs or error logs or binary logs. |
Well, in your login.php file, you use :
if(isset($_GET['link']))
{
echo "Invalid Username and Password";
}
to echo the error message, but in your checklogin.php file, you use :
header("Location: login.php");
to redirect if the login fails.
There is no $_GET parameter here, hence your error message will never bbe displayed. Try something like this for the redirect :
header("Location: login.php?link=whatever");
EDIT : Just saw this :
And the url should have request from the specified resource then it will passed back to login page when the authentication fails, it should be like this "../login.php?uname=Mary&pw=mary"
For this to happen, you have to use this redirect :
header("Location: login.php?uname=" . $u . "&pw=" . $p);
And check for these parameters in your login.php :
if(isset($_GET['uname']) && isset($_GET['pw']))
{
echo "Invalid Username and Password";
}
But keep in mind that it's never a good idea to send passwords, even wrong ones, by $_GET. |
As pointed out in the comments 256 keys are quite small and can be factorized easily. First you have to reconstruct the prime numbers used in key generation. Finding the modulus and exponent is an easy one liner with openssl:
$ openssl rsa -in <your-public-key> -pubin -text -modulus
This should output something like
Exponent: <decimal-value> (<hex-value>)
Modulus=<hex-value>
Now you can factorize the modulus with msieve or search for it within the https://factordb.com/ database. This will give you your "p" and "q".
Since the encryption code is not quite RSA you have to write your own decrypt function, which should look like this:
def ext_rsa_decrypt(p, q, e, msg):
m = bytes_to_long(msg)
while True:
n = p * q
try:
phi = (p - 1)*(q - 1)
d = gmpy.invert(e, phi)
privkey = RSA.construct((long(n), long(e), long(d)))
key = PKCS1_v1_5.new(privkey)
enc = key.decrypt(msg, "a")
return enc
except Exception, ex:
traceback.print_exc()
p = gmpy.next_prime(p**2 + q**2)
q = gmpy.next_prime(2*p*q)
e = gmpy.next_prime(e**2)
Now you should have everything you need to decrypt the message, just don't forget to base64 decode the encrypted message before passing it to the decrypt function. |
I made a mistake in my code. That is Token.create(tokenParams); should be handled with in AysncTask. Because it deals with network. After gone through their git repository I came to know. So, I handled that create token part in async task. The code I have changed is below:
int SDK_INT = android.os.Build.VERSION.SDK_INT;
final String[] tokens = {"new"};
Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
final Map<String, Object> tokenParams = new HashMap<String, Object>();
Map<String, Object> bank_accountParams = new HashMap<String, Object>();
bank_accountParams.put("country", "US");
bank_accountParams.put("currency", "usd");
bank_accountParams.put("account_holder_name", "Jayden Moore");
bank_accountParams.put("account_holder_type", "individual");
bank_accountParams.put("routing_number", "110000000");
bank_accountParams.put("account_number", "000123456789");
tokenParams.put("bank_account", bank_accountParams);
final Token[] responseToken = {null};
if (SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
//your codes here
com.stripe.Stripe.apiKey = "sk_test_0wgmvQOVjIpspIgKsoW7wtTp";
new AsyncTask<Void, Void, Token>() {
String errorMsg = null;
@Override
protected Token doInBackground(Void... params) {
try {
return Token.create(tokenParams);
} catch (AuthenticationException e) {
e.printStackTrace();
return null;
} catch (InvalidRequestException e) {
e.printStackTrace();
return null;
} catch (APIConnectionException e) {
e.printStackTrace();
return null;
} catch (CardException e) {
e.printStackTrace();
return null;
} catch (APIException e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(Token result) {
if (errorMsg == null) {
// success
} else {
// handleError(errorMsg);
}
}
}.execute();
}
|
I don't think you really want a function with variable arguments, like printf. The solution below just expects the arguments you use in the end. Note that I do not use a user-supplied format string; that is considered a security risk. I also used snprintf (instead of the simple sprintf) in order to protect against error messages which are longer than the array size in the struct. The array size is a define so that it can be changed easily.
Specific fixes:
Proper declaration order (define the struct type before it's used)
Define an actual error packet object (and not just an uninitialized pointer to one)
Provide actual memory in the error packet for the message
Provide a print function for error packets
Do not let the user code specify printf formats; print user supplied strings with a length protected %s format specifier.
Do not use a variable argument function (whose excess arguments were not evaluated anyway); just declare the needed arguments explicitly.
.
#include<stdio.h>
int errCode = 0xA0B0C0D0;
#define MAX_ERRDESC_LEN 80 // avoid literals
typedef struct{
int err;
char errDesc[MAX_ERRDESC_LEN]; // provide actual space for the message
}errpacket;
void printErrPack(FILE *f, errpacket *ep){
fprintf(f, "Error packet:\n");
fprintf(f, " err = 0x%x:\n", ep->err);
fprintf(f, " desc = ->%s<-\n", ep->errDesc);
}
// Standard function with fixed argument count and types
void function(errpacket* ptr, int errNo, char* errString, int errCodeArg){
ptr->err = errNo;
// snprintf "prints" into a string
snprintf( ptr->errDesc, // print destination
MAX_ERRDESC_LEN, // max length, no buffer overflow
"%s with error code %x", // do not use user string as format
errString, // user supplied string, printed via %s
errCodeArg );
}
int main(){
errpacket a; // define an actual object, not a pointer
// pass the address of the object a
function(&a, 0xdead, "Error detected ", errCode);
printErrPack(stdout, &a);
return 0;
}
|
Sorry this is old but I just spotted it while searching something else. In case you have not solved it, the answer is yes. I use my Rpi with Alexa this way. If you are publishing a skill you need to use proper security measures that include account linking, Oauth2 etc. and there are limits on the types of commands you can accept without a user PIN. However, if you are willing to assume the risk on a skill for your own use in developer mode, you can put http calls, with or without basic authentication, directly into your skill code as though it were any other public ip address. As long as your pi is addressable from outside via http, you can command it. I use my pi with a web server to control a media center. I was sending Alexa commands to that via smart things, but now also have developed a custom skill to go straight fro Alexa tot he Pi and to link commands together. I can say "Alexa, start listening..." and then send multiple menu commands via voice that are recognized by the Pi and executed (e.g. menu, guide, page down, channel name, select, etc...) until I exit or it times out due to no input. I don't have to repeat "Alexa" or "turn on/off" as though each command were a device as is the case when going through smart things. I would only recommend this if your htpc and pi have no secure data and are firewalled from the rest of your network. |
The problem was that above code didn't solve problem, login by HTTP GET didn't work anyway.
There is steps for solve:
Add new class extends UsernamePasswordAuthenticationFilter
package net.company.rest.config.web;
@Slf4j
public class AuthByGetFilter extends UsernamePasswordAuthenticationFilter {
public AuthByGetFilter() {
super();
// change auth parameters
setUsernameParameter("user");
setPasswordParameter("pass");
// allow GET
setPostOnly(false);
setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/login", "GET"));
}
@Override
protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException, ServletException {
SecurityContextHolder.clearContext();
log.debug("Method: {}, Request: {}, params was hidden for security", request.getMethod(), request.getRequestURL());
log.debug("Authentication request failed: {}", failed.toString());
log.debug("Updated SecurityContextHolder to contain null Authentication");
log.debug("Delegating to authentication failure handler " + getFailureHandler());
getRememberMeServices().loginFail(request, response);
getFailureHandler().onAuthenticationFailure(request, response, failed);
}
}
Use this class as filter in the above described SecurityConfig class
...
// configure security
@Override
protected void configure(HttpSecurity http) throws Exception {
http.addFilterBefore(authByGetFilter(), UsernamePasswordAuthenticationFilter.class); // add authByGetFilter
...
}
// allow authentication by http GET method
@Bean
public AuthByGetFilter authByGetFilter() throws Exception {
AuthByGetFilter authByGetFilter = new AuthByGetFilter();
authByGetFilter.setAuthenticationManager(authenticationManagerBean());
authByGetFilter.setAuthenticationFailureHandler(authFailureHandler);
authByGetFilter.setAuthenticationSuccessHandler(authSuccessHandler);
return authByGetFilter;
}
...
|
If you were to condider SQL Server instead of mysql, then the most secure design I can think of that meets your requirements is to require SQL Server Enterprise Edition an Extensible Key Management system that uses a Hardware Security Module. SQL Server Extensible Key Management enables the encryption keys that protect the database files to be stored in an off-box device such as a smartcard, USB device, or EKM/HSM module. EKMs are only supported in Enterprise edition. An HSM will allow for the delegation and isolation of managing the encryption keys and functions under a group other than both developers and DBAs, if that is your intent. Other features I would suggest in the design include the following options to complete end to end transport\session encryption:
Installing a domain or CA certificate on the SQL Server and enabling Force Protocol Encryption or enabling IPSec on the host of the instance
Installing a domain or CA certificate on all IIS websites or web services and forcing encryption in the connection strings and https
The benefits of this design over SQL Server Always Encrypted are that the encryption is protected by a single system that can be monitored and defended with more focus as opposed to numerous clients that increase exposure to theft of the private key from one of the users key stores. Also, key rotation for EKMs should be easy for those who are managing the system. It is also possible with an EKM to require that more than one person be involved in generating keys. |
The problem was in the ajax function itself. So, I tried to get the cookie and rewrite it to the browser. But, I could not do that using the Set-Cookie header as indicated here .
xhr.getResponseHeader('Set-Cookie');
So, I modified the API under branch site to return the cookie data in the respone body as json, instead of having it in the response header.
The API:
[HttpPost]
public HttpResponseMessage Get(string name, string pass)
{
var resp = new HttpResponseMessage();
if (name == "h" && pass == "1") //dummy data
{
// Create the authentication ticket with custom user data.
var serializer = new JavaScriptSerializer();
Models.User u = new Models.User() { Id = 1, Name = "Test", Username = "h", Age = 31 };
string userData = serializer.Serialize(u);
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
name,
DateTime.Now,
DateTime.Now.AddDays(2),
true,
userData,
FormsAuthentication.FormsCookiePath);
// Encrypt the ticket.
string encTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new MyCustomCookie()
{
Name = FormsAuthentication.FormsCookieName,
Value = encTicket,
Days = "2"
};
return Request.CreateResponse(HttpStatusCode.OK, cookie);
}
return Request.CreateResponse(HttpStatusCode.Unauthorized);
}
This is the Response body from the API:
{"Name":".MyAuthCookie","Value":"953020CCD5739418E2D3FB42AB00072..", "Days": 1}
Then in the AJAX call in the Main Site: I get the json data and create a cookie using javascript:
$(document).ready(function () {
authUser();
});
function authUser() {
$.ajax({
url: 'http://localhost:50725/api/auth?name=h&pass=1',
type: 'POST',
success: function (data, status, xhr) {
// you need to also check the status to avoid creating a
//useless cookie if the user was not authorized
createCookie(data.Name, data.Value, data.Days);
frmCompas.src = "http://localhost:50725/Default.aspx"
},
error: function () {
console.log('Error in Operation');
}
});
}
function createCookie(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else
var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
|
Basically, you have three options:
1. Create a custom authentication provider
If you want to really listen to the firewall, you need to create a custom authentication provider, which is rather a challenging task.
You can follow this guide in the documentation: http://symfony.com/doc/current/security/custom_authentication_provider.html
or http://sirprize.me/scribble/under-the-hood-of-symfony-security/
The point here is to create your own firewall listener, which decides whether or not to authenticate the user. A firewall can have multiple listeners.
2. Listen to every request
Alternatively, you can listen to the kernel.request event, possibly manually checking if you are on the secured path, and if so, authenticate the user manually by a helper method. Example:
namespace AppBundle\Subscriber;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
class RequestSubscriber implements EventSubscriberInterface
{
private $tokenStorage;
private $eventDispatcher;
public function __construct(TokenStorageInterface $tokenStorage, EventDispatcherInterface $eventDispatcher)
{
$this->tokenStorage = $tokenStorage;
$this->eventDispatcher = $eventDispatcher;
}
public static function getSubscribedEvents()
{
return [ KernelEvents::REQUEST => 'onRequest' ];
}
public function onRequest(GetResponseEvent $event)
{
// only master requests and not authenticated users
if (!$event->isMasterRequest() || $this->isUserLoggedIn()) {
return;
}
// add your own logic for creating or loading a User object
// and filtering secured routes
/* ... */
// wohoo, user is going to be logged in manually!
$this->authenticate($user, $event->getRequest(), 'secured_area');
}
protected function authenticate(UserInterface $user, Request $request, String $provider) : Bool
{
// password doesn't matter in this case
$token = new UsernamePasswordToken($user, null, $provider, $user->getRoles());
// actual authenticating
$this->tokenStorage->setToken($token);
// dispatch the authentication event, so event listeners can do stuff
$loggedUser = $token->getUser();
if ($loggedUser instanceof UserInterface && $loggedUser->isAccountNonLocked() &&
$loggedUser->isEnabled()) {
$this->eventDispatcher
->dispatch(
SecurityEvents::INTERACTIVE_LOGIN,
new InteractiveLoginEvent($request, $token)
);
return true;
}
return false;
}
protected function isUserLoggedIn()
{
$token = $this->tokenStorage->getToken();
if (!$token) {
return false;
}
return ($token->getUser() instanceof UserInterface);
}
}
And don't forget to add it to the app/config/services.yml:
app.request_subscriber:
class: AppBundle\Subscriber\RequestSubscriber
tags:
- { name: kernel.event_subscriber }
arguments: ['@security.token_storage', '@event_dispatcher']
3. Turn off the authorization
(Probably not a solution for you, since you want to authenticate, not authorize users, but I still mention it for others.)
In app/config/security.yml, change the access control settings so that everyone can access the secured area:
# ...
access_control:
- { path: ^/secured-area$, role: IS_AUTHENTICATED_ANONYMOUSLY }
|
Apparently the files other than .cs as not packaged, and needed to be added manually to the publish folder.
I've the below example for sending html file as attached email:
and the files structures are:
project.json
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"runtimes": {
"win10-x64": {},
"win10-x86": {}
},
"dependencies": {
"NETStandard.Library": "1.6.0",
"Microsoft.NETCore.Runtime.CoreCLR": "1.0.2",
"Microsoft.NETCore.DotNetHostPolicy": "1.0.1",
"MailKit" : "1.10.0"
},
"frameworks": {
"netstandard1.6": { }
}
}
program.cs
using System;
using System.IO; // for File.ReadAllText
using MailKit.Net.Smtp; // for SmtpClient
using MimeKit; // for MimeMessage, MailboxAddress and MailboxAddress
using MailKit; // for ProtocolLogger
namespace sendHTMLemail
{
public class newsLetter
{
public static void Main()
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress("INFO", "[email protected]"));
message.To.Add(new MailboxAddress("MYSELF", "[email protected]"));
message.Subject = "Test Email";
var bodyBuilder = new BodyBuilder();
string htmlFilePath = "./html-files/msg.html";
bodyBuilder.Attachments.Add("./html-files/msg.html");
bodyBuilder.HtmlBody = File.ReadAllText(htmlFilePath);
message.Body = bodyBuilder.ToMessageBody();
using (var client = new SmtpClient (new ProtocolLogger ("smtp.log")))
{
client.Connect("smtp.office365.com", 587);
try{
client.Authenticate("[email protected]", "inof@PSWD");
}
catch{
Console.WriteLine("Authentication Faild");
}
try
{
client.Send(message);
}
catch (Exception)
{
Console.WriteLine("ERROR");
}
client.Disconnect(true);
}
}
}
}
The above worked very fine, and the publish had been prepared running the below commands:
dotnet restore
dotnet build -r win10-x64
dotnet build -r win10-x86
dotnet publish -c release -r win10-x64
dotnet publish -c release -r win10-x86
but while executing the .exe file in the publish folder, it gave an error that the file pathTo/html-files/msg.html is not found.
Once I copied the folder required to the publish folder as below, everything worked fine:
NOTE
If you do not need the public/static file to be seen by the user, then you can compress them, then read them from memory stream, as explained here |
Try this, it's worked for me!
api.py
class UserResource(ModelResource):
raw_password = fields.CharField(attribute=None, readonly=True, null=True, blank=True)
class Meta:
queryset = User.objects.all()
allowed_methods = ['get', 'post' ]
resource_name = 'user'
authentication = Authentication()
authorization = Authorization()
serializer = Serializer(formats=['json'])
def prepend_urls(self):
return [
url(r"^(?P<resource_name>%s)/login%s$" %
(self._meta.resource_name, trailing_slash()),
self.wrap_view("login"), name="api_login"),
url(r'^(?P<resource_name>%s)/logout%s$' %
(self._meta.resource_name, trailing_slash()),
self.wrap_view("logout"), name="api_logout"),
]
def login(self, request, **kwargs):
self.method_check(request, allowed=['post'])
data = self.deserialize(request, request.body, format=request.META.get('CONTENT_TYPE', 'application/json'))
username = data.get('username', '')
password = data.get('password', '')
user = authenticate(username=username, password=password)
print user
if user:
if user.is_active:
login(request, user)
return self.create_response(request, {
'success': True
})
else:
return self.create_response(request, {
'success': False,
'reason': 'disabled',
}, HttpUnauthorized)
else:
return self.create_response(request, {
'success': False,
'reason': 'incorrect',
}, HttpUnauthorized)
def logout(self, request, **kwargs):
"""
Attempt to log a user out, and return success status.
"""
self.method_check(request, allowed=['get'])
# Run tastypie's BasicAuthentication
self.is_authenticated(request)
if request.user and request.user.is_authenticated():
logout(request)
return self.create_response(request, { 'success': True })
else:
return self.create_response(request, { 'success': False, 'error_message': 'You are not authenticated, %s' % request.user.is_authenticated() })
request.py
import json
import requests
data = {"username" : "test", "password" : "password"}
headers = {"content-type": "application/json"}
url = "http://localhost:8000/api/v1/user/login/"
response = requests.post(url, data=json.dumps(data), headers=headers)
print response
In terminal
In [2]: import requests
In [3]: import json
In [4]: data = {"username" : "test", "password" : "password"}
In [5]: headers = {"content-type": "application/json"}
In [6]: url= "http://localhost:8000/api/v1/user/login/"
In [7]: response = requests.post(url, data=json.dumps(data), headers=headers)
In [8]: response
Out[8]: <Response [200]>
|
For just ordinary usage by one user, SMTP will work fine except API has the advantage on server-side for the sysadmin for security.
Differences are theoretical for web service, web application development. Both are ways to give access or to interact with their server. Nowadays REST is used for integrating their service for custom software development, their one part will have F/OSS implementation like OAuth. With REST API we get some extra advantages but that is for integrating for professional grade software development. SMTP relay is less secure.
Take as 2 servers with two technologies. That "Google Apps Service Account" one modern web application supporting Representational State Transfer(REST) API to give access to resource, interact with the server. SMTP one is older web software using Simple Object Access Protocol (SOAP). You can search with SOAP vs REST to understand the basics.
Google SMTP Server is traditional SMTP traditional SMTP relay service. Advantages are -- easy to setup by the users, lesser documentation to help the users to use etc. Disadvantage are they are less secure, plus all inherited disadvantages of SOAP.
"Google Apps Service Account" is modern web application developed in service oriented architecture providing RESTful API for server to server communication over TCP/IP. Advantages are easy to integrate with custom software using open source authentication library (they use OAuth), REST provide more control on sending request, username-password for communication can be avoided, extensive examples of usage, more secure, granular control to operation on server, JSON response has common meaningful format etc. Disadvantages are related to common disadvantages of SOA, Web Hook, RESTful API, difficult to use by a new user etc.
In real, it is basically one web software supporting both ways. One always should use DKIM, SPF etc as anti-spoofing measures. |
If with every REST request also comes user credentials again, does this mean that, for any need of authorization after login, I need to check the credentials again from the database?
You have to authenticate user on each request, but whether authentication uses database or not depends on implementation. By the way, you also have to then authorize the request for the authenticated user.
Do I keep some secret key related to the user in the server, and then check this etc.? But, does not this mean keeping a session?
You can have some secret key known only to the user as an alternative to username-password pair and use this secret key for authentication.
The presence of a secret key doesn't mean keeping a session, because it is not necessarily change on a per session basis.
In my project, I authenticate (login) the user, checking his credentials from database server.
Login is not authentication, it's usually a request for a secret key / session key done using username-password pair for authentication
|
After following Lou's advice, I needed two more changes to get it to work.
I got rid of COUNTER and used partyVInfoByes
I changed encryptionKeyBytes to be an array of 32 instead of 16 bytes, since it's 256 bit ECC (32 * 8 = 256)
RestoreSymmetricKey now looks like this:
protected byte[] RestoreSymmertricKey(byte[] sharedSecretBytes)
{
byte[] merchantIdentifier = ExtractMIdentifier();
ConcatenationKdfGenerator generator = new ConcatenationKdfGenerator(new Sha256Digest());
byte[] algorithmIdBytes = Encoding.UTF8.GetBytes((char)0x0d + "id-aes256-GCM");
byte[] partyUInfoBytes = Encoding.UTF8.GetBytes("Apple");
byte[] partyVInfoBytes = merchantIdentifier;
byte[] otherInfoBytes = Combine(Combine(algorithmIdBytes, partyUInfoBytes), partyVInfoBytes);
generator.Init(new KdfParameters(sharedSecretBytes, otherInfoBytes));
byte[] encryptionKeyBytes = new byte[32];
generator.GenerateBytes(encryptionKeyBytes, 0, encryptionKeyBytes.Length);
return encryptionKeyBytes;
}
|
You are correct, the session is required. From the documentation:
The client creates a new session for the user, via the JIRA REST API.
JIRA returns a session object, which has information about the session including the session cookie. The client stores this session object.
The client can now set the cookie in the header for all subsequent requests to the JIRA REST API.
In other words, the session is integral to the request, receipt and use of the cookie-based authentication token.
Also, the atlassian.xsrf.token would have been injected by atlassian to prevent cross-site forgery and hijacking of the session/cookie.
The way I see it, here are your simple-but-secure options:
For every invocation of your script, use the session to request-receive-retain the cookie (and then, once all API calls are complete, let everything get discarded)
Base64 encode your username and password, store it in a separate file (encrypted if you so choose), and have your script collect (and decrypt) it then place it in an authorization header. See Hiding a password in a python script (insecure obfuscation only).
|
This approach isn't working because you're trying to build the page server-side, then expect input client-side, then do some more server-side work to build the page. However (and I'm not an expert on this myself, so I would appreciate corrections), once you build the page server-side, and send it to the client, you need some form of JavaScript on the client to get any more information from the server (AJAX is a common way).
If you're okay with the submit button taking the user to a different page to see the results, you don't need the Javascript. I would structure what you're trying to do like this (keep in mind that I can't test this right now, so you'll have to debug it):
In file form.html:
<!-- TODO: put the rest of the HTML here -->
<form method="post" action="get_results.py">
<fieldset>
<legend>Personal information:</legend>
Last name:
<input type="text" name="lastname" value="lastname"><br>
First name:
<input type="text" name="firstname" value="firstname"><br>
MidtermGrade:
<input type="text" name="midtermgrade" value="midtermgrade"><br>
FinalGrade:
<input type="text" name="finalgrade" value="finalgrade"><br>
FirstHW:
<input type="text" name="firsthw" value="firsthw"><br>
SecondHW:
<input type="text" name="secondhw" value="secondhw"><br>
ThirdHW:
<input type="text" name="thirdhw" value="thirdhw"><br>
<br><br>
<input type="submit" value="Submit">
</fieldset>
</form>
Note that I filled in the action and method attributes in the form . This is pure HTML. When the form gets submitted, the user will be redirected to get_results.py, which will have to read the POST information attached to the page request by the form.
Something like:
In file get_results.html:
import cgi
import cgitb
import pymysql
cgitb.enable()
# This *should* get the fields from the previous form.
# I can't test it now though...
form = cgi.FieldStorage()
# this part is almost straight from https://github.com/PyMySQL/PyMySQL
import pymysql.cursors
# Connect to the database
connection = pymysql.connect(host='localhost',
user='user',
password='passwd',
db='db',
charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
with connection.cursor() as cursor:
student_sql = 'INSERT INTO `students` (lastname, firstname) VALUES (%s, %s)'
cursor.execute(student_sql,(form['lastname'], form['firstname']) )
# replacing some filed names with '...'. Fill them in
grade_sql = 'INSERT INTO `grades` (midtermgrade, finalgrade, ...) VALUES (%d, %d, %d, %d)'
cursor.execute(grade_sql, form['midtermgrade'], form['finalgrade'], ...)
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT * FROM students"
cursor.execute(sql))
for result in cursor.fetchall():
print(result, '<br>')
finally:
connection.close()
That's probably the simplest way to do it. However, and this is important to know, this approach WILL NOT scale to larger projects.
For starters, you'll want:
a templating languages, so you can separate your raw HTML and code inserted into it
URL manipulation (so something like mysite.com//grades will take users straight to their grades)
User authentication (don't want students looking at other students grades do we?)
an ORM instead of dealing with your database directly (I don't place as much stock in this, but some people swear by it)
If you're trying to make something much larger than this, look into a framework like Flask or Django for Python, or any number of other solutions for other languages. |
Here is my working example on 2.4.10 and Swift 3.
An IdentityProviderManager:
class DigitsIdentityProviderManager:NSObject, AWSIdentityProviderManager {
public func logins() -> AWSTask<NSDictionary> {
let completion = AWSTaskCompletionSource<NSDictionary>()
if let configuration = DGTAuthenticationConfiguration(accountFields: .defaultOptionMask) {
configuration.appearance = DGTAppearance()
configuration.appearance.backgroundColor = UIColor.white
configuration.appearance.accentColor = UIColor.tintColor()
Digits.sharedInstance().authenticate(with: nil, configuration:configuration) {(session, error) in
if session != nil {
let value = session!.authToken + ";" + session!.authTokenSecret
print("digits: \(value)")
completion.setResult(["www.digits.com" : value as NSString])
} else {
completion.setError(error!)
}
}
}
return completion.task
}
}
Invoke with
func handleDigitLogin() {
let digitsIdentityProviderManager = DigitsIdentityProviderManager()
let credentialsProvider = AWSCognitoCredentialsProvider(regionType:.usEast1,
identityPoolId:Constants.Aws.CognitoPoolId,
identityProviderManager:digitsIdentityProviderManager)
let serviceConfiguration = AWSServiceConfiguration(region: .usEast1, credentialsProvider: credentialsProvider)
AWSServiceManager.default().defaultServiceConfiguration = serviceConfiguration
credentialsProvider.clearKeychain()
credentialsProvider.clearCredentials()
let task = credentialsProvider.getIdentityId()
task.continue(successBlock: { (task:AWSTask) -> Any? in
if (task.error != nil ) {
print("\(task.error)")
} else {
print("Task result: \(task.result)")
}
return nil
})
}
|
You could add a custom handler for AccessDeniedException. There are more ways to do this. One way: create a global handler for all controllers by annotating a class with @ControllerAdvice and adding exception handling methods.
@ExceptionHandler(AccessDeniedException.class)
public void handleAccessDenied() {
if (SecurityContextHolder.getContext().getAuthentication() != null &&
SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
//when Anonymous Authentication is enabled
!(SecurityContextHolder.getContext().getAuthentication()
instanceof AnonymousAuthenticationToken) ) {
// do nothing
} else {
throw new MyCustomException();
}
}
@ExceptionHandler(MyCustomException.class)
public String handleAccessDeniedForNotLoggedInUser() {
return "redirect:/login";
}
Also I believe it would be more readable to use ACL expressions in SpEL.
You can annotate controller methods with expressions like @PreAuthorize("hasPermission(#event, 'WRITE')") if you set up ACL by Spring guidelines and I believe Spring would then eat those exceptions silently and no redirecting would occur. |
I got the solution from the below link, all I need to do is to replace the "POST" with "PUT" and the url should be look like 'http://urladdress/myamailId' and the values in array format
Send Put request
The thing I need to do is add the below method in my code
private static JSONObject put(String sUrl, String body) {
Log.d("post", sUrl);
Log.d("post-body", sanitizeJSONBody(body));
HttpURLConnection connection = null;
String authentication = "example" + ":" + "exam123ple";
String encodedAuthentication = Base64
.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
try {
URL url = new URL(sUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("PUT");
connection.setRequestProperty("Content-Type", "application/json");
connection.setRequestProperty("Accept", "application/json");
connection.setRequestProperty("Authorization",
"Basic " + encodedAuthentication);
connection.setRequestProperty("Accept-Charset", "utf-8,*");
OutputStreamWriter streamWriter = new OutputStreamWriter(
connection.getOutputStream());
streamWriter.write(body);
streamWriter.flush();
StringBuilder stringBuilder = new StringBuilder();
if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStreamReader streamReader = new InputStreamReader(
connection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(
streamReader);
String response = null;
while ((response = bufferedReader.readLine()) != null) {
stringBuilder.append(response + "\n");
}
bufferedReader.close();
Log.d("Post-Response",
sanitizeJSONBody(stringBuilder.toString()));
return new JSONObject(stringBuilder.toString());
} else {
Log.d("Post-Error", connection.getResponseMessage());
return null;
}
} catch (Exception exception) {
Log.e("Post-Exception", exception.toString());
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
and my calling method should look like
public static JSONObject registerTask(Context ctx, String sUrl,
String firstName, String lastName, string username) throws JSONException, IOException {
JSONObject request = new JSONObject();
request.putOpt("firstName", firstName);
request.putOpt("lastName", ((lastName == null) ? "" : lastName));
sUrl = sUrl + "registration/"+username;
return put(sUrl, request.toString());
}
|
I suspect you are asking the wrong question because the answer to "how can I return the database back to the point where is has no keys?" is to drop all of the keys. You also said you don't care about the encrypted data since it is test data. However, if your goal is to migrate the encryption from your system to the production system and it is working on your system, then you need to back up the Database Master Key to a file and restore it to the production database. The fact that you did not retain the original password used to encrypt the key in SQL Server is irrelevant because when the DMK was created, the system also encrypted it with the Service Master Key. When you backup the DMK, the system can decrypt the key for you without you providing the original password. Unless you explicitly executed a command to drop the encryption by service master key, you can backup the DMK to a file, provide a password which encrypts the file, migrate the file to your production system and restore it using the file encryption password previously provided. Or you can drop all keys and rebuild the encryption hierarchy giving the keys and certificates the same name. |
You have a strong coupling between your entity class and your dbms functions.
Here, the big problem is that the coupling is on metadata that you cannot easily disable at runtime. Therefore, to write some unit-tests, it will encourage you to use bytecode modification at runtime to have what you want. But it brings complexity and potential side-effects in your unit-test.
Besides, a code should be naturaly testable as much as possible( just a remark : with a TDD approach, this kind of problem may be fast noticed and handled).
So, if you can modify the code, I think that a better idea would be to separate the encryption/decryption matter from the domain matter in a way where you could choose implementation you wish for encryption/decryption matter.
In this way, in the applicative scope, you could use the real implementation and
in unit testing you could use a fake implementation which does nothing or even better no implementation at all.
Hibernate provides Entity Listener mechanisms. With them, you can have hooks at some time of the entity life-cycle.
Here you find more information :
https://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html/listeners.html
These callbacks could interest you :
@PrePersist Executed before the entity manager persist operation is
actually executed or cascaded. This call is synchronous with the
persist operation.
to encrypt value.
@PostLoad Executed after an entity has been loaded into the current
persistence context or an entity has been refreshed.
to decrypt value.
Finally, you could have two configuration files for hibernate, one with listener and another one without listener for your unit testing. |
Josso support all this federated login using OAuth. Check for Josso version 2 in josso.org and Twitter supported authentication protocols
Main Features (v2.4.2)
Advanced Administration console
Fully visual configuration, rollout and management Robust Identity and Access Management
A standards-compliant stack that supports a wide range of features Single Sign-On
Simple combined Web and Cloud Single Sign-On Rigorously tested and certified against multiple OS, Database and application servers
Clustering for high availability and scalability
System monitoring Provided via advanced JMX tools and APMs such as NewRelic
User Provisioning Automatic synchronization for aggregating identity repositories and keeping them in sync Desktop single sign-on
Password-free access from workstations to any on-premise or hosted service Deploy anywhere
Public, Private and Hybrid Clouds Multi-tenant and White Labeling ready for enabling wholesale business models Social SSO
Honors social identities from Google, Twitter, Facebook and LinkedIn Support for SAML, OpenID, OpenID Connect, OAuth, WS-Federation support for seamless Cloud/Federated SSO experience
Integrates with most commonly used stacks such as JavaEE, LAMP and MEAN stacks Multi-factor authentication support Windows interoperability
plays nice with Active Directory for native single sign-on Supports LDAP-compliant and JDBC-accessible identity repositories
Advanced multi-tenant branding capabilities Bundled with user self-services SOA security
Provides access control for both RESTful and SOAP web services Self-contained
Runs as an all-in-one server with no external infrastructure dependencies Cross OS and Hardware compatibility (100% Java-based)
|
I've not found a way to do this either. It looks like the Jersey filters/handlers aren't active on the Shiro servlet stack during authentication. As a work-around specifically for the AuthenticationException I opted to override the AdviceFilter::cleanup(...) method on my AuthenticatingFilter and return a custom message directly.
public class MyTokenAuthenticatingFilter extends AuthenticatingFilter {
protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) throws Exception {
// regular auth/token creation
}
@Override
protected void cleanup(ServletRequest request, ServletResponse response, Exception existing) throws ServletException, IOException {
HttpServletResponse httpResponse = (HttpServletResponse)response;
if ( null != existing ) {
httpResponse.setContentType(MediaType.APPLICATION_JSON);
httpResponse.getOutputStream().write(String.format("{\"error\":\"%s\"}", existing.getMessage()).getBytes());
httpResponse.setStatus(Response.Status.FORBIDDEN.getStatusCode());
existing = null; // prevent Shiro from tossing a ServletException
}
super.cleanup(request, httpResponse, existing);
}
}
When authentication is successful the ExceptionMappers work fine for exceptions thrown within the context of the Jersey controllers. |
The filter's (UsernamePasswordAuthenticationFilter or you can provide a custom-filter extends UsernamePasswordAuthenticationFilter)property "filterProcessesUrl" decide your login action go through the filter, looks like below:
<b:bean id="myAuthenticationFilter" class="com.xxx.xxx.YourFilterExtendsUsernamePasswordAuthenticationFilter">
<b:property name="filterProcessesUrl" value="/login" />
<b:property name="authenticationManager" ref="authenticationManager" />
<b:property name="usernameParameter" value="username" />
<b:property name="passwordParameter" value="password" />
<b:property name="authenticationSuccessHandler">
<b:bean class="org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler">
<b:property name="defaultTargetUrl" value="/acl/login/successhandler" />
</b:bean>
</b:property>
<b:property name="authenticationFailureHandler">
<b:bean class="org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler">
<b:property name="defaultFailureUrl" value="/acl/login/failurehandler" />
</b:bean>
</b:property>
</b:bean>
And configuration:
<intercept-url pattern="/login" access="permitAll" />
guarantee your Spring security's SecurityContextHolder have user's infomation which you can get it by:
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext() .getAuthentication().getPrincipal();
String username = userDetails.getUsername();
And configuration:
<http pattern="/login" security="none"/>
will ingore your intercept action, it could not save any user's detail infomation to SecurityContextHolder. so when you configure like this, it doesn't pass through any filter and when you call
SecurityContextHolder.getContext() .getAuthentication()
it will return null. |
I am working on a module to provide this functionality, but anyone looking to do this quick and dirty can do so with the following code:
from openerp import models
from openerp.http import SessionExpiredException
class IrHttp(models.Model):
_inherit = 'ir.http'
def _auth_method_user(self):
try:
return super(IrHttp, self)._auth_method_user()
except SessionExpiredException:
return self._auth_method_public()
The above attempts a user authentication, then explicitly re-authenticates as the public user on a SessionExpiredError. This is the method used for authentication with an RPC session, and this is the error thrown when it fails. It also seems that this error is only thrown when auth fails for public user.
The naming of the error, however, makes me think that there are some possible connotations involved with using this hack that have not been fully identified yet.
What I can say is that your data will at least be secure with this, due to the default secure permissions of Odoo. I can also say that basic session functionality & tests all seem to work as normal, outside of a slightly different error than normal in the case of logging out in one tab then browsing in another.
What I cannot say is what unintended side-effects this has on edge cases with sessions. Prelim testing seemed fine, but there are definitely possible far-reaching consequences.
The module is being worked in on in this pull request, with a preliminary name of web_session_allow_public |
This works for me.
protected async Task<String> connect(String URL,WSMethod method,StringContent body)
{
try
{
HttpClient client = new HttpClient
{
Timeout = TimeSpan.FromSeconds(Variables.SERVERWAITINGTIME)
};
if (await controller.getIsInternetAccessAvailable())
{
if (Variables.CURRENTUSER != null)
{
var authData = String.Format("{0}:{1}:{2}", Variables.CURRENTUSER.Login, Variables.CURRENTUSER.Mdp, Variables.TOKEN);
var authHeaderValue = Convert.ToBase64String(Encoding.UTF8.GetBytes(authData));
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authHeaderValue);
}
HttpResponseMessage response = null;
if (method == WSMethod.PUT)
response = await client.PutAsync(URL, body);
else if (method == WSMethod.POST)
response = await client.PostAsync(URL, body);
else
response = await client.GetAsync(URL);
....
}
|
if you have to handle encrypted ID columns, you have these options:
1) load the tables that are referenced into memory (out of your DB, into your application), then decrypt, then join ... obviously this has a little flaw: you are not capable of using your DBMS for the join, or for groupings, or for aggregation, etc if said things rely on the encrypted column to be available in decrypted form
2) load the first table, ENCRYPT the ids, and create a temp table containing the first table with its IDs encrypted, run your query against the temp table + other tables with encrypted IDs, and drop the temp table... obviously again there is a little flaw: your DBMS gains knowledge about what it is not supposed to know: the relation between the encrypted and unencrypted ids...
3) implement your encryption/decryption as a stored function, and call it with a key everytime you use the relationship ... again there is a flaw: your DBMS will need to call this function for every id value to obtain the decrypted/encrypted value, which is likely a performance impact you or your users can at most barely, if at all, tolerate
in the end you will most likely find out that the whole security gain of your encrypted IDs will be lost due to the fact that the key has to be stored on the applicationserver, or can be intercepted on the DBMS side, and the whole deal with implementing a encrypted ID columns was merely for fun and not for profit |
Quick way option with powershell, you should change some configurations.
For NAV 2016
$appUser = "XXX\XXX"; # User Name
$appUserFullName = "XXXXXxxxXX"; # FullName
$dataSource = "192.168.100.XX"; # SQL SERVER IP
$user = "sa"; # USERNAME
$pwd = "XXxxXX"; # SA Password
$database = "NAVERP"; # Database
$connectionString = "Server=$dataSource;uid=$user; pwd=$pwd;Database=$database;Integrated Security=False;";
$connection = New-Object System.Data.SqlClient.SqlConnection;
$connection.ConnectionString = $connectionString;
$objUser = New-Object System.Security.Principal.NTAccount($appUser)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$sqlCommandText ="
USE NAVERP
DECLARE @USERSID uniqueidentifier, @WINDOWSSID nvarchar(119), @USERNAME nvarchar(50), @USERSIDTXT varchar(50), @FullName as varchar(50)
SELECT NEWID()
SET @USERNAME = '$appUser'
set @FullName = '$appUserFullName'
SET @USERSID = NEWID()
SET @USERSIDTXT = CONVERT(VARCHAR(50), @USERSID)
SET @WINDOWSSID = '$strSID'
INSERT INTO [dbo].[User]
([User Security ID],[User Name],[Full Name],[State],[Expiry Date],[Windows Security ID], [Change Password],[License Type],[Authentication Email],[Contact Email])
VALUES
(@USERSID,@USERNAME,@FullName,0,'1753-01-01 00:00:00.000',@WINDOWSSID,0,0,'','');
INSERT INTO [dbo].[User Property]
([User Security ID],[Password],[Name Identifier],[Authentication Key], [WebServices Key],[WebServices Key Expiry Date],[Authentication Object ID])
VALUES
(@USERSID,'','','','','1753-01-01 00:00:00.000','');
INSERT INTO [dbo].[Access Control]([User Security ID],[Role ID],[Company Name],[App ID],Scope)
VALUES
(@USERSID,'SUPER','',cast(cast(0 as binary) as uniqueidentifier),0);
";
$connection.Open();
$command = $connection.CreateCommand();
$command.CommandText = $sqlCommandText;
$command.ExecuteNonQuery();
$connection.Close();
$sqlCommandText
|
In Entity Framework you can choose between three different approaches: Code first, Database first, and Model first. Check the link for more info: http://www.entityframeworktutorial.net/choosing-development-approach-with-entity-framework.aspx
Since you are manually creating the database tables, it looks like you want to use the Database first approach.
In order to create a data model in Visual Studio based on your existing database, you need to:
Add a "ADO.NET Entity Data Model" to your project.
In the first step of the wizard, select "EF Designer from database".
Specify the connection details (Server, database and authentication)
Select what entities should be in your model (you can include tables, views, stored procedures and functions).
After all those steps, an edmx file will be created with your model in it. Once you save this, all the classes will be generated.
If you want to modify an existing model, you can right click on your edmx file, select update model from database and follow the steps specified above.
Check this link for a more detailed explanation:
https://msdn.microsoft.com/en-us/data/jj206878 |
I don't think you need to add an extra authentication provider for a new IDP. You just need to add a new ?? in your CachingMetadataManager Bean. In the securityContext.xml provided in the sample app:
<!-- IDP Metadata configuration - paths to metadata of IDPs in circle of trust is here -->
<bean id="metadata" class="org.springframework.security.saml.metadata.CachingMetadataManager">
<constructor-arg>
<list>
<!-- Example of classpath metadata with Extended Metadata -->
<bean class="org.springframework.security.saml.metadata.ExtendedMetadataDelegate">
<constructor-arg>
<bean class="org.opensaml.saml2.metadata.provider.ResourceBackedMetadataProvider">
<constructor-arg>
<bean class="java.util.Timer"/>
</constructor-arg>
<constructor-arg>
<bean class="org.opensaml.util.resource.ClasspathResource">
<constructor-arg value="/metadata/idp.xml"/>
</bean>
</constructor-arg>
<property name="parserPool" ref="parserPool"/>
</bean>
</constructor-arg>
<constructor-arg>
<bean class="org.springframework.security.saml.metadata.ExtendedMetadata">
</bean>
</constructor-arg>
</bean>
<!-- Example of HTTP metadata without Extended Metadata -->
<bean class="org.opensaml.saml2.metadata.provider.HTTPMetadataProvider">
<!-- URL containing the metadata -->
<constructor-arg>
<value type="java.lang.String">http://idp.ssocircle.com/idp-meta.xml</value>
</constructor-arg>
<!-- Timeout for metadata loading in ms -->
<constructor-arg>
<value type="int">15000</value>
</constructor-arg>
<property name="parserPool" ref="parserPool"/>
</bean>
<!-- Example of file system metadata without Extended Metadata -->
<bean class="org.opensaml.saml2.metadata.provider.FilesystemMetadataProvider">
<constructor-arg>
<value type="java.io.File">/usr/local/metadata/idp.xml</value>
</constructor-arg>
<property name="parserPool" ref="parserPool"/>
</bean>
</list>
</constructor-arg>
</bean>
If you un-comment the second bean in the list, it will enable another IDP specified in the xml file provided at /usr/local/metadata/idp.xml. If you want to add the metadata of another IDP over http, just copy the one for ssocircle and make adjustments. |
You need to register both WebAPI routes and MVC routes:
All this should be done in Application_Start method in Global.asax.cs file:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
GlobalConfiguration.Configure(WebApiConfig.Register) is used to configure WebApi (and register api related routes)():
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
RouteConfig.RegisterRoutes(RouteTable.Routes); is used to register MVC routes:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Default", action = "Index", id = UrlParameter.Optional }
);
}
You also need verify that the DefaultController that you created is MVC controller (inherits from System.Web.Mvc.Controller) and not WebAPI controller |
curl -v -XPOST -H 'Content-Type: application/json' -d '{ "email":"[email protected]", "password": "password"}' localhost:3000/auth/sign_in
* Hostname was NOT found in DNS cache
* Trying 127.0.0.1...
* Connected to localhost (127.0.0.1) port 3000 (#0)
> POST /auth/sign_in HTTP/1.1
> User-Agent: curl/7.35.0
> Host: localhost:3000
> Accept: */*
> Content-Type: application/json
> Content-Length: 55
>
* upload completely sent off: 55 out of 55 bytes
< HTTP/1.1 200 OK
< X-Frame-Options: SAMEORIGIN
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< Content-Type: application/json; charset=utf-8
< access-token: Bm3FaRpSAjT-EtTrj8Ucww
< token-type: Bearer
< client: 6XCiYTxcEITVRZItRKFa8w
< expiry: 1480750998
< uid: [email protected]
< ETag: W/"be9091473a08ccf2672b9685eb25caa2"
< Cache-Control: max-age=0, private, must-revalidate
< X-Request-Id: 4996fb00-a45c-41e4-b30b-c86bc10b24d5
< X-Runtime: 0.737506
< Transfer-Encoding: chunked
<
* Connection #0 to host localhost left intact
{"data":{"id":1,"email":"[email protected]","provider":"email","uid":"[email protected]","name":null,"nickname":null,"image":null}}
Use -v for curl - it will give you many clues.
Comment was right - do not place login / password inside session.
Snip from TL;DR that you should read thoroughly:
The authentication headers consists of the following params: access-token, client, expire, uid
The authentication headers required for each request will be available in the response from the previous request.
|
Say we have two individuals Alice and Bob, each with their own private key and public key. In order for Alice to send out a message that only Bob can read, do we simply send an encrypted message with Bob's public key?
Yes, the message is encrypted with Bob's public key and encrypted with private key. ( Be aware that the size of the message is límited by RSA key size, so for encryption of large message RSA encryption is used to share a symmetric encryption key)
Likewise, in order for Alice to send a message that everyone can verify that it is from her, do we simply send an encrypted message with Alice's public key?
It is not correct. This case if known as 'digital signature'. The message is digested with a hashing algorithm like SHA, and the result is encrypted with Alice's private key. This is the signature. Bob can verify the message and signature with Alice's public key (decrypt the signature and check that the hash of the message is the same that the encrypted one). If verification is succesful you know that It has been issued by Alice because she owns the private key |
try the following.
1.Ensure that you have Ruby installed, and then run this from your terminal:
wget -O- https://toolbelt.heroku.com/install-ubuntu.sh | sh
2.Login to heroku
$ heroku login
Enter your Heroku credentials.
Email: [email protected]
Password (typing will be hidden):
Authentication successful.
3.Create your app if you haven't created
$ cd ~/myapp
$ heroku create <app name>
4.install git & git init in your project folder
5.login to heroku dashboard get your app git repository
6.git remote add heroku <repository url>
7.make your changes in project and commit
8.create Procfile in project root folder
web:python manage.py runserver
web: gunicorn <project-name>.wsgi --log-file -
heroku ps:scale web=1
9.Create requirements.txt file in project root folder
Django==1.9
gunicorn==19.4.5
psycopg2==2.6.1
whitenoise==2.0.6
wsgiref==0.1.2
dj-database-url==0.4.1
10.In your settings.py add the following at end of file.
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, "static"),
]
import dj_database_url
DATABASES['default'] = dj_database_url.config()
11.Add the following in wsgi.py to server static files
from whitenoise.django import DjangoWhiteNoise
application = DjangoWhiteNoise(get_wsgi_application())
12.Commit your changes and git push heroku master.
Now, open your browser and type https://your-app-name.heroku.com see the magic. |
It is nigh impossible to do it from C code alone. The multiple ways a C-compiler is allowed to translate a chunk of C-code do not allow for a precise calculation of the energy consumption. You need to know how the compiler translates which code for which architecture.
It is much simpler (for certain degrees of "simple") to count the assembler commands and multiply them with the respective latencies (Listed in the technical specs, e.g. for a randomly chosen MCU from the Wiki list: http://www.atmel.com/Images/doc32002.pdf). This is still not exact, division for example might take a different amount of CPU cycles depending on the input, CPU architecture and implementation in the hardware, but it comes quite close and is rather simple, although a bit tedious.
And than there are the loops with a completely unknown number of iterations, input taking different paths with different runtimes and much more. The people writing encryption software know more about it, especially how to avoid it. You might not like their solutions.
Otherwise: check what you expect for input (you do know which path which input takes, do you?), write a test program, go to e.g.: https://www.rohde-schwarz.com/ to get a good meter and measure the power consumption. You also need an engineer who knows how to do that, it's not easy! |
I couldn't understand very clearly, about your unsuccessful login. Actually, Azure AD implement with OAuth 2.0 grand flow to authenticate and authorize your users.
And the url you provided is the first step to generate the authentication code, then you direct your user to this endpoint, any unsuccessfully authentication occurs, it will not redirect to your uri. The error message will be shown to your user in the IDP page.
If your user has redirected to your uri with the code parameter, it means that this user has successfully signed on in Azure AD.
After authentication, your user need to set the access_token in Authorization request header to your server. If you want to get the info of authenticated user, you can try to use following code snippet:
$headers = getallheaders();
$token = (explode(' ',$headers['Authorization']))[1];
list($headb64, $bodyb64, $cryptob64) = explode('.',$token);
$payload = json_decode(base64_decode($bodyb64));
echo $payload->{'family_name'};
echo $payload->{'given_name'};
echo $payload->{'upn'}; //email
You can refer to https://docs.microsoft.com/en-us/azure/active-directory/active-directory-authentication-scenarios?toc=%2fazure%2factive-directory%2fdevelop%2ftoc.json#claims-in-azure-ad-security-tokens for the supported claim in payload.
Any further concern, please feel free to let me know. |
I have noticed that when you want to switch between tenants, you need to re-authorize against the current tenant.
I got it working this way:
1. First sign-in needs to be done against the common endpoint.
2. Every time I need a token for certain resource, I try to get the token silently.
=> This can throw 2 different AdalSilentTokenAcquisitionException
Nothing found in cache, also no refresh token found
=> In this case, I redirect the user to the login page again.
When you switch between tenants, and it is the first time you want to login using a tenant where you've been trusted, you can get a error like: User or admin should be given consent for this application. Although the admin from his home tenant has added the application in the directory for the home tenant. Anyone who knows why this consent is needed? So tenant A and tenant B admins have both been given consent. Why does a trusted user from B in A still needs to consent someway?
I was able to trigger the consent flow by redirecting the user to the authorization request URL.
So when I got an AdalSilentTokenAcquisitionException, and the error code is "failed_to_acquire_token_silently" then I had to redirect the user to the URL generated by the authContext (authenticationContext.GetAuthorizationRequestUrlAsync) when the cache had been cleared, no refresh token will be found, then redirect the user to resign. |
Even if some public TLS Server were to support PSK, you won't be able to test your client with it. There is a fundamental difference between the way public key authentication (which is used by most of the TLS Servers) work and PSK.
Public Key Authentication:
Incase of Public Key Server Authentication (the ones that doesn't involve Client Authentication), the server sends a Certificate, which contains a Public Key and Client encrypts it's pre-master secret and sends it to server which only the server can decrypt. In this way both have the same pre-master secret and can use the same set of derivations to further derive the final key.
Pre-Shared key:
As the name indicates the pre-shared requires both parties to have the same key pre-shared among themselves. They just exchange the IDs between them to indicate which of the Pre-Shared they will be using to generate the final key.
So, even if there is a server which supports PSK, you should have the same set of (or atleast one) of the keys which it has, which is impossible as those servers won't share their keys with anyone apart from whom it is supposed to be shared with (the legit clients).
So, the best way for you is to use openssl's test client and server tools and test it. |
1.Where is doAuthentication bound to the the props in App.js? Assuming that App.js is the top level root app component.
Ans:
The action doAuthentication is bound with the props of App component using the middleware called redux-thunk.
let createStoreWithMiddleware = applyMiddleware(thunkMiddleware, api)(createStore)
let store = createStoreWithMiddleware(quotesApp)
The above two line of code would have done it for your. Read here why redux-thunk is required.
2.Doesn't doAuthentication generate a function that expects a dispatch argument? Why don't we do anything in the constructor with the returned function from doAuthentication()? If we don't assign the returned function to anything, does this.props.doAuthentication persist anything or have any effects? Shouldn't it be something like doAuthentication()(someDispatchFunction) Where does this dispatch function come from?
Ans:
2.1 Yes, the function which is returned by doAuthentication function expects a dispatch method as to be a first parameter.
2.2, 2.3 Here the doAuthentication action creator's job is to create a Redux action which would just listen for the event called authenticated. When we call doAuthentication action creator, it returns a Redux action function which accepts a dispatch method as first parameter and getState method as second. The parameters would be passed by the redux-thunnk middleware.
The redux-thunk middleware would call the redux action which is return from the doAuthentication call since it is connet-ed. Otherwise we have to dispatch the action returned by the doAuthentication as like the below,
this.props.dispatch(doAuthentication())
2.4 We can do as you mention doAuthentication()(someDispatchFunction), but consider this quote
If Redux Thunk middleware is enabled, any time you attempt to
dispatch a function instead of an action object, the middleware will
call that function with dispatch method itself as the first argument.
And, you can find a detailed info about the redux-thunk with this answer |
Implementing a SSO requires having a common database holding the user credential information. One way of doing it is implementing your own authentication server which exposes a login, register, reset and forgot password APIs which each of your apps would use to login into the application.
Lets say you are using JWT to maintain statelessness, which means auth server responds with a JWT for every successful login through any android app.
So your launcher activity in each of your app should not be login but the dashboard or whatever the user sees after login. In the on_create of the dashboard, check if there is an existing jwt available in the shared preferences. If there is one, go ahead with the dashboard. But if there isnt one, goto login activity and let the user login first. Once logged in, preserve the jwt in shared preferences for the other apps to use it. You need to make sure that all the shared preferences are using the same namespace to access the jwt.
To make it more effective, you can implement a library module for login, regd and forgot password to be included into each app and you would have that part for all the apps ready. The XML files for three activities can be included into the lib itself and app will load them from the lib file if it doesnt find it in the app drawables.
Now coming to server part, implementing your custom auth server, say using OAuth2 is one way but to make it easier, there are 3rd party solutions like Stormpath or CAS which would provide such a service. May be you can find one which is free too.
Instead of JWT, you could use userId (primary key in the user database) to identify if the user is logged in or not.
Another point to consider is if the application server for each of these apps, if they have one, are using JWT or userId to respond to app requests and based on that auth server communication token should be decided. Needless to say, that application server and the auth server should also communicate among them to sync user information for app. This would be the same even if you are using a 3rd party auth server which would talk to a single database holding the entire user information but you might need to work on syncing your application server with 3rd party auth server
However, the tricky part is in logout and reset password and change password. I am not talking about the logout process if JWT is used, which has its own challenges to meet, but I am talking about the logout when SSO is used. If the user logs out from one of the apps you need to decide if the user has to be logged out from the rest of the apps or not. Both can be handled though but usually it would be a single sign out for ease of implementation and it would provide a good UX too.
Also, if any of these apps has a website version and the user changes or resets password from the website, you need to make sure that user logs in again on the device when he first uses the app after the change. However this logic has to be managed entirely on the server side inside the auth server.
Though your question is related to android app only, you might have to implement a server for that and modify the appl server too for each of the app. There might be a chance that this might not be your question essence entirely, but your actual requirement might help me to help you implement this. |
By the following updated code I have achieved by fetch the user and the details of the user from Active Directory using LDAP Query
The ldapUsername is the administrator user of the domain controller.
The ldapPassword is the password of the administrator user.
The ldapAccountToLookup is the username to which have to search under the given domain.
public static void main(String[] args) throws NamingException
{
final String ldapSearchBase = "dc=NewForest,dc=sample,dc=com";
final String ldapUsername = "sampleAdminUser";
final String ldapPassword = "Password";
final String ldapAccountToLookup = "sampleUser";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://XX.XX.XX.XX:389");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, ldapUsername);
env.put(Context.SECURITY_CREDENTIALS, ldapPassword);
DirContext ctx = new InitialDirContext(env);
LDAPTest ldap = new LDAPTest();
SearchResult srLdapUser = ldap.findAccountByAccountName(ctx, ldapSearchBase, ldapAccountToLookup);
System.out.println("srLdapUser :" + srLdapUser);
}
|
Based on the information you provided I'm assuming that you want to have an application that has the front-end implemented in Angular and uses a Rails based API to provides the services required to the Angular front-end.
In this scenario you can model this as a single (client) application from the Auth0 side of things and do one of the following:
Use the ID token resulting from the authentication for two purposes:
to provide information about the currently authenticated user to the Angular application so that it can meet any applicable user interface requirements
as a way to authenticate calls made by the Angular application to the Rails API, that is, the Rails API uses a token-based authentication system that accepts the ID tokens issued by Auth0.
Expose an endpoint on the Rails API that can be used by Angular to exchange the ID token received upon user authentication by any other credentials that can then be later used to access the API.
The first option is the easiest to implement, but you'll have to include the ID token in every request. The second one increases complexity on your side, but it may allow you more flexibility.
If this does not address all your concerns, can you please update the question with more details about the exact scenario you're trying to accomplish.
A final note, if your intentions are to provide an API that can be later consumed by a different range of applications then the most correct way to secure it would be by using a token-based system where the tokens would be issued by an authorization server compliant with OAuth2.
Having your own OAuth2 authorization server is significantly complex to maintain so Auth0 is in the process of enabling this as an additional service that can already be used in preview mode for accounts in the US region. This would basically allow to obtain as part of the authentication process an ID token used by the client application to know the currently authenticated user and also an access token that would allow to make call into the specified API. |
Had the same problem, was really frustrated about it. I found a 'dirty' workaround by creating a rudimentary API in PHP that handles the authentication for me.
If you want to try this route, do this:
Have a look at this page, and install this package in your PHP (it wasn't updated since 2010 but it still works fine): https://ssrsphp.codeplex.com/
Here is the example from the page (useful if you want to pass parameters to your report):
// include the SSRS library
require_once 'SSRSReport.php';
define("REPORT", "/AdventureWorks 2008 Sample Reports/TopStoresBegin");
$settings = parse_ini_file("app.config", 1);
// Create a connection to the SSRS Server
$rs = new SSRSReport(new Credentials($settings["UID"], $settings["PASWD"]),$settings["SERVICE_URL"]);
// Load the report and specify the params required for its execution
$executionInfo = $rs->LoadReport2(REPORT, NULL);
$parameters = array();
$parameters[0] = new ParameterValue();
$parameters[0]->Name = "ProductCategory";
$parameters[0]->Value = "1";
$parameters[1] = new ParameterValue();
$parameters[1]->Name = "StartDate";
$parameters[1]->Value = "1/1/2003";
$parameters[2] = new ParameterValue();
$parameters[2]->Name = "EndDate";
$parameters[2]->Value = "12/31/2003";
$parameters[3] = new ParameterValue();
$parameters[3]->Name = "ProductSubcategory";
$parameters[3]->Value = "2";
$rs->SetExecutionParameters2($parameters);
// Require the Report to be rendered in HTML format
$renderAsHTML = new RenderAsHTML();
// Set the links in the reports to point to the php app
$renderAsHTML->ReplacementRoot = getPageURL();
// Set the root path on the server for any image included in the report
$renderAsHTML->StreamRoot = './images/';
// Execute the Report
$result_html = $rs->Render2($renderAsHTML,
PageCountModeEnum::$Actual,
$Extension,
$MimeType,
$Encoding,
$Warnings,
$StreamIds);
// Save all images on the server (under /images/ dir)
foreach($StreamIds as $StreamId)
{
$renderAsHTML->StreamRoot = null;
$result_png = $rs->RenderStream($renderAsHTML,
$StreamId,
$Encoding,
$MimeType);
if (!$handle = fopen("./images/" . $StreamId, 'wb'))
{
echo "Cannot open file for writing output";
exit;
}
if (fwrite($handle, $result_png) === FALSE)
{
echo "Cannot write to file";
exit;
}
fclose($handle);
}
// include the Report within a Div on the page
echo '<html><body><br/><br/>';
echo '<div align="center">';
echo '<div style="overflow:auto; width:700px; height:600px">';
echo $result_html;
echo '</div>';
echo '</div>';
echo '</body></html>';
However for my needs I have simplified the code very much. Also I had to remove the url rewrite function from it as it would mess up server session id, and that in turn would mean that if you had any drilldowns on your reports they would not work at all. This is snippet from my code:
/* Load SSRS Library */
require_once 'SSRSReport.php';
/* Load a report - remember that you can set up an external file that would hold the login credentials for you, I left those here for demonstration only*/
define("UID", 'Your user name here');
define("PWD", "Your pass");
define("SERVICE_URL", "Service url for your ssrs");
define("REPORT", "Variable with your 'path to' and name of report");
try
{
$ssrs_report = new SSRSReport(new Credentials(UID, PWD),
SERVICE_URL);
$ssrs_report->LoadReport2(REPORT, NULL);
$htmlFormat = new RenderAsHTML();
$htmlFormat->StreamRoot = './images/';
$result_html = $ssrs_report->Render2($htmlFormat,
PageCountModeEnum::$Estimate,
$Extension,
$MimeType,
$Encoding,
$Warnings,
$StreamIds);
echo $result_html;
}
Catch(SSRSReportException $serviceExcprion)
{
echo $serviceExcprion->GetErrorMessage();
}
So in my app when I make the call to my api I pass the name of the report and the path (url encoded) at the end of the url. Then I decode it on the server, PHP SSRS SDK then logs you in grabs the report and returns it as HTML (works a charm for PDF or CSV too)
So in an iFrame I put the url for my api with the parameter at the end. You can obviously handle any extra parameters this way. Then when I go to my main app I no longer see login screen and the report displays immediately.
One problem I've found though is that still, very very occasionally you do get logged out somehow and the dreaded login screen shows itself, but then on the page refresh it works again.
Hope this helps! |
IntegerWolf's answer definitely pointed me in the right direction, but here's what ended up working for me:
Discovering the Authorization Authority
I ran the following code (in LINQPad) to determine the authorization endpoint to use for the Dynamics CRM instance to which I want my daemon/service/application to connect:
AuthenticationParameters ap =
AuthenticationParameters.CreateFromResourceUrlAsync(
new Uri(resource + "/api/data/"))
.Result;
return ap.Authority;
resource is the URL of your CRM instance (or other app/service that's using ADAL), e.g. "https://myorg.crm.dynamics.com".
In my case, the return value was "https://login.windows.net/my-crm-instance-tenant-id/oauth2/authorize". I suspect you can simply replace the tenant ID of your instance.
Source:
Discover the authority at run time – Connect to Microsoft Dynamics 365 web services using OAuth
Manually Authorizing the Daemon/Service/Application
This was the crucial step for which I failed to find any help.
I had to open the following URL in a web browser [formatted for easier viewing]:
https://login.windows.net/my-crm-instance-tenant-id/oauth2/authorize?
client_id=my-app-id
&response_type=code
&resource=https%3A//myorg.crm.dynamics.com
When the page for that URL loaded, I logged in using the credentials for the user for which I wanted to run my daemon/service/app. I was then prompted to grant access to Dynamics CRM for the daemon/service/app as the user for which I logged-in. I granted access.
Note that the login.windows.net site/app tried to open the 'home page' of my app that I setup in my app's Azure Active Directory registration. But my app doesn't actually have a home page so this 'failed'. But the above still seems to have successfully authorized my app's credentials to access Dynamics.
Acquiring a Token
Finally, the code below based on the code in IntegerWolf's answer worked for me.
Note that the endpoint used is mostly the same as for the 'manual authorization' described in the previous section except that the final segment of the URL path is token instead of authorize.
string AcquireAccessToken(
string appId,
string appSecretKey,
string resource,
string userName,
string userPassword)
{
Dictionary<string, string> contentValues =
new Dictionary<string, string>()
{
{ "client_id", appId },
{ "resource", resource },
{ "username", userName },
{ "password", userPassword },
{ "grant_type", "password" },
{ "client_secret", appSecretKey }
};
HttpContent content = new FormUrlEncodedContent(contentValues);
using (HttpClient httpClient = new HttpClient())
{
httpClient.DefaultRequestHeaders.Add("Cache-Control", "no-cache");
HttpResponseMessage response =
httpClient.PostAsync(
"https://login.windows.net/my-crm-instance-tenant-id/oauth2/token",
content)
.Result
//.Dump() // LINQPad output
;
string responseContent =
response.Content.ReadAsStringAsync().Result
//.Dump() // LINQPad output
;
if (response.IsOk() && response.IsJson())
{
Dictionary<string, string> resultDictionary =
(new JavaScriptSerializer())
.Deserialize<Dictionary<string, string>>(responseContent)
//.Dump() // LINQPad output
;
return resultDictionary["access_token"];
}
}
return null;
}
The code above makes use of some extension methods:
public static class HttpResponseMessageExtensions
{
public static bool IsOk(this HttpResponseMessage response)
{
return response.StatusCode == System.Net.HttpStatusCode.OK;
}
public static bool IsHtml(this HttpResponseMessage response)
{
return response.FirstContentTypeTypes().Contains("text/html");
}
public static bool IsJson(this HttpResponseMessage response)
{
return response.FirstContentTypeTypes().Contains("application/json");
}
public static IEnumerable<string> FirstContentTypeTypes(
this HttpResponseMessage response)
{
IEnumerable<string> contentTypes =
response.Content.Headers.Single(h => h.Key == "Content-Type").Value;
return contentTypes.First().Split(new string[] { "; " }, StringSplitOptions.None);
}
}
Using a Token
To use a token with requests made with the HttpClient class, just add an authorization header containing the token:
httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", accessToken);
|
I fix it by following http://webservices20.blogspot.ae/2012/06/12-common-wcf-interop-confusions.html
In short I have,
[ServiceContractAttribute(ConfigurationName="ServiceSoap",ProtectionLevel=ProtectionLevel.Sign)]
<bindings>
<customBinding>
<binding name="BPELProcess1Binding">
<security authenticationMode="MutualCertificate" enableUnsecuredResponse="true"
messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
<textMessageEncoding messageVersion="Soap11" />
<httpsTransport />
</binding>
</customBinding>
</bindings>
<behaviors>
<endpointBehaviors>
<behavior name="secureBehaviour">
<clientCredentials>
<serviceCertificate>
<defaultCertificate findValue="My CA" storeLocation="CurrentUser" storeName="TrustedPublisher" x509FindType="FindByIssuerName" />
</serviceCertificate>
</clientCredentials>
</behavior>
</endpointBehaviors>
<client>
<endpoint address="MyUrl" binding="customBinding" bindingConfiguration="BPELProcess1Binding" contract="MyContract" name="DeclarationB2BProcessing" behaviorConfiguration="secureBehaviour">
<identity>
<dns value="MyCertProp" />
</identity>
</endpoint>
</client>
|
Note that GitHub completely ignores your configured user.name. It uses only the authentication you send them.
When you push with SSH (ssh://[email protected]/path/to/repo.git), the authentication you send is your SSH key. The details of how this are stored are somewhat OS-dependent.
When you push with HTTPS (https://github.com/path/to/repo.git), you will generally have to enter a user name and password. These make up the authentication you send. If you are not being prompted to enter a user name and password, you might want to check any cached or stored authentication credentials. The details are, as before, OS-dependent.
Git does have a few built-in "credential helpers" for HTTPS. The default one simply asks for user name and password every time. The "cache" helper stores them in memory and times them out, and the "store" helper which is not secure stores them as plain-text files, meaning anyone with access to your files can find your password. See https://git-scm.com/book/en/v2/Git-Tools-Credential-Storage for details on these.
You can install additional helpers, and some come with some OSes, that do store authentications more permanently, but also store them reasonably securely, the same way SSH does.
Existing StackOverflow post git credential.helper=cache never forgets the password? has additional information on setting and clearing credential helpers (although the specific questions about why the cache timeout was not working, way back in Git 1.7.10.4, are not answered there). |
Model is a pure client component, you need to modify the adal for js's SDK to manually implement the iframe into a model component. It's a lot of work and not directly integration.
Although, you can use popup window to achieve your requirement. Configure displayCall in adal context initial function closure:
adalProvider.init(
{
displayCall: function (urlNavigate) {
var popupWindow = window.open(urlNavigate, "login", 'width=483, height=600');
if (popupWindow && popupWindow.focus)
popupWindow.focus();
var registeredRedirectUri = this.redirectUri;
var pollTimer = window.setInterval(function () {
if (!popupWindow || popupWindow.closed || popupWindow.closed === undefined) {
window.clearInterval(pollTimer);
}
try {
if (popupWindow.document.URL.indexOf(registeredRedirectUri) != -1) {
window.clearInterval(pollTimer);
window.location.hash = popupWindow.location.hash;
popupWindow.close();
}
} catch (e) {
}
}, 20);
}
},
$httpProvider
);
It will direct to Azure AD SSO page in a popup window. You can refer to https://github.com/AzureAD/azure-activedirectory-library-for-js/wiki/FAQs#q5-how-to-use-a-popup-for-loginauthentication-process for more info. |
NO.
This is not a good idea, for several reasons:
If you fear that someone will be able to access your database (that's why you want to encrypt it, right?), then you should also fear that they will be able to access your source-code, wich means your whole scheme falls apart from the start.
even if you manage to keep your algorithm for encryption safe, chances are someone able to access your DB will be able to get some information out of it anyway (either by brute force, or using something like statistical analysis to search for known or common passwords, etc). Encryption is a complicated science. It's best to leave the technical details to the experts.
This may be a little beyond what you are considering right now, but if you DO get hacked, and some or all of your data is leaked, you will probably have a harder time explaining it to your users if it happened because you had "home-made" security. For my part at least, I would be more forgiving of a data leak if I knew you had made a real effort to apply security measures that are up to date and generally accepted as trustworthy by the industry.
In short: It's best to leave encryption to the experts. Instead of building you own, your're most likely better off looking for a good way to apply their solutions to your particular situation. |
I change my spring SecurityConfig,here is used to processing some authorizeUrls:
@Configuration
@Order(ManagementServerProperties.ACCESS_OVERRIDE_ORDER)
@EnableGlobalMethodSecurity(securedEnabled = true)
public class SecurityConfig extends GlobalAuthenticationConfigurerAdapter {
@Override
public void init(AuthenticationManagerBuilder auth) throws Exception {
//doing jdbc Authentication
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
super.configure(auth);
}
@Configuration
@Order(1)
public static class ClientSecurityConfigurationAdapter extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.antMatcher("/mobile/**")
.formLogin().loginPage("/client/login")
.loginProcessingUrl("/oauth/login")
.successHandler(clientLoginSuccessHandler).permitAll()
.and()
.logout()
.logoutSuccessHandler(clientLogoutSuccessHandler)
.logoutUrl("/client/logout")
.logoutSuccessUrl("/client/login")
.invalidateHttpSession(true);
}
}
@Configuration
@Order(2)
public static class WebSecurityConfigurerAdapter extends
WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.regexMatcher("/((?!api).)*")
.formLogin()
.loginPage("/web/login")
.loginProcessingUrl("/oauth/login")
.successHandler(loginSuccessHandler)
.permitAll()
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler)
.logoutUrl("/web/logout")
.logoutSuccessUrl("/web/login")
.invalidateHttpSession(true);
}
}
}
and add ResourceServerConfig for handle token validation issues:
@Configuration
@EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
@Autowired
TokenStore tokenStore;
@Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/api/**").//
and().authorizeRequests().antMatchers("/api/**",).authenticated();
}
@Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId("openid").tokenStore(tokenStore);
}
}
finally,build a request with a request header
"Authorization:Bearer <access_token>"
|
The question is too old, but I run in the same issue.
Anirudh Ramanathan's answer is correct.
The solution is to add new Application in different ApplicationPools.
Right from Microsoft's documentation:
In the Connections pane, expand the Sites node.
Right-click the site for which you want to create an application, and click Add Application.
In the Alias text box, type a value for the application URL, such as marketing. This value is used to access the application in a URL.
Click Select if you want to select a different application pool than the one listed in the Application pool box. In the Select Application Pool dialog box, select an application pool from the Application pool list and then click OK.
In the Physical path text box, type the physical path of the application's folder, or click the browse button (...) to navigate the file system to find the folder.
Optionally, click Connect as to specify credentials that have permission to access the physical path. If you do not use specific credentials, select the Application user (pass-through authentication) option on the >Connect As dialog box.
Optionally, click Test Settings to verify the settings that you specified for the application.
Click OK.
Complete documentation here
N.B.: "click Test Settings to verify the settings that you specified for the application" may produce an error. According to other SO answers, it seems to be a bug. I ignore this alert and everything run well. |
According to the disclaimer on the slim-jwt-auth landing page the middleware only processes tokens; does not provide any way to generate them.
HEADS UP! Middleware does not implement OAuth 2.0 authorization server nor does it provide ways to generate, issue or store authentication tokens. It only parses and authenticates a token when passed via header or cookie.
(emphasis is mine)
You can indeed use another library to generate JWT tokens which will then be consumed by slim-jwt-auth. As long as both libraries implemented the specification correctly you should have no interoperability problems at least if you only use the mandatory to implement parts of the specification.
You can check jwt.io for a list of PHP libraries for JWT processing, but firebase/jwt would be a good starting point. If instead of generating the tokens yourself you're looking into completely delegate the authentication and issuance of tokens to a third-party, then I would suggest having a look at Auth0.
Disclosure: I work at Auth0. |
I think it would be good for you to step back and consider what this script actually does, because it is still a gigantic security hole. Here is what it does:
Take the user's input (which is always untrustworthy)
See if it's extension is allowed according to a small list of possible extensions
If so, pass it off to the user
Now that you have it die for unrecognized file extensions, it won't let them download your actual php files. But it will still let the user do all sorts of terrible things, all of which comes down to one very key issue:
You make no attempt to verify that the file being requested is actually reasonable for the person to view!!!
A key point is that readfile() doesn't care where the file is. Nor does it even assume that the file is in your website's public directory. The only reason it is downloading files from your web directory is because you didn't start the filename with a slash. However, readfile() will happily pass along anything on the server that it has read access to. Without your recent change a user could have just as easily done this:
http://domain.net/download.php?file=/etc/passwd
Moreover, it doesn't even have to be an actual file on the server. In most PHP installations PHP will happily load up URLs as actual files. So someone could also use your script as a proxy:
http://domain.net/download.php?file=http://theFBIwillArrestYouIfYouLoadThis.com/secrets.pdf
That sort of vulnerability (the ability to use your script as a proxy) is still present in your current solution. Anytime I see a website take file paths like this I love to see just how much it will let me get away with. You could set yourself up for a world of hurt in the worst case scenario.
You have to look at it from a defense-in-depth scenario. What it boils down to is the difference between blacklisting (what is the user not allowed to do) and whitelisting (what should this user be allowed to do). Good security practices rely on the latter method of thinking exclusively, because it is impossible to come up with a completely exhaustive blacklist that covers all possible scenarios.
In a case like this if you want a user to be able to download files you need some sort of list of files that are allowed to be downloaded. One example would be to place any file that is supposed to be downloaded into a specific directory. If a user requests a file then your script can use realpath() to make sure that file is actually in your public directory and otherwise forbid the download. Although if they are all in one directory you could just as easy change a configuration rule in your webserver (e.g. apache or nginx) to have it automatically add the 'content-disposition: attachment' header to anything in that directory. Then you just have to make sure that you never put the wrong files in that public directory.
Me personally though, I would approach it with a complete white-list. I would never let someone specify a filename and then use it to download a file. Rather I would have an administrative area where I manage files that are marked for download: the list of allowed files would be stored in the database and managed by me. When the user downloads a file they don't do it by specifying a filename but rather by specifying the id from the database that corresponds to the file they want to download (a simple user interface is necessary to facilitate this). The ID is used to lookup the file path, and the file can then be downloaded safely. You can then even store the files in directories outside the public area of your website so that you have full control over who can access the files.
That last suggestion is probably overkill for what you are trying to do, but the short of this is simple: you have to think carefully about the security implications of your code and make sure you are giving the user the minimum amount of privileges possible. |
Tried to redirect from Google to Authorized redirect URI
http://localhost:10001/user
o.s.s.w.a.i.FilterSecurityInterceptor - Secure object:
FilterInvocation: URL:
/user?state=Wj7RVk&code=4/wa2AFtJr0K3cKTxDAYo8rTOu2p41km5o3YCPnimx4wU;
Attributes: [authenticated]
Looks like you are doing it in a wrong way, you shouldn't go to /user with the code and state params! The flow is:
You register an sso endpoint for an url like
localhost:8080/login/facebook
Once you clicked to a link which leads to the endpoint you get
redirected to facebook authorization page
Once authorized you should be redirected back to
localhost:8080/login/facebook with your state and code params:
localhost:8080/login/facebook?state=Wj7RVk&code=4/wa2AFtJr0K3cKTxDAYo8rTOu2p41km5o3YCPnimx4wU
When sso filter gets the code is goes to the facebook again to
exchange access_code to access_token and puts the token into session
In the end of the process AuthenticationSuccessHandler is called to redirect
you according to its concrete imlementation (usually it is
SavedRequestAwareAuthenticationSuccessHandler)
If these steps were completed successfully you can go to /user endpoint to get some user information. |
I also had this problem - using Rails 4.1 no matter what I did when I tried to send out an email I always got the dreaded
NoMethodError (undefined method `ascii_only?' for nil:NilClass):
For me the problem was related to my mailer settings - one of the components, in this case the SMTP Server Name, was not set up correctly.
I use a local file for semi-secret settings, so my configuration looked like this:
config.action_mailer.smtp_settings = {
:authentication => :plain,
:address => SECRET['SMTP_HOST'],
:port => SECRET['SMTP_PORT'],
:domain => SECRET['SMTP_DOMAIN'],
:user_name => SECRET['SMTP_USER'],
:password => SECRET['SMTP_PASS']
}
The SECRET hash is read in application.rb like this
secrets_file = "#{ENV['HOME']}/.secrets/myapp.yml"
SECRET = File.exists?(secrets_file) ? YAML.load_file(secrets_file) : {}
And the myapp.yml file then simply contains key-value pairs in YAML format.
The reason I got the ascii_only? nil error was because I was simply missing on of the SMTP settings (in my case the :address) - and that caused the error. |
By default, you can add authentication for users with a Google Account:
Have a look at https://cloud.google.com/appengine/docs/java/endpoints/getstarted/clients/js/add_auth for web clients (JavaScript)
Have a look at https://rominirani.com/google-cloud-endpoints-tutorial-part-7-8cc471fccbf6#.pp02fjo8u for Android client (note that this very good tutorial also covers web clients)
Recently, during last Google I/O, Google announced that it will be possible to authenticate users on Google App Engine using Firebase Authentication. The interesting aspect is that Firebase Authentication "supports authentication using passwords, popular federated identity providers like Google, Facebook and Twitter, and more." while the solution proposed above is only for Google accounts.
More recently, Google has published on its GCP Blog the detailed explanantion on how to authenticate users on Google App Engine using Firebase, but ... for Python only, see https://cloudplatform.googleblog.com/2016/10/how-to-authenticate-users-on-Google-App-Engine-using-Firebase.html. We are currently waiting for the same OFFICIAL explanations for Java! Hoping it will be published soon. |
You can do it like that using NConcern, a new open source AOP Framework on which I actively work.
public class Trigger<T> : Aspect
{
static public event EventArgs MethodCalled;
static private Trigger<T> m_Singleton = new Trigger<T>();
//Auto weaving aspect
static Trigger()
{
Aspect.Weave<Trigger<T>>(method => method.ReflectedType == typeof(T));
}
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//define an advice to trigger only when method execution not failed
yield return Advice.Basic.After.Returning(() =>
{
if (MethodCalled != null)
{
MethodCalled(this, null);
}
});
}
}
public class A
{
public void Test()
{
}
}
int main(string[] args)
{
Trigger<A>.MethodCalled += ...
new A().Test();
}
You can find a similar Example code source here : Example of observation pattern implemented with NConcern
NConcern AOP Framework is a light framework working at runtime. It work with code injection avoiding factory/proxy by inheritance. It allow you to add aspect to a class by injecting code you can create using simple delegate, ILGenerator or expression tree (linq) before/after or around a method. It can handle sealed class, sealed method, virtual method or explicit/implicit interface implementation.
Into my example, I create a class derived from Aspect (abstract class).
When a class derived from Aspect, it have to implement Advise method by returning an instance of Advice (Before/After/After.Returning/After.Throwing or Around). Each can be created with Delegate or Expression to define what you need to do on method interception.
public class MyAspect : IAspect
{
//this method is called initially (not on interception) to rewrite method body.
public IEnumerable<IAdvice> Advise(MethodInfo method)
{
//this block of code means that method will be rewrite to execute a write method name to console before original code only for public methods
if (method.IsPublic)
{
yield return Advice.Basic.Before(() => Console.WriteLine(method.Name));
}
}
}
Usage
//attach myaspect to A class. All methods of A will be passed to Advise method to process methods rewriting.
Aspect.Weave<MyAspect>(method => method.ReflectedType == typeof(A));
//detach myaspect from A class. All methods will be rewrite to give back original code.
Aspect.Release<MyAspect>(method => method.ReflectedType == typeof(A));
|
Authorize the User
You begin by trying to connect to RunKeeper. If the user previously authorized the app and the access token, is still available, the connection will happen immediately and without any intervention:
[[AppData sharedAppData].runKeeper tryToConnect:self];
If the user has not granted authorization OR the access token has been lost/deleted, your delegate method needsAuthentication will be called. In this method, you can request authorization via OAuth.
- (void)needsAuthentication {
[[AppData sharedAppData].runKeeper tryToAuthorize];
}
For login in purpose it's using OAuth so once the login is successful it will store the token and creds so you need to manually clear the keychain prefrences. For doing that check below:
Removing Accounts
To remove an account and its tokens from the store:
[[NXOAuth2AccountStore sharedStore] removeAccount:account];
Note that if you used a UIWebView to request access to a service as described above, it's likely that the token has been cached in [NSHTTPCookieStorage sharedHTTPCookieStorage]
You can remove the auth token from the cookie cache using:
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
if([[cookie domain] isEqualToString:@"myapp.com"]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
[[NSUserDefaults standardUserDefaults] synchronize];
Where myapp.com is the domain from which you received the auth token -- likley the authorizationURL assigned to the store at the time of request. As a convenience, you may want to store the domain of the token in the account.userData so that it is readily available if you need to delete the cookies. |
Opps!
Finally got solution.
The issue was in Amazon S3's CORSConfiguration
I don't know much about it, but now its allowing Cross-Origin from all browsers.
I have changes CORSConfiguration as :
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>https://myWebApp.net</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<ExposeHeader>x-amz-server-side-encryption</ExposeHeader>
<ExposeHeader>x-amz-request-id</ExposeHeader>
<ExposeHeader>x-amz-id-2</ExposeHeader>
</CORSRule>
</CORSConfiguration>
by this rules, browsers getting proper Request Headers and Response Headers.
Request Headers :
Host: myWebApp.s3.amazonaws.com
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:49.0) Gecko/20100101 Firefox/49.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Access-Control-Request-Method: GET
Access-Control-Request-Headers: x-requested-with
origin: https://myWebApp.net
Connection: keep-alive
Cache-Control: max-age=0
Response Headers :
Access-Control-Allow-Headers: x-requested-with
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Origin: https://myWebApp.net
Access-Control-Max-Age: 3000
Content-Length: 0
Date: Thu, 24 Nov 2016 13:21:17 GMT
Server: AmazonS3
Vary: Origin, Access-Control-Request-Headers, Access-Control-Request-Method
access-control-allow-credentials: true
access-control-expose-headers: x-amz-server-side-encryption, x-amz-request-id, x-amz-id-2
x-amz-id-2: emYYMILNIdkCejpjuDXz4Haks87asdhj/7JL5AASt/8eIwKdgO1Gb/AzGRg7SU/GH55IVopScg=
x-amz-request-id: 307572CDFF39F443
|
I think you are not following the authentication flow appropriately. After $auth_url = $client->createAuthUrl(); you have to be redirected to be authenticated and then you will get your access code. You have to use header('Location: ' . filter_var($auth_url, FILTER_SANITIZE_URL)); Try using this code instead.
<?php
require_once ('XXX/vendor/autoload.php');
$client = new Google_Client();
$client->setApplicationName("AdKeek");
$client->setAuthConfig('XXX/client_secrets.json');
$client->addScope("https://www.googleapis.com/auth/youtube.readonly");
$redirect_uri = 'XXX THIS PAGE';
$client->setRedirectUri($redirect_uri);
if (!isset($_GET['code'])) {
$auth_url = $client->createAuthUrl();
echo '<div class="col-xs-6 col-sm-3" style="padding-top: 10px;">
<a href="'.$auth_url.'" style="border-radius: 5px;padding-left: inherit;padding-top: 5px;padding-bottom: 5px;width: 127px; display: block;" class="yutub" ><i class="fa fa-youtube" aria-hidden="true"></i>
<span class="social-text">YouTube</span><i class="fa fa-link" aria-hidden="true" style="padding-left: 15px;"></i></a></div>';
} else {
$client->authenticate($_GET['code']);
//whatever else you want to do
}
?>
Now, if you already saved the access code, you don´t need to create an auth URL. Instead just grab the access code from the file and then use $client->authenticate($code); where $code = value from file. |
I face Authentication Proxy pop-up issue in my project. So I tried below solution and it is working fine.
When we run Script from Selenium Web driver on Security Environment following Setup needs to be done to handle Authentication Proxy.
First you need to know below details,
network.proxy.autoconfig_url (Example: "http://example.com/abc.pac")
network.proxy.http (Example: abc-proxy.com)
network.proxy.http_port (Example: 8080)
private static WebDriver initFirefoxDriver(String appURL)
{
System.out.println("Launching Firefox browser..");
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("network.proxy.type", 1);
firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://example.com/abc.pac");
firefoxProfile.setPreference("network.proxy.http", " abc-proxy.com");
firefoxProfile.setPreference("network.proxy.http_port", 8080);
WebDriver driver = new FirefoxDriver(firefoxProfile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to(appURL);
//driver.get(appURL);
return driver;
}
|
I was facing Authentication Proxy pop-up issue in my project. So I tried below solution and it is working fine.
When we run Script from Selenium Web driver on Security Environment following Setup needs to be done to handle Authentication Proxy.
First you need to know below details,
network.proxy.autoconfig_url (Example: http://example.com/abc.pac)
network.proxy.http (Example: abc-proxy.com)
network.proxy.http_port (Example: 8080)
private static WebDriver initFirefoxDriver(String appURL)
{
System.out.println("Launching Firefox browser..");
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("network.proxy.type", 1);
firefoxProfile.setPreference("network.proxy.autoconfig_url", "http://example.com/abc.pac");
firefoxProfile.setPreference("network.proxy.http", " abc-proxy.com");
firefoxProfile.setPreference("network.proxy.http_port", 8080);
WebDriver driver = new FirefoxDriver(firefoxProfile);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.navigate().to(appURL);
//driver.get(appURL);
return driver;
}
|
As Gaurav mentioned in another SO thread. We can switch to Azure Resource Manager API. Another important thing is that we also need to create service principal to access resources. We can use azure PowerShell command to do it easily. More detail steps about how to registry a web app in the Azure AD and create service principal please refer to article.
New-AzureRmRoleAssignment -RoleDefinitionName Contributor -ServicePrincipalName $app.ApplicationId.Guid
Microsoft.Azure.Management.WebSites SDK that implement WebApp Resource Management API. It is a pre-release version.
The following is my code sample:
var subscriptionId = "Your subscription Id";
var appId = "Application Id";
var appKey = "secret key";
var tenantId = "tenant id";
var serviceCreds = ApplicationTokenProvider.LoginSilentAsync(tenantId, appId, appKey).Result;
var webClient = new WebSiteManagementClient(serviceCreds) { SubscriptionId = subscriptionId };
var result = webClient.Sites.GetSiteConfigWithHttpMessagesAsync("ResourceGroup Name", "Web App name").Result;
Package file:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Azure.Management.Websites" version="1.3.2-preview" targetFramework="net452" />
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="2.28.1" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.1" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime.Azure" version="3.1.0" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.4.1-preview" targetFramework="net452" />
<package id="Newtonsoft.Json" version="6.0.8" targetFramework="net452" />
</packages>
Demo test result:
|
This is a dark corner of the servlet spec that is not well defined (and has had discussion on the servlet spec experts group mailing list as recently as a 2 months ago!)
The spec says the incoming URLs have to be "normalized" before being matched against a contextPath or urlPattern.
Normalization of a URI/URL is done for a number of reasons (spec requirements, security, prevent access outside of context, cleanup directory traversals, apply constraints correctly, etc..)
Things that are normalized (assuming 3 deployed contexts at /foo and /bar, and /):
/foo -> /foo/
/foo/../bar/ -> /bar/
/foo/../../../etc/passwd -> /etc/passwd
/foo/css//main.css -> /foo/css/main.css
/foo/app/./css/./widget.css -> /foo/app/css/widget.css
Then take this monster ...
/foo/context/.//..%2F..//./%62%61%72/context/servlet/info -> ??
Jetty currently normalizes this down to /bar/context/servlet/info, but the strictest interpretation of the servlet spec (a very unpopular interpretation among the servlet spec implementers!) says it should:
match on /foo context
getContextPath() returns /foo/context/.//..%2F..//./%62%61%72/context/servlet/info
getPathInfo() returns /context/.//..%2F..//./%62%61%72/context/servlet/info
This ugly part of the spec is very hostile towards security efforts and is likely going to be refined/clarified in Servlet 4.0 |
To answer your questions:
Is this a legitimate file (despite a possible infection)?
Yes, it's legitimate
It was infected?
Yes, it was infected
Is there good and bad (malware) code?
Malware is never good.
How can I remove the bad part?, just by deleting that line of code, with: script?
Yes, but you haven't solved the problem of how it got there in the first place.
How this code could got attached there?
What most likely happened, is that someone would have exploited some vulnerability in one of your outdated Drupal modules (or Drupal core) that allowed them to overwrite your html.tpl.php to include that script component.
To summarise what it's doing, that script tag is designed to make the browser of anyone who visits your site request a page from a completely different site. This kind of trick can be used to artificially inflate traffic numbers on other sites. Where it pays off for the author is in the fact that the other site's traffic figures will be artificially inflated.
This kind of tactic might be employed by people who charge people money to "drive traffic to their site", or by the site owner themselves, if they sell advertising on their webpage to other companies. The higher their traffic numbers, the more "exposure" advertisers get, the more money they could charge for advertising.
What you need to be concerned about is the fact that somewhere, there's a vulnerability on your site that allows people to overwrite files in your web folders however they want.
You need to do the following, or the problem will resurface:
Put your site into maintenance mode by navigating to /admin/config/development/maintenance
Back up your database and your web folder
Update Drupal's core files following these instructions: https://www.drupal.org/docs/7/updating-your-drupal-site/how-to-update-drupal-core
Update all your modules at /admin/modules/update/
Run database updates
Once confirming all module updates were successful, and assuming you don't get any errors, you can now turn maintenance mode off
Now, you also need to make sure you secure all your files and folders appropriately, by making sure that they're read-only (with the exception of where uploaded files are stored)
Then, assuming you're on your own server, you need to look into hardening whichever HTTP server you're using (Apache, Nginx, etc).
If you don't follow these steps, it's only a matter of time before some malware scans your server, finds the exact same vulnerability, and exploits it in a similar fashion.
Theoretically, you're lucky in that all it does is drive additional traffic to a different site. It could've been a lot worse. |
Here's a template to work with, it'll check every 120 seconds for changes in passed directory and notify on creation of directories,files,or names pipes. If you also want to run commands when something is removed then check my other answer on stackoverflow for additional looping examples.
#!/usr/bin/env bash
Var_dir="${1:-/tmp}"
Var_diff_sleep="${2:-120}"
Var_diff_opts="--suppress-common-lines"
Func_parse_diff(){
_added="$(grep -E '>' <<<"${@}")"
if [ "${#_added}" != "0" ]; then
mapfile -t _added_list <<<"${_added//> /}"
_let _index=0
until [ "${#_added_list[@]}" = "${_index}" ]; do
_path_to_check="${Var_dir}/${_added_list[${_index}]}"
if [ -f "${_path_to_check}" ]; then
echo "# File: ${_path_to_check}"
elif [ -d "${_path_to_check}" ]; then
echo "# Directory: ${_path_to_check}"
if [ -p "${_path_to_check}" ]; then
echo "# Pipe: ${_path_to_check}"
fi
let _index++
done
unset _index
fi
}
Func_watch_bulk_dir(){
_current_listing=""
while [ -d "${Var_dir}" ]; do
_new_listing="$(ls "${Var_dir}")"
_diff_listing="$(diff ${Var_dec_diff_opts} <(${Var_echo} "${_current_listing}") <(${Var_echo} "${_new_listing}"))"
if [ "${_diff_listing}" != "0" ]; then
Func_parse_diff "${_diff_listing}"
fi
_current_listing="${_new_listing}"
sleep ${Var_diff_sleep}
done
}
Hint if you replace the echo lines above with eval <some command> for each type of action monitored for you'll be all the closer to automation of actions. And if you wish to see what the above looks like when used within a script then check out the latest script version for the project I've been working on for automation of encryption and decryption via gpg and tar. |
The error is due to missing dependencies. Have you thought about using redshift-spark instead ?
To connect via redshift-spark, verify that you have these jar files in the spark home directory:
spark-redshift_2.10-3.0.0-preview1.jar
RedshiftJDBC41-1.1.10.1010.jar
hadoop-aws-2.7.1.jar
aws-java-sdk-1.7.4.jar
(aws-java-sdk-s3-1.11.60.jar) (newer version but not everything worked with it)
Put these jar files in $SPARK_HOME/jars/ and then start spark
pyspark --jars $SPARK_HOME/jars/spark-redshift_2.10-3.0.0-preview1.jar,$SPARK_HOME/jars/RedshiftJDBC41-1.1.10.1010.jar,$SPARK_HOME/jars/hadoop-aws-2.7.1.jar,$SPARK_HOME/jars/aws-java-sdk-s3-1.11.60.jar,$SPARK_HOME/jars/aws-java-sdk-1.7.4.jar
(SPARK_HOME should be = "/usr/local/Cellar/apache-spark/$SPARK_VERSION/libexec")
This will run Spark with all necessary dependencies. Note that you also need to specify the authentication type 'forward_spark_s3_credentials'=True if you are using awsAccessKeys.
from pyspark.sql import SQLContext
from pyspark import SparkContext
sc = SparkContext(appName="Connect Spark with Redshift")
sql_context = SQLContext(sc)
sc._jsc.hadoopConfiguration().set("fs.s3n.awsAccessKeyId", <ACCESSID>)
sc._jsc.hadoopConfiguration().set("fs.s3n.awsSecretAccessKey", <ACCESSKEY>)
df = sql_context.read \
.format("com.databricks.spark.redshift") \
.option("url", "jdbc:redshift://example.coyf2i236wts.eu-central- 1.redshift.amazonaws.com:5439/agcdb?user=user&password=pwd") \
.option("dbtable", "table_name") \
.option('forward_spark_s3_credentials',True) \
.option("tempdir", "s3n://bucket") \
.load()
Common errors afterwards are:
Redshift Connection Error: "SSL off"
Solution:
.option("url", "jdbc:redshift://example.coyf2i236wts.eu-central- 1.redshift.amazonaws.com:5439/agcdb?user=user&password=pwd?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory")
S3 Error: When unloading the data, e.g. after df.show() you get the message: "The bucket you are attempting to access must be addressed using the specified endpoint. Please send all future requests to this endpoint."
Solution: The bucket & cluster must be run within the same region
|
On my Phone Apps I call server side APIs using https. I have provided sample code here of how I authorize users...this code has been modified so as not to show my actual process. You'll have to modify it to meet your needs. But it does show an approach that calls web services only.
On your Service Side create the following Attribute:
using System.Text;
using System.Security.Cryptography;
using System.Web.Http.Filters;
using System.Web.Http.Controllers;
using System.Net.Http;
public class RequireHttpsAttribute : AuthorizationFilterAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
if (actionContext.Request.RequestUri.Scheme !=Uri.UriSchemeHttps)
{
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
else
{
string UserName;
String Password;
if (actionContext.Request.Headers.Any(p => p.Key == "UserName") &&
actionContext.Request.Headers.Any(p => p.Key == "UserName"))
{
UserName = actionContext.Request.Headers.Where(p => p.Key == "UserName").FirstOrDefault().Value.FirstOrDefault();
Password = actionContext.Request.Headers.Where(p => p.Key == "UserName").FirstOrDefault().Value.FirstOrDefault();
//do authentication stuff here..
If(Authorized())
{
base.OnAuthorization(actionContext);
return;
}
Else
{
actionContext.Response = new HttpResponseMessage (System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "Invalid User or Password"
};
}
}
actionContext.Response = new HttpResponseMessage(System.Net.HttpStatusCode.Forbidden)
{
ReasonPhrase = "HTTPS Required"
};
}
}
return ReasonPhrase;
}
On your client side make request like this:
string ResponseText= String.Empty();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://YOURAPI/");
client.DefaultRequestHeaders.Accept.Clear();
//client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue ("text/json"));
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
client.DefaultRequestHeaders.Add("UserName", UserName);
client.DefaultRequestHeaders.Add("Password", Password);
// New code:
HttpResponseMessage response = await client.GetAsync ("api/YOURAPIENDPOINT").ConfigureAwait(continueOnCapturedContext: false);
if (response.IsSuccessStatusCode)
{
ResponseText = await response.Content.ReadAsStringAsync();
}
}
The API method should look something like this:
[RequireHttps]
public YOURAPI Get(int id)
{
//if you got this far then the user is authorized.
}
Your mileage may vary. I have not tested this code as modified. But you should get the idea of how to accomplish what you want. |
I found a way to resolve the issue. Below is code that will help you cancel authentication challenge. I don't recommend this, this useful for temporary solution. The best thing to do is still validate the authentication challenge fully.
let manager: SessionManager = SessionManager(configuration: configuration, serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies))
manager.delegate.sessionDidReceiveChallenge = { session, challenge in
var disposition: URLSession.AuthChallengeDisposition = .cancelAuthenticationChallenge
var credential: URLCredential?
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
disposition = URLSession.AuthChallengeDisposition.useCredential
credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
} else {
if challenge.previousFailureCount > 0 {
disposition = .cancelAuthenticationChallenge
} else {
credential = manager.session.configuration.urlCredentialStorage?.defaultCredential(for: challenge.protectionSpace)
if credential != nil {
disposition = .useCredential
}
}
}
return (disposition, credential)
}
return manager
}
|
I assume by this code:
if(isset($_POST['q'])){ // get the name from html form for go to a function of this class
$settings->$_POST['q']($conexion);
}
And submitting the hidden form field called q with value proofQueries, you are trying to call $settings->proofQueries($conexion). This is an extremely bad idea.
You are effectively executing code that comes directly from client side, which is a HUGE vulnerability risk.
It seems like a strange approach to begin with to specify the function client side, and then execute it in PHP (i.e. server side). Why specifying the q value at all, instead of just explicitly doing $settings->proofQueries($conexion) in PHP?
If you somehow must specify the function to be called client side, do something like this:
if(isset($_POST['q'])){ // get member function from submitted form
$f = $_POST['q'];
if ($f=='proofQueries') {
$settings->proofQueries($conexion);
}
else {
die("Nope");
}
}
Or if you have multiple possible functions, explicitly filter them with a whitelist to make absolutely 100% sure that ONLY the function names you decide can be called:
if(isset($_POST['q'])){ // get member function from submitted form
$f = $_POST['q'];
$allowedFunctions = array('proofQueries','doSomething','otherFunction');
if (in_array($f,$allowedFunctions)) {
$settings->$f($conexion);
}
else {
die("Nope");
}
}
But again, it seems like a strange approach alltogether. You should not specify server side specific implementation details through client side. |
Got it working via first a mount of the NFS share in the playbook. The copy tasks executes ok according to the output but the files aren't copied over.?!
This is the copy task
- name: copy install files
copy:
src: "/mnt"
dest: "/tmp/INSTALL_{{ ansible_fqdn }}/{{ item }}"
group: install
owner: setup
mode: 0777
with_items:
- p1.zip
- p2.zip
- p3.zip
The folder /tmp/INSTALL_{{ ansible_fqdn }} is created but no files are copied.
With -vvv I get :
ESTABLISH SSH CONNECTION FOR USER: None
SSH: EXEC ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/home/setup/.ansible/cp/ansible-ssh-%h-%p-%r '/bin/sh -c '"'"'( umask 77 && mkdir -p "echo $HOME/.ansible/tmp/ansible-tmp-1480262122.31-14572056940306" && echo ansible-tmp-1480262122.31-14572056940306="echo $HOME/.ansible/tmp/ansible-tmp-1480262122.31-14572056940306" ) && sleep 0'"'"''
Edit:
I tried it now with synchronize module
- name: Transfer file
synchronize:
src: "/IP address/oracle"
dest: "/tmp/INSTALL_{{ ansible_fqdn }}/"
But then I got the following msg:
"msg": "sudo: sorry, you must have a tty to run sudo\nrsync: connection unexpectedly closed (0 bytes received so far) [sender]\nrsync error: error in rsync protocol data stream (code 12)
I commented out in sudoers "# Defaults requiretty" on both servers |
I've just answered a very similar question a few minutes ago.
SSL is the standard. It provides:
Confidentiality: the data is encrypted between the client and the server and cannot be read by an attacker. Typically uses the RSA
algorithm.
Integrity: an attacker cannot tamper with the messages sent between the client and the server. Typically implemented using
HMAC
Authentication: the browser is able to check that the server it is talking to is actually yours, and not an attacker. Basically, the
server shows to the browser a certificate signed by the Certificate
Authority having issued the SSL certificate (e.g. VeriSign), that
proves its identity.
All that is assuming SSL is configured properly on the server's side:
up-to-date ciphers, no support for outdated ones, proper key length
(2048 bits or higher), etc.
You can use SSL Labs to check if your SSL configuration looks
secure. Also, be sure to enforce your users to use SSL, for instance
by automatically redirecting http:// URLs to https:// ones.
|
void stringuniz(char *);
int *x;
int main(){
[...]
}
void stringuniz(char *s){
[...]
}
I don't know why many ppl teach it this way, but there is absolute no use in having main somewhere in the middle of a source file, and putting it at the end also allows you to get rid of the forward declarations. So, I would write it this way:
int *x;
void stringuniz(char *s){
[...]
}
int main(){
[...]
}
Then you should start using the space character more.
stringuniz(s);
for(i=0;i<(sizeof(x)/sizeof(int));i++)
printf("%d",x[i]);
In a comment, alain already pointed out, that sizeof(x) will return the size of a pointer. So, you need a different way to figure out the size of the array. One way is to add a variable size_t x_len; besides int * x;. Also, you should use curley brackets even for one line statements, believe me, not only makes it the code more readable, it also prevents introducing bugs on later changes.
for (i = 0; i < x_len; i++) {
printf("%d", x[i]);
}
.
void stringuniz(char *s){
int duz,c=0,i,j,k=0,m=0;
char b[10];
b will hold the word the user enters. If his word is longer then 9 characters, you get a buffer overflow here.
duz=strlen(s);
for(i=0;i<duz;i++)
if(s[i]=='_')
c++;
You are counting the number of words here. So, please use more descriptive names like num_words instead of c. BTW: This is the x_len mentioned above.
x=(int*)malloc((c+1)*sizeof(int));
No need to cast return value of malloc. Actually it might hide bugs. Also, I would use sizeof(*x) instead of sizeof(int), because if you change the type of x, in your statement, you also would have to change the malloc call. In my statement, the malloc call doesn't need to be touched in any way.
x = malloc((c+1) * sizeof(*x));
if(x==NULL) exit(1);
for(i=0;i<c+1;i++){
for(j=m;j<duz;j++){
if(s[j]!='_'){
b[k++]=s[j];
You are constantly overwriting b with the next word being read. Since you're not using it anyway, you can just skip this line.
m++;
}
else{
b[k]='\0';
x[i]=atoi(b);
k=0;
m++;
break;
And this break; only breaks out of the innermost for (j-loop.
}
}
}
}
|
@Emlinux
This's piece of code that i've implemented for printer. Hope this will help you figure it out ;)
private string deviceName;
private string rfCommName;
private string rfCommId;
private object rfCommProperty;
private bool rfCommAvalability;
private PeerInformation device;
private HostName hostName;
private StreamSocket streamSocket = null;
private DataWriter dataWriter;
private RfcommDeviceService rfcommService;
private DeviceInformation deviceInformation;
private DeviceInformationCollection deviceInformationCollection;
private static readonly Guid RfcommSerialUuid = Guid.Parse("00001101-0000-1000-8000-00805f9b34fb");
public MainPage()
{
this.InitializeComponent();
this.NavigationCacheMode = NavigationCacheMode.Required;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
}
private async void searchButton_Click(object sender, RoutedEventArgs e)
{
PeerFinder.AlternateIdentities["Bluetooth:PAIRED"] = "";
var serviceInfoCollection = await PeerFinder.FindAllPeersAsync();
if (serviceInfoCollection.Count > 0)
{
Debug.WriteLine("Search() - There's few paired devices");
foreach (var peerInfo in serviceInfoCollection)
{
if (peerInfo.DisplayName.ToLower().IndexOf("star-") > -1)
{
hostName = peerInfo.HostName;
deviceName = peerInfo.DisplayName;
device = peerInfo;
Debug.WriteLine("Search() - There's your star printer");
Debug.WriteLine("Search() - Device - " + deviceName);
Debug.WriteLine("Search() - Hostname - " + hostName);
textBlock.Text = "I've found ur printer: " + deviceName;
break;
}
}
}
else
{
Debug.WriteLine("Search() - There's no paired devices");
textBlock.Text = "I didn't found ur printer";
}
}
private async void rfcommButton_Clicked(object sender, RoutedEventArgs e)
{
Debug.WriteLine("RfComm() - I'm going to check all Rfcomm devices");
deviceInformationCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.FromUuid(RfcommSerialUuid)));
if (deviceInformationCollection != null)
{
foreach (var rfComm in deviceInformationCollection)
{
if (rfComm.Name.ToLower().IndexOf("star-") > -1)
{
rfCommName = rfComm.Name;
rfCommId = rfComm.Id;
rfCommProperty = rfComm.Properties;
rfCommAvalability = rfComm.IsEnabled;
Debug.WriteLine("RfComm() - name - " + rfCommName);
Debug.WriteLine("RfComm() - id - " + rfCommId);
Debug.WriteLine("RfComm() - property - " + rfCommProperty);
Debug.WriteLine("RfComm() - avalability - " + rfCommAvalability);
deviceInformation = rfComm;
}
}
}
try
{
rfcommService = await RfcommDeviceService.FromIdAsync(rfCommId);
Debug.WriteLine("RfComm() - seems like we're at home");
textBlock.Text = "seems liek we're at home";
}
catch (Exception)
{
Debug.WriteLine("RfComm() - access to the device is denied");
textBlock.Text = "access to the device is denied";
}
}
private void socketButton_Click(object sender, RoutedEventArgs e)
{
if (streamSocket == null)
{
Debug.WriteLine("Socket() - socket's null");
lock (this)
{
streamSocket = new StreamSocket();
Debug.WriteLine("Socket() - socket created");
textBlock.Text = "socket created";
}
}
try
{
dataWriter = new DataWriter(streamSocket.OutputStream);
Debug.WriteLine("Socket() - data writer created");
}
catch (Exception)
{
Debug.WriteLine("Socket() - something went wrong while creating writer");
textBlock.Text = "something went wront while socket creation";
}
}
private async void connectToButton_Click(object sender, RoutedEventArgs e)
{
try
{
Debug.WriteLine("Connect() - Trying to connect");
await streamSocket.ConnectAsync(hostName, rfcommService.ConnectionServiceName, SocketProtectionLevel.BluetoothEncryptionAllowNullAuthentication);
Debug.WriteLine("Connect() - Connected");
textBlock.Text = "Connected";
}
catch (Exception)
{
Debug.WriteLine("Connect() - Couldn't connect");
textBlock.Text = "Couldn't connect";
}
}
|
SOLVED: The problem was the function
Private Declare PtrSafe Function CryptHashData Lib "advapi32.dll" _
(ByVal hHash As LongPtr, pbData As Any, ByVal cbData As Long, ByVal dwFlags As Long) As Long
was completely wrong because is written to accept BYTE type and not STRING data.
Exact is
For 64 Bit:
Private Declare PTRSAFE Function CryptHashData Lib "advapi32.dll" _
(ByVal hHash As Longptr, _
ByVal pbData As String, _
ByVal dwDataLen As Long, _
ByVal dwFlags As Long) As Long
For 32 BIT:
Private Declare Function CryptHashData Lib "advapi32.dll" _
(ByVal hHash As Long, _
ByVal pbData As String, _
ByVal dwDataLen As Long, _
ByVal dwFlags As Long) As Long
Following is the definitely listing. Thanks to all.
Option Explicit
#If Win64 Then
Private Declare PtrSafe Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" _
(ByRef phProv As LongPtr, ByVal pszContainer As String, ByVal pszProvider As String, _
ByVal dwProvType As Long, ByVal dwFlags As Long) As Long
Private Declare PtrSafe Function CryptReleaseContext Lib "advapi32.dll" _
(ByVal hProv As LongPtr, ByVal dwFlags As Long) As Long
Private Declare PtrSafe Function CryptCreateHash Lib "advapi32.dll" _
(ByVal hProv As LongPtr, ByVal algid As Long, ByVal hKey As LongPtr, ByVal dwFlags As Long, _
ByRef phHash As LongPtr) As Boolean
Private Declare PtrSafe Function CryptDestroyHash Lib "advapi32.dll" _
(ByVal hHash As LongPtr) As Long
Private Declare PtrSafe Function CryptHashData Lib "advapi32.dll" _
(ByVal hHash As Long, _
ByVal pbData As String, _
ByVal dwDataLen As Long, _
ByVal dwFlags As Long) As Long
Private Declare PtrSafe Function CryptGetHashParam Lib "advapi32.dll" _
(ByVal hHash As LongPtr, ByVal dwParam As Long, pbData As Any, ByRef pcbData As Long, _
ByVal dwFlags As Long) As Long
Private Declare PtrSafe Function CryptDeriveKey Lib "advapi32.dll" _
(ByVal hProv As LongPtr, ByVal algid As Long, ByVal hBaseData As LongPtr, ByVal dwFlags As Long, _
ByRef phKey As LongPtr) As Long
Private Declare PtrSafe Function CryptDestroyKey Lib "advapi32.dll" _
(ByVal hKey As LongPtr) As Long
Private Declare PtrSafe Function CryptEncrypt Lib "advapi32.dll" _
(ByVal hKey As LongPtr, ByVal hHash As LongPtr, ByVal Final As Boolean, ByVal dwFlags As Long, _
ByVal pbData As String, ByRef pdwDataLen As Long, ByVal dwBufLen As Long) As Long
Private Declare PtrSafe Function CryptDecrypt Lib "advapi32.dll" _
(ByVal hKey As LongPtr, _
ByVal hHash As LongPtr, _
ByVal Final As Boolean, _
ByVal dwFlags As Long, _
ByVal pbData As String, _
ByRef pdwDataLen As Long) As Boolean
Private Declare PtrSafe Function CryptGetProvParam Lib "advapi32.dll" _
(ByVal hProv As LongPtr, _
ByVal dwParam As Long, _
ByRef pbData As Any, _
ByRef pdwDataLen As Long, _
ByVal dwFlags As Long) As Long
#Else
Private Declare Function CryptAcquireContext Lib "advapi32.dll" Alias "CryptAcquireContextA" _
(ByRef phProv As Long, ByVal pszContainer As String, ByVal pszProvider As String, _
ByVal dwProvType As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptReleaseContext Lib "advapi32.dll" _
(ByVal hProv As Long, ByVal dwFlags As Long) As Long
Private Declare Function CryptCreateHash Lib "advapi32.dll" _
(ByVal hProv As Long, ByVal Algid As Long, ByVal hKey As Long, ByVal dwFlags As Long, _
ByRef phHash As Long) As Long
Private Declare Function CryptDestroyHash Lib "advapi32.dll" _
(ByVal hHash As Long) As Long
Private Declare PtrSafe Function CryptHashData Lib "advapi32.dll" _
(ByVal hHash As Long, _
ByVal pbData As String, _
ByVal dwDataLen As Long, _
ByVal dwFlags As Long) As Long
Private Declare Function CryptGetHashParam Lib "advapi32.dll" _
(ByVal hHash As Long, ByVal dwParam As Long, pbData As Any, ByRef pcbData As Long, _
ByVal dwFlags As Long) As Long
Private Declare Function CryptDeriveKey Lib "advapi32.dll" _
(ByVal hProv As Long, ByVal Algid As Long, ByVal hBaseData As Long, ByVal dwFlags As Long, _
ByRef phKey As Long) As Long
Private Declare Function CryptDestroyKey Lib "advapi32.dll" _
(ByVal hKey As Long) As Long
Private Declare Function CryptEncrypt Lib "advapi32.dll" _
(ByVal hKey As Long, ByVal hHash As Long, ByVal Final As Long, ByVal dwFlags As Long, _
ByVal pbData As String, ByRef pdwDataLen As Long, ByVal dwBufLen As Long) As Long
Private Declare Function CryptDecrypt Lib "advapi32.dll" _
(ByVal hKey As Long, _
ByVal hHash As Long, _
ByVal Final As Long, _
ByVal dwFlags As Long, _
ByVal pbData As String, _
ByRef pdwDataLen As Long) As Long
Private Declare Function CryptGetProvParam Lib "advapi32.dll" _
(ByVal hProv As Long, _
ByVal dwParam As Long, _
ByRef pbData As Any, _
ByRef pdwDataLen As Long, _
ByVal dwFlags As Long) As Long
#End If
Private Const SERVICE_PROVIDER As String = "Microsoft Base Cryptographic Provider v1.0"
Private Const KEY_CONTAINER As String = "Metallica"
Private Const PROV_RSA_FULL As Long = 1
Private Const PP_NAME As Long = 4
Private Const PP_CONTAINER As Long = 6
Private Const CRYPT_NEWKEYSET As Long = 8
Private Const ALG_CLASS_DATA_ENCRYPT As Long = 24576
Private Const ALG_CLASS_HASH As Long = 32768
Private Const ALG_TYPE_ANY As Long = 0
Private Const ALG_TYPE_STREAM As Long = 2048
Private Const ALG_SID_RC4 As Long = 1
Private Const ALG_SID_MD5 As Long = 3
Private Const CALG_MD5 As Long = ((ALG_CLASS_HASH Or ALG_TYPE_ANY) Or ALG_SID_MD5)
Private Const CALG_RC4 As Long = ((ALG_CLASS_DATA_ENCRYPT Or ALG_TYPE_STREAM) Or ALG_SID_RC4)
Private Const ENCRYPT_ALGORITHM As Long = CALG_RC4
Private Const NUMBER_ENCRYPT_PASSWORD As String = "´o¸sçPQ]"
#If VBA7 And Win64 Then
Private hCryptProv As LongPtr
#Else
Private hCryptProv As Long
#End If
Public Function EncryptionCSPConnect() As Boolean
'Function Adapted
'Get handle to CSP
If CryptAcquireContext(hCryptProv, KEY_CONTAINER, SERVICE_PROVIDER, PROV_RSA_FULL, CRYPT_NEWKEYSET) = 0 Then
If CryptAcquireContext(hCryptProv, KEY_CONTAINER, SERVICE_PROVIDER, PROV_RSA_FULL, 0) = 0 Then
HandleError "Error during CryptAcquireContext for a new key container." & vbCrLf & _
"A container with this name probably already exists."
EncryptionCSPConnect = False
Exit Function
End If
End If
EncryptionCSPConnect = True
End Function
Public Sub EncryptionCSPDisconnect()
'Release provider handle.
'Function Adapted
If hCryptProv <> 0 Then
CryptReleaseContext hCryptProv, 0
End If
End Sub
Public Function EncryptData(ByVal data As String, ByVal Password As String) As String
Dim sEncrypted As String
Dim lEncryptionCount As Long
Dim sTempPassword As String
'It is possible that the normal encryption will give you a string
'containing cr or lf characters which make it difficult to write to files
'Do a loop changing the password and keep encrypting until the result is ok
'To be able to decrypt we need to also store the number of loops in the result
'Try first encryption
lEncryptionCount = 0
sTempPassword = Password & lEncryptionCount
sEncrypted = EncryptDecrypt(data, sTempPassword, True)
'Loop if this contained a bad character
Do While (InStr(1, sEncrypted, vbCr) > 0) _
Or (InStr(1, sEncrypted, vbLf) > 0) _
Or (InStr(1, sEncrypted, Chr$(0)) > 0) _
Or (InStr(1, sEncrypted, vbTab) > 0)
'Try the next password
lEncryptionCount = lEncryptionCount + 1
sTempPassword = Password & lEncryptionCount
sEncrypted = EncryptDecrypt(data, sTempPassword, True)
'Don't go on for ever, 1 billion attempts should be plenty
If lEncryptionCount = 99999999 Then
Err.Raise vbObjectError + 999, "EncryptData", "This data cannot be successfully encrypted"
EncryptData = ""
Exit Function
End If
Loop
'Build encrypted string, starting with number of encryption iterations
EncryptData = EncryptNumber(lEncryptionCount) & sEncrypted
End Function
Public Function DecryptData(ByVal data As String, ByVal Password As String) As String
Dim lEncryptionCount As Long
Dim sDecrypted As String
Dim sTempPassword As String
'When encrypting we may have gone through a number of iterations
'How many did we go through?
lEncryptionCount = DecryptNumber(Mid$(data, 1, 8))
'start with the last password and work back
sTempPassword = Password & lEncryptionCount
sDecrypted = EncryptDecrypt(Mid$(data, 9), sTempPassword, False)
DecryptData = sDecrypted
End Function
Public Function GetCSPDetails() As String
Dim lLength As Long
Dim yContainer() As Byte
If hCryptProv = 0 Then
GetCSPDetails = "Not connected to CSP"
Exit Function
End If
'For developer info, show what the CSP & container name is
lLength = 1000
ReDim yContainer(lLength)
If CryptGetProvParam(hCryptProv, PP_NAME, yContainer(0), lLength, 0) <> 0 Then
GetCSPDetails = "Cryptographic Service Provider name: " & ByteToStr(yContainer, lLength)
End If
lLength = 1000
ReDim yContainer(lLength)
If CryptGetProvParam(hCryptProv, PP_CONTAINER, yContainer(0), lLength, 0) <> 0 Then
GetCSPDetails = GetCSPDetails & vbCrLf & "Key Container name: " & ByteToStr(yContainer, lLength)
End If
End Function
Private Function EncryptDecrypt(ByVal data As String, ByVal Password As String, ByVal encrypt As Boolean) As String
#If Win64 Then
Dim hHash As LongPtr
Dim hKey As LongPtr
Dim hHashNull As LongPtr
Dim hKeyNull As LongPtr
hHashNull = 0&
hKeyNull = 0&
#Else
Dim hHash As Long
Dim hKey As Long
Dim hHashNull As Long
Dim hKeyNull As Long
#End If
Dim lLength As Long
Dim sTemp As String
Dim GetValue As Boolean
If hCryptProv = 0 Then
HandleError "Not connected to CSP"
Exit Function
End If
'--------------------------------------------------------------------
'The data will be encrypted with a session key derived from the
'password.
'The session key will be recreated when the data is decrypted
'only if the password used to create the key is available.
'--------------------------------------------------------------------
'Create a hash object.
GetValue = CryptCreateHash(hCryptProv, CALG_MD5, hKeyNull, 0, hHash)
If GetValue = False Then
HandleError "Error during CryptCreateHash!"
End If
'Hash the password.
If CryptHashData(hHash, Password, Len(Password), 0) = 0 Then
HandleError "Error during CryptHashData."
End If
'Derive a session key from the hash object.
If CryptDeriveKey(hCryptProv, ENCRYPT_ALGORITHM, hHash, 0, hKey) = 0 Then
HandleError "Error during CryptDeriveKey!"
End If
'Do the work
sTemp = data
lLength = Len(data)
If encrypt Then
'Encrypt data.
If CryptEncrypt(hKey, hHashNull, True, 0, sTemp, lLength, lLength) = 0 Then
HandleError "Error during CryptEncrypt."
End If
Else
'Encrypt data.
GetValue = CryptDecrypt(hKey, hHashNull, True, 0, sTemp, lLength)
If GetValue = 0 Then
HandleError "Error during CryptDecrypt."
End If
End If
'This is what we return.
EncryptDecrypt = Mid$(sTemp, 1, lLength)
'Destroy session key.
If hKey <> 0 Then
CryptDestroyKey hKey
End If
'Destroy hash object.
If hHash <> 0 Then
CryptDestroyHash hHash
End If
End Function
Private Sub HandleError(ByVal error As String)
'You could write the error to the screen or to a file
Debug.Print error
End Sub
Private Function ByteToStr(ByRef ByteArray() As Byte, ByVal lLength As Long) As String
Dim i As Long
For i = LBound(ByteArray) To (LBound(ByteArray) + lLength)
ByteToStr = ByteToStr & Chr$(ByteArray(i))
Next i
End Function
Private Function EncryptNumber(ByVal lNumber As Long) As String
Dim i As Long
Dim sNumber As String
sNumber = Format$(lNumber, "00000000")
For i = 1 To 8
EncryptNumber = EncryptNumber & Chr$(Asc(Mid$(NUMBER_ENCRYPT_PASSWORD, i, 1)) + Val(Mid$(sNumber, i, 1)))
Next i
End Function
Private Function DecryptNumber(ByVal sNumber As String) As Long
Dim i As Long
For i = 1 To 8
DecryptNumber = (10 * DecryptNumber) + (Asc(Mid$(sNumber, i, 1)) - Asc(Mid$(NUMBER_ENCRYPT_PASSWORD, i, 1)))
Next i
End Function
|
OK, found the solution: I launched the cluster with M3Xlarge instances instead of M2Medium. Works like a charm!
How I got to this:
Since I managed to launch clusters in N. Virginia with the default IAM roles for EMR, I started to think that I may have problems with authentication. This was further supported when I managed to launch a cluster in Frankfurt via CLI (found the example here under Create and Use IAM Roles with the AWS CLI).
What I did next was trying to re-launch the cluster via the SDK. The cluster failed, but I copied the launch commands so I could launch via the CLI. To do this, I clicked on the cluster in the EMR cluster list (web interface), clicked on View cluster details and then at the button on the top row AWS CLI export.
To my amazement, the CLI provided much more specific error messages (in comparison with the web interface, which listed a validation error), which indicated that the culprit is the instance type! I then checked here to find out which instances are available in Frankfurt, and selected one that didn't require VPC (M4 requires it), since I didn't have the energy to start messing with that stuff.
A bit of prelude - the listed validation error caused me to find this. It was this question that led me to research the issue of default IAM roles, and to try and use the CLI.
|
maybe it can help you
<?php
$serverName = "localhost"; //serverName\instanceName
// Since UID and PWD are not specified in the $connectionInfo array,
// The connection will be attempted using Windows Authentication.
$connectionInfo = array( "Database"=>"jdih");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
echo "Connection established.<br />";
}else{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
function count_data($var)
{
$serverName = "localhost";
$connectionInfo = array( "Database"=>"jdih");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$sql = "SELECT count(*) total from test where parent_id = '".$var."'";
$stmt = sqlsrv_query( $conn, $sql );
$rowChild = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC);
return $rowChild['total'];
}
$sql = "SELECT id from test where parent_id = 0";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$totalchild = count_data($row['id']);
if($totalchild > 0){
$sqlchild = "select id from test where parent_id = '".$row['id']."'";
$stmtchild = sqlsrv_query( $conn, $sqlchild);
while( $rowChild = sqlsrv_fetch_array( $stmtchild, SQLSRV_FETCH_ASSOC) ){
//
$totalchild2 = count_data($rowChild['id']);
if($totalchild2 > 0){
$sqlchild2 = "select id from test where parent_id = '".$rowChild['id']."'";
$stmtchild2 = sqlsrv_query( $conn, $sqlchild2);
while( $rowChild2 = sqlsrv_fetch_array( $stmtchild2, SQLSRV_FETCH_ASSOC) ){
echo $row['id']. ' Has ' . $rowChild['id'].' has '.$rowChild2['id']. '<br>';
}
}else{
echo $row['id']. ' Has ' . $rowChild['id'].'<br>';
}
}
}else{
echo $row['id']. ' Has nothing';
}
}
?>
here is an example,i'm using sql. It's not dynamic but if only two level maybe it will help. You can add conditional check if that has child.
sorry bad english |
The solution I came up with, but I'm open to other ideas.
In web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.web>
<compilation strict="false" explicit="true" debug="true" targetFramework="4.5.2" />
<customErrors mode="Off" />
<authentication mode="Windows" />
<httpRuntime targetFramework="4.5.2" />
<!-- Required for Web Services via Handlers -->
<webServices>
<protocols>
<add name="HttpGet" />
<add name="HttpPost" />
</protocols>
</webServices>
</system.web>
<system.webServer>
<handlers>
<add verb="GET,POST" name="Test" type="MyApp.Test" path="Test" />
</handlers>
<modules>
<add name="AppModule" type="MyApp.AppModule" />
</modules>
<defaultDocument enabled="false" />
<directoryBrowse enabled="false" />
</system.webServer>
</configuration>
And then added the AppModule class where I evaluate HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath and do a HttpContext.Current.RewritePath so the handler defined above will pick it up.
my.example.com
my.example.com/AnyFolder/MyApplication
Matching for "~/" works if the web app is at the site root in IIS or is set up as an app within a site:
Public Class AppModule
Implements IHttpModule
Friend WithEvents WebApp As HttpApplication
Public Sub Init(ByVal HttpApplication As HttpApplication) _
Implements IHttpModule.Init
WebApp = HttpApplication
End Sub
Private Sub WebApp_BeginRequest(sender As Object, e As EventArgs) _
Handles WebApp.BeginRequest
With HttpContext.Current
If .Request.AppRelativeCurrentExecutionFilePath = "~/" Then .RewritePath("~/Test")
End With
End Sub
Public Sub Dispose() _
Implements IHttpModule.Dispose
Throw New NotImplementedException()
End Sub
End Class
|
The following suppose that you have the control in the deployment of the database, the website.
For a Winforms application and depending your database, but let assume that it is SQL SERVER, you should use integrated security and let Windows do this dirty job.
If you can't use integrated security (client are not on the same domain than the database), you should ask the user to insert their credential on first use, store theses data in a secure place and build the connection string by hand. Have a look to the ProtectedData Class and the Data Protection API (DPAPI) for storing these kind of data.
https://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata(v=vs.110).aspx
For a website application, you could use database integrated security too with the credential of the IIS User or with the client windows authentication if they have one. As the config file of the website should not be visible to the client it is not the biggest security issue if it contains some credential.
As I'm not a guru of ASP.Net, you should not rely only on my experience. |
You question is a little board, and so the answer is a little general. but there are a couple approaches;
option 1. remove the Changelog and Licence files? if these are yii install changelog and licence then they dont need to be left on the server. just ensure you complying with the licence requirements.
option 2.
you mentioned "guest user" which htaccess is not going to integrate well with yii for authorized users. you could move the files into a folder with a .htaccess containing a single line Deny from all. this blocks everyone except the PHP executed on your server.
you can now create a method/action in a controller which just echos the file contents. file-get-contents or readfile. wrap this your authentication so only non-guest users are able to use the method.
if there are only two static files, then maybe just an 'action' for each. if its many files that are changing names etc, then you accept an id to the controller pass to a model that uses scandir and checks the file really exists and spits out your output to view.
option 2.1
instead of folder with a .htaccess you could also move the files to the parent of the webhost base dir if you have this access. this means that your webserver can not serve the file, but the php can still reach it with local paths.
option 3
in .htaccess you can use AuthType basic and will invoke your webserver to prompt the user for username and password as configured in the .htaccess. this is problematic as the interface is not user friendly and is very difficult to integrate with your webapps user db.
option 4
.htaccess can support other AuthTypes but option 2 becomes much easier at this point. |
If you want to make your API a first-class citizen in your system and have it require access tokens that are specifically issued to it instead of accepting Google authentication related tokens that were issued to your client application then you need to have an authorization server that specifically issues tokens for your API.
This authorization server can still delegate user authentication to Google, but then after verifying the user identity it will issue API specific access tokens that better satisfy your requirements, like for example, including specific scopes then used by your API to perform authorization decisions.
For a more complete description of this scenario you can check Auth0 Mobile + API architecture scenario.
In this scenario you have a mobile application ("Client") which talks to an API ("Resource Server"). The application will use OpenID Connect with the Authorization Code Grant using Proof Key for Code Exchange (PKCE) to authenticate users.
The information is Auth0 specific and you can indeed use Auth0 as an authorization server for your own API while still maintaining Google authentication support, however, most of the theory would also apply to any OAuth 2.0 compliant provider.
Disclosure: I'm an Auth0 engineer. |
I do not believe there is any issues with the create draft reply API.
I was able to test this API call using a Native Client I registered in my tenant (with mail.readwrite scope registered), and a PowerShell script using ADAL which did Authentication and the REST call.
Here is that script:
Add-Type -Path "..\ADAL\Microsoft.IdentityModel.Clients.ActiveDirectory.dll";
$output = ".\Output.txt"
$accessToken = ".\Token.txt"
$clientId = "<AppID>";
$tenantId = "<Tenant or Common>";
$resourceId = "https://outlook.office.com"
$redirectUri = new-object System.Uri("<Reply URL>")
$login = "https://login.microsoftonline.com"
$authContext = New-Object Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext @(("{0}/{1}" -f $login,$tenantId), $false);
$authenticationResult = $authContext.AcquireToken($resourceId,$clientID,$redirectUri);
($token = $authenticationResult.AccessToken) | Out-File $accessToken
$headers = @{
"Authorization" = ("Bearer {0}" -f $token);
"Content-Type" = "application/json";
}
$body = @{
Comment= 'This is my comment'
}
$bodyJSON = $body | ConvertTo-Json
Invoke-RestMethod -Method Post -Uri ("{0}/api/beta/me/messages/<message id>/createreply" -f $resourceId) -Headers $headers -Body $bodyJSON -OutFile $output
I was able to get a valid response from the API with this code. I am a little hesitant to share my output, I do not really know what is sensitive and what isn't, but I believe the error comes from the way your code is formulating your POST request. Can you share your code?
I hope this helps! |
You have to modify how you are posting and reading the response.
Modify the post call from
var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json);
to
var sucSender = await cl.PostAsJsonAsync("api/sender/successtested", json).ConfigureAwait(false);
And modify the response read call from doing this
var newvar = JsonConvert.DeserializeObject<Tested>(sucSender.ToString());
To
var newvar = await sucSender.Content.ReadAsAsync<Tested>();
here is full code based on my own test sample. I have a test2 api controller hosted at http://localhost/MyTestTwo which internally calls another api hosted at http://localhost/MyTestApi using HttpClient. To keep it simple, I have kept Test2Controller Get method sync instead of converting it into async await pattern. Both webapi applications are configured in IIS with Anonymous authentication.
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web.Http;
namespace MyTestTwo.Controllers
{
public class Test2Controller : ApiController
{
public IHttpActionResult Get()
{
var employeesTask = GetEmp();
employeesTask.Wait();
var employees = employeesTask.Result;
return Ok(employees);
}
private async Task<IEnumerable<string>> GetEmp()
{
IEnumerable<string> response = new List<string>();
var cl = new HttpClient();
cl.BaseAddress = new Uri("http://localhost/MyTestApp/");
cl.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var sucSender = await cl.PostAsJsonAsync("api/MyTest", "test").ConfigureAwait(false);
if (sucSender.IsSuccessStatusCode)
{
response = await sucSender.Content.ReadAsAsync<IEnumerable<string>>();
}
return response;
}
}
}
Please refer to this post Get response from PostAsJsonAsync and HttpClient.GetAsync(...) never returns when using await/async for more details. |
Thank you. I am also answering my own Q to add some more detail to how I have progressed (hope it helps some reader) and to ask a more detailed question to get to the nub of it.
I now have a way to compare an incoming authenticated user's graph data to a list of customer company names I keep. But this is not ideal. It depends on the graph api getting the customer tenant's DisplayName, which should match my list. I fear that might change and then disallow legit customers. I would prefer to use the Tenant ID from Azure AD. But I do not know how to get that immediately on signup. I can get that after the first user authenticates from that tenant, but how do I get the customer's Tenant ID before anyone from that company authenticates? Do I have to ask for it, or can I get that on my own?
Is there a better way to filter access to my web app (IIS) to allow only my customers? That is my detailed Q.
Please help a beginner figure out how the big boys authorize only their customers to an IIS web app. Here is the beginning of how I do it (cheating with pseudo code in the customer filtering part because I'd like to compare a GUID like TenantID (Issuer?) rather than a string like DisplayName):
public partial class Startup
{
private static string clientId = ConfigurationManager.AppSettings["ida:ClientId"];
private static string appKey = ConfigurationManager.AppSettings["ida:ClientSecret"];
private static string aadInstance = ConfigurationManager.AppSettings["ida:AADInstance"];
private static string postLogoutRedirectUri = ConfigurationManager.AppSettings["ida:PostLogoutRedirectUri"];
public static string custTenantID = "";
//for multi tenant sso, can be 'common' for consumer, 'organization' for work+school, or tenantID for single company
public static readonly string Authority = aadInstance + "common/";
//this is my model for the customer db
public CustomerTenant tenant = new CustomerTenant();
// This is the resource ID of the AAD Graph API. We'll need this to request a token to call the Graph API.
string graphResourceId = "https://graph.windows.net";
public void ConfigureAuth(IAppBuilder app)
{
ApplicationDbContext db = new ApplicationDbContext();
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
app.UseCookieAuthentication(new CookieAuthenticationOptions());
app.UseOpenIdConnectAuthentication(
new OpenIdConnectAuthenticationOptions
{
ClientId = clientId,
Authority = Authority,
PostLogoutRedirectUri = postLogoutRedirectUri,
//for multi-tenant
TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
{
// instead of using the default validation (validating against a single issuer value, as we do in line of business apps)
// we inject our own multitenant validation logic
ValidateIssuer = false,
},
Notifications = new OpenIdConnectAuthenticationNotifications()
{
// If there is a code in the OpenID Connect response, redeem it for an access token and refresh token, and store those away.
//AuthorizationCodeReceived is invoked after SecurityTokenValidated
//using this Notification to inject logic to authorize only my customers
AuthorizationCodeReceived = (context) =>
{
var code = context.Code;
ClientCredential credential = new ClientCredential(clientId, appKey);
string signedInUserID = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;
Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(Authority, new ADALTokenCache(signedInUserID));
AuthenticationResult result = authContext.AcquireTokenByAuthorizationCode(
code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), credential, graphResourceId);
//look up the customer tenant's DisplayName to compare to my list
Uri servicePointUri = new Uri(graphResourceId);
Uri serviceRoot = new Uri(servicePointUri, custTenantID);
ActiveDirectoryClient client = new ActiveDirectoryClient(serviceRoot, async () => { return await Task.FromResult(result.AccessToken); });
string tenantName = client.TenantDetails.ExecuteAsync().Result.CurrentPage.First().DisplayName;
//pseudo-code: compare this tenantName to db.CustomerTenants.CustomerName and if there is a match then authorize else do not authorize
return Task.FromResult(0);
},
//for multi-tenant sso
RedirectToIdentityProvider = (context) =>
{
string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
context.ProtocolMessage.RedirectUri = appBaseUrl;
context.ProtocolMessage.PostLogoutRedirectUri = postLogoutRedirectUri;
return Task.FromResult(0);
},
SecurityTokenValidated = (context) =>
{
// retrieve caller data from the incoming principal
string issuer = context.AuthenticationTicket.Identity.FindFirst("iss").Value;
string UPN = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.Name).Value;
custTenantID = context.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
return Task.FromResult(0);
},
AuthenticationFailed = (context) =>
{
context.OwinContext.Response.Redirect("urlToMyErrorPage?message=" + context.Exception.Message);
context.HandleResponse(); // Suppress the exception
return Task.FromResult(0);
}
}
});
}
|
I have been involved in three angularjs apps and in each of them we handled the whole user authentication/authorization in following way:
we defined a currentUser service which holds the information of current user of our application, things like user roles, email, name and ..., and this service have a very important method named isLoggedIn which based on this service values determine if user is logged in or not.
on the server side we have some sort of api which returns a token to a user after user have provided valid credentials, we post username/pass to the api and in response we receive a token and store it in a cookie or local sotrage. there are various ways of returning a token on would be using JWT(Json Web Token).
Tokens are sent in each request by help of $http interceptors, token may expire after 30 minutes which result in an unauthorized response from server.
for JWT refer to this link.
for client side authentication/authorization you can take a look at ng-book or this link. |
Solution is not great, but so far, that's what works for me :
in my config (only the relevant code):
@Configuration
@EnableWebSecurity
public class CASWebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
//disable HTTP Session management
http
.securityContext()
.securityContextRepository(new NullSecurityContextRepository())
.and()
.sessionManagement().disable();
http.requestCache().requestCache(new NullRequestCache());
//no security checks for health checks
http.authorizeRequests().antMatchers("/health/**").permitAll();
http.csrf().disable();
http
.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint());
http // login configuration
.addFilter(authenticationFilter())
.authorizeRequests().anyRequest().authenticated();
}
}
Then I added a specific filter :
@Component
public class HealthcheckSimpleStatusFilter extends GenericFilterBean {
private final String AUTHORIZATION_HEADER_NAME="Authorization";
private final String URL_PATH = "/health";
@Value("${healthcheck.username}")
private String username;
@Value("${healthcheck.password}")
private String password;
private String healthcheckRole="ADMIN";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest = this.getAsHttpRequest(request);
//doing it only for /health endpoint.
if(URL_PATH.equals(httpRequest.getServletPath())) {
String authHeader = httpRequest.getHeader(AUTHORIZATION_HEADER_NAME);
if (authHeader != null && authHeader.startsWith("Basic ")) {
String[] tokens = extractAndDecodeHeader(authHeader);
if (tokens != null && tokens.length == 2 && username.equals(tokens[0]) && password.equals(tokens[1])) {
createUserContext(username, password, healthcheckRole, httpRequest);
} else {
throw new BadCredentialsException("Invalid credentials");
}
}
}
chain.doFilter(request, response);
}
/**
* setting the authenticated user in Spring context so that {@link HealthMvcEndpoint} knows later on that this is an authorized user
* @param username
* @param password
* @param role
* @param httpRequest
*/
private void createUserContext(String username, String password, String role,HttpServletRequest httpRequest) {
List<GrantedAuthority> authoritiesForAnonymous = new ArrayList<>();
authoritiesForAnonymous.add(new SimpleGrantedAuthority("ROLE_" + role));
UserDetails userDetails = new User(username, password, authoritiesForAnonymous);
UsernamePasswordAuthenticationToken authentication =
new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(httpRequest));
SecurityContextHolder.getContext().setAuthentication(authentication);
}
private HttpServletRequest getAsHttpRequest(ServletRequest request) throws ServletException {
if (!(request instanceof HttpServletRequest)) {
throw new ServletException("Expecting an HTTP request");
}
return (HttpServletRequest) request;
}
private String[] extractAndDecodeHeader(String header) throws IOException {
byte[] base64Token = header.substring(6).getBytes("UTF-8");
byte[] decoded;
try {
decoded = Base64.decode(base64Token);
} catch (IllegalArgumentException var7) {
throw new BadCredentialsException("Failed to decode basic authentication token",var7);
}
String token = new String(decoded, "UTF-8");
int delim = token.indexOf(":");
if(delim == -1) {
throw new BadCredentialsException("Invalid basic authentication token");
} else {
return new String[]{token.substring(0, delim), token.substring(delim + 1)};
}
}
}
|
The request fails via file_get_contentssince Google server requires the call to be authorized, it could be seen from the picture below (Cookie header contains so called authentication tokens such as HSID, SSID and SID)
About authentication tokens
Google uses Security cookies:
to authenticate users, prevent fraudulent use of login credentials,
and protect user data from unauthorized parties.
This python example (see GetAuthTokens function) demonstrates how to obtain authentication tokens.
Example
The following example demonstrates how to perform authorized call by specifying security cookie:
$authTokens = array(
'HSID' => '',
'SSID' => '',
'SID' => '',
);
$opts = array(
'http'=>array(
'method'=>"GET",
'header'=>
'Cookie: HSID=' . $authTokens["HSID"] . '; SSID=' . $authTokens["SSID"] . '; SID=' . $authTokens["SID"]
)
);
$context = stream_context_create($opts);
$content = file_get_contents($url,false, $context);
|
Regarding Kerberos request and reply packet size - they are generally very small, typically around 50 - 100 kilobytes. To understand how Kerberos works, think of a triangle. At one point of the triangle, you have the Kerberos Key Distribution Center (KDC). After you have proven your identity to the KDC, it hands out a ticket to you - you being the internal network web browser user or SSH user. You are the second point on the triangle. This Kerberos ticket allows you access a Kerberos-protected service (such as HTTP or SSH) running on an application server on your network. The "application server" in this scenario, is the third point of the triangle. Two of the early and arguably most important contributors/creators of Kerberos, Clifford Neuman & Theodore Ts'o, from MIT at the time, explain how Kerberos works in this guide: Kerberos: An Authentication Service for Computer Networks. Literally, just a few paragraphs down from the top of the article is a section titled, "How Kerberos works". This is not really a manual. It explains the Kerberos main concepts. The article is dated but all concepts still apply. For "a manual", you need to ask yourself what you're trying to do. Integrate a Java web application to Kerberos (using Microsoft Active Directory)? Something else? For the former, which is very popular combination, I suggest reading this: Java-based Integrated Windows Authentication w/ Kerberos SPNEGO. As mentioned, Kerberos request and reply packet sizes are generally small. Encryptions types available are DES through AES and more, encryption key sizes are 40-bit to 256-bit lengths and more, though anything smaller than 128-bit length is out of favor now. Take a look at the Kerberos Network Authentication Service (V5) - RFC 4120. Though not an easy read, the article contains embedded references which will explain all of this. This question was far too broad, as samiles has said. Please try to start off with a specific programming example next time. |
Here's a work-around that doesn't require modifying the authentication backend at all.
First, look at the example login view from Django.
from django.contrib.auth import authenticate, login
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
If authentication with the username fails we can check if there is an email match, get the corresponding username, and try to authenticate again.
from django.contrib.auth import authenticate, login, get_user_model
def my_view(request):
username = request.POST['username']
password = request.POST['password']
user = authenticate(username=username, password=password)
if user is None:
User = get_user_model()
user_queryset = User.objects.all().filter(email__iexact=username)
if user_queryset:
username = user_queryset[0].username
user = authenticate(username=username, password=password)
if user is not None:
login(request, user)
# Redirect to a success page.
...
else:
# Return an 'invalid login' error message.
...
Similar to 1bit0fMe's example, email should be a unique field and there is the same (highly unlikely) downside that they mentioned.
I would only recommend this approach if all login on your site is handled by a single view or form. Otherwise, it would be better to modify the authenticate() method itself in the backend to avoid creating multiple points of potential failure. |
You can do what you are doing:
<input id="start-test" type="hidden" name="userid" value="<?php echo htmlspecialchars($userID); ?>">
Or use set_value like this:
<input id="start-test" type="hidden" name="userid" value="<?php echo set_value('userid', $userID); ?>">
This will repopulate the field value on form error. I have missed off the HTML special chars but you can include that still if you feel like you need to, but I presume this is an id from a database, that is set with auto increment and as it is not user generated data the use of html special chars here might be a bit unnecessary.
In your controller you can access the post variables like this:
$posted_id = $this->input->post('userid');
However, you should be using form validation on posted data. This is quite a big topic but you can read about the above in the docs. Also referring to your User ID directly is not always a great solution since this form can be easily manipulated. You can help to alleviate that somewhat with CI CSRF protection and using form_open but it is often best to use sessions and get the ID from there. You should not ever have to include a user id in a hidden form variable.
Set Value
http://www.codeigniter.com/user_guide/libraries/form_validation.html#re-populating-the-form
Reading post variables
http://www.codeigniter.com/user_guide/libraries/input.html#accessing-form-data
Form Validation in general
http://www.codeigniter.com/user_guide/libraries/form_validation.html#form-validation
Form open and CSRF
http://www.codeigniter.com/user_guide/helpers/form_helper.html#form_open
CI Sessions
http://www.codeigniter.com/user_guide/libraries/sessions.html#session-library
If you are not familiar with security practices it is sometimes best to get to know and use a mature and developed authorization and authentication library. There are many so I will not recommend one here. Just do a search for one and find one that suits your needs. |
I don't think you're going about this the correct way. The best way to log the request, with validation is in your Authentication Class and add the audit log to the request.
Then you can use your APIView to log the render time, against the AuditLog generated in the Authentication Class.
Here's an example using Token Authentication, assuming each request has a header Authorization: Bearer <Token>.
settings.py
...
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'common.authentication.MyTokenAuthenticationClass'
),
...,
}
common/authentication.py
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from ipware.ip import get_real_ip
from rest_framework import authentication
from rest_framework import exceptions
from accounts.models import Token, AuditLog
class MyTokenAuthenticationClass(authentication.BaseAuthentication):
def authenticate(self, request):
# Grab the Athorization Header from the HTTP Request
auth = authentication.get_authorization_header(request).split()
if not auth or auth[0].lower() != b'bearer':
return None
# Check that Token header is properly formatted and present, raise errors if not
if len(auth) == 1:
msg = _('Invalid token header. No credentials provided.')
raise exceptions.AuthenticationFailed(msg)
elif len(auth) > 2:
msg = _('Invalid token header. Credentials string should not contain spaces.')
raise exceptions.AuthenticationFailed(msg)
try:
token = Token.objects.get(token=auth[1])
# Using the `ipware.ip` module to get the real IP (if hosted on ElasticBeanstalk or Heroku)
token.last_ip = get_real_ip(request)
token.last_login = timezone.now()
token.save()
# Add the saved token instance to the request context
request.token = token
except Token.DoesNotExist:
raise exceptions.AuthenticationFailed('Invalid token.')
# At this point, insert the Log into your AuditLog table and add to request:
request.audit_log = AuditLog.objects.create(
user_id=token.user,
request_payload=request.body,
# Additional fields
...
)
# Return the Authenticated User associated with the Token
return (token.user, token)
Now, you have access to the AuditLog in your request. So you can log everything before and after validation. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.