text
stringlengths
64
2.99M
I also faced the same problem. But I used thymeleaf with iText. I use the ttf font package of the language (not unicode) and use the converter to convert unicode to my language and attach it into the PDF as normal string. it works like a charm. if you have the possibility to use thymeleaf, try this approach. put below CSS inside the style tag. @font-face { font-family: 'myfont-family'; src: url('/fonts/myfont.ttf'); -fs-pdf-font-embed: embed; -fs-pdf-font-encoding: Identity-H; } .mylanguage{ font-family: 'myfontfamily'; } <p class="mylanguage">your converted font text</p> Java code to generate pdf. context.setVariable("myvariable", myvariable); String html = templateEngine.process("mypdf", context); html = templateEngine.process("mythymeleaf", context); String fileName = "myfile.pdf"; PDFEncryption pdfEncryption = new PDFEncryption(); String password = "0000"; pdfEncryption.setUserPassword(password.getBytes()); ITextRenderer renderer = new ITextRenderer(); renderer.setDocumentFromString(html); renderer.layout(); renderer.setPDFEncryption(pdfEncryption); renderer.createPDF(outputStream); outputStream.flush(); outputStream.close(); Here is the link for this full tutorial about this approach with working source code. https://medium.com/@natsucoder/create-pdf-in-different-language-fonts-using-spring-boot-thymeleaf-itext-cba7f8612c61
You can supply a path with OPENJSON which allows you to drill in to nested JSON, eg SELECT * FROM OPENJSON( @json, '$.vehicleStatusResponse.vehicleStatuses' ) WITH ( vin VARCHAR(50) '$.vin', triggerType VARCHAR(50) '$.triggerType.triggerType', context VARCHAR(50) '$.triggerType.context', driverIdentification VARCHAR(50) '$.triggerType.driverId.tachoDriverIdentification.driverIdentification', cardIssuingMemberState VARCHAR(50) '$.triggerType.driverId.tachoDriverIdentification.cardIssuingMemberState', receivedDateTime DATETIME '$.receivedDateTime', engineTotalFuelUsed INT '$.engineTotalFuelUsed' ) Full script example: DECLARE @json VARCHAR(MAX) = '{ "vehicleStatusResponse": { "vehicleStatuses": [ { "vin": "ABC1234567890", "triggerType": { "triggerType": "TIMER", "context": "RFMS", "driverId": { "tachoDriverIdentification": { "driverIdentification": "123456789", "cardIssuingMemberState": "BRA", "driverAuthenticationEquipment": "CARD", "cardReplacementIndex": "0", "cardRenewalIndex": "1" } } }, "receivedDateTime": "2020-02-12T04:11:19.221Z", "hrTotalVehicleDistance": 103306960, "totalEngineHours": 3966.6216666666664, "driver1Id": { "tachoDriverIdentification": { "driverIdentification": "BRA1234567" } }, "engineTotalFuelUsed": 48477520, "accumulatedData": { "durationWheelbaseSpeedOverZero": 8309713, "distanceCruiseControlActive": 8612200, "durationCruiseControlActive": 366083, "fuelConsumptionDuringCruiseActive": 3064170, "durationWheelbaseSpeedZero": 5425783, "fuelWheelbaseSpeedZero": 3332540, "fuelWheelbaseSpeedOverZero": 44709670, "ptoActiveClass": [ { "label": "wheelbased speed >0", "seconds": 16610, "meters": 29050, "milliLitres": 26310 }, { "label": "wheelbased speed =0", "seconds": 457344, "milliLitres": 363350 } ] } } ] }}}}}}}}' SELECT * FROM OPENJSON( @json, '$.vehicleStatusResponse.vehicleStatuses' ) WITH ( vin VARCHAR(50) '$.vin', triggerType VARCHAR(50) '$.triggerType.triggerType', context VARCHAR(50) '$.triggerType.context', driverIdentification VARCHAR(50) '$.triggerType.driverId.tachoDriverIdentification.driverIdentification', cardIssuingMemberState VARCHAR(50) '$.triggerType.driverId.tachoDriverIdentification.cardIssuingMemberState', receivedDateTime DATETIME '$.receivedDateTime', engineTotalFuelUsed INT '$.engineTotalFuelUsed' ) My results: Read more about OPENJSON here: https://docs.microsoft.com/en-us/sql/t-sql/functions/openjson-transact-sql?view=sql-server-ver15 A second example. With OPENJSON you can either supply the json path expression is more explicit and gives you more control particularly for nested JSON. If the JSON is relatively simple, you do not have to supply the paths, eg DECLARE @json VARCHAR(MAX) = '{ "ptoActiveClass": [ { "label": "wheelbased speed >0", "seconds": 16610, "meters": 29050, "milliLitres": 26310 }, { "label": "wheelbased speed =0", "seconds": 457344, "milliLitres": 363350 } ] }' SELECT * FROM OPENJSON( @json, '$.ptoActiveClass' ) WITH ( label VARCHAR(50), seconds INT, meters INT, milliLitres INT ) SELECT * FROM OPENJSON( @json, '$.ptoActiveClass' ) WITH ( label VARCHAR(50) '$.label', seconds VARCHAR(50) '$.seconds', meters VARCHAR(50) '$.meters', milliLitres VARCHAR(50) '$.milliLitres' )
I had luck with this using the Openssl library. I wrote a library that wraps some of the encryption and decryption functionality available in Openssl to hopefully make it simpler. Here's a short example that uses AES-256-CCM to encrypt and decrypt a string using a 12 byte IV: use Encryption\Encryption; require('../vendor/autoload.php'); $text = 'The quick brown fox jumps over the lazy dog'; $key = 'secretkey'; $encryption = Encryption::getEncryptionObject('AES-256-CCM'); $iv = $encryption->generateIv(); $encryptedText = $encryption->encrypt($text, $key, $iv, $tag); $decryptedText = $encryption->decrypt($encryptedText, $key, $iv, $tag); printf('Cipher : %s%s', $encryption->getName(), PHP_EOL); printf('IV : %s%s', base64_encode($iv), PHP_EOL); printf('IV Length: %s%s', strlen($iv), PHP_EOL); printf('Tag : %s%s', base64_encode($tag), PHP_EOL); printf('Encrypted: %s%s', $encryptedText, PHP_EOL); printf('Decrypted: %s%s', $decryptedText, PHP_EOL); Outputs: Cipher : AES-256-CCM IV : i925n5X6xdrKyImY IV Length: 12 Tag : b/fl4BEDAGN5U0P40/GN7g== Encrypted: zcfFmoRKZNxxwh4z9FGaY63bl4YXYnzSxlLFEE+e9QqsMhoJjpsJ6ALH2ho+ochS Decrypted: The quick brown fox jumps over the lazy dog If this is good enough for you, the library is called PHP Simple Encryption and is available as a composer package.
https://stackoverflow.com/a/13078276/702977 is 8 years old, so the links may not work anymore. MongoDB drivers are usually libraries that you use in your application to handle connecting to the database to query, insert, etc. If you upgrade the database from 2.6 to 4.2 without upgrading the driver, it probably won't be able to connect. It would be best to upgrade the driver first, then the database. If you are going to use mongodump to backup your data and mongorestore to insert it into the upgraded database, you don't need to upgrade in steps. backup the data set using mongodump uninstall the existing version follow the installation steps for MongoDB 4.2 restore the data with mongorestore One of the major changes between 2.6 and the newer versions is authentication. MongoDB-CR is not supported at all in 4.2, so you will probably need to recreate all of your users once you upgrade. MMAP is also gone, but that shouldn't be a problem when you use the backup/restore method to upgrade.
Your code works perfectly. I only updated tenant,clientId,clientSecret and MY_ISSUER in your code. Here is the whole code I ran. const { AuthenticationContext } = require('adal-node'); class AuthProvider { async getAccessToken() { return new Promise((resolve, reject) => { const tenant = '6b72a356-867d-4c35-bde6-959d99388ca8'; const authority = `https://login.microsoftonline.com/${tenant}`; const authenticationContext = new AuthenticationContext(authority); const resource = 'https://graph.microsoft.com'; const clientId = '270408b5-85a6-4e99-861e-7634853a5827'; const clientSecret = 'VYD_F_Rr~eHYqLtTXqa1~1KRS_932yNw35'; authenticationContext.acquireTokenWithClientCredentials( resource, clientId, clientSecret, (err, tokenResponse) => { if (err) { console.error('error!', err); return reject(err); } return resolve(tokenResponse.accessToken); }, ); }); } } require('isomorphic-fetch'); //needed for server side request with the client const { Client } = require('@microsoft/microsoft-graph-client'); const options = { authProvider: new AuthProvider(), }; const client = Client.initWithMiddleware(options); const user = { displayName: 'John Smith', identities: [ { signInType: 'emailAddress', issuer: 'tonyb2ctest.onmicrosoft.com', issuerAssignedId: '[email protected]', }, ], passwordProfile: { password: 'df42bfe2-8060-411f-b277-06b819874573', }, passwordPolicies: 'DisablePasswordExpiration', }; client .api('/users') .post(user) .then(data => console.log(data)) .catch(e => console.error(e)) The result: I registered an application under Azure Active Directory and granted Directory.ReadWrite.All permission.
Some notes: HMAC is for message authentication, not hashing passwords. BCrypt or SCrypt are not implemented in the Windows API, while SHA256/384/512 are. SHA512 is plenty secure for hashing passwords. If we go for SHA512, you can use a hashing approach I previously shared here. This code uses the Windows CNG API, and allowed hashing algorithms are listed here with corresponding OS support. A call is as simple as HashString("SomePassword" & "SomeSalt"). It returns a byte array, for convenience you could convert that to Base64 but storing it as binary is more efficient. You can use the same API for generating random numbers (salts). I've outlined an approach here focused on integers, but you might want to generate random bytes and then prepend the string to those bytes. An additional challenge is character encoding. PHP is UTF-8, Access is UTF-16 and doesn't really do UTF-8. If you limit possible characters to ASCII, you can use StrConv in VBA to cast the string to ANSI, and validate that there are no non-ASCII characters in there. If you want to convert strings to UTF-8 in VBA, that's another API call (WideCharToMultiByte) you need to use before hashing. Note that unicode in password is a UX hazard, because some operating systems express special characters as composite characters, and some don't, and that difference will cause passwords to mismatch, so there's an argument to be made for keeping it ASCII. See the hashing code down below: Public Declare PtrSafe Function BCryptOpenAlgorithmProvider Lib "BCrypt.dll" (ByRef phAlgorithm As LongPtr, ByVal pszAlgId As LongPtr, ByVal pszImplementation As LongPtr, ByVal dwFlags As Long) As Long Public Declare PtrSafe Function BCryptCloseAlgorithmProvider Lib "BCrypt.dll" (ByVal hAlgorithm As LongPtr, ByVal dwFlags As Long) As Long Public Declare PtrSafe Function BCryptCreateHash Lib "BCrypt.dll" (ByVal hAlgorithm As LongPtr, ByRef phHash As LongPtr, pbHashObject As Any, ByVal cbHashObject As Long, ByVal pbSecret As LongPtr, ByVal cbSecret As Long, ByVal dwFlags As Long) As Long Public Declare PtrSafe Function BCryptHashData Lib "BCrypt.dll" (ByVal hHash As LongPtr, pbInput As Any, ByVal cbInput As Long, Optional ByVal dwFlags As Long = 0) As Long Public Declare PtrSafe Function BCryptFinishHash Lib "BCrypt.dll" (ByVal hHash As LongPtr, pbOutput As Any, ByVal cbOutput As Long, ByVal dwFlags As Long) As Long Public Declare PtrSafe Function BCryptDestroyHash Lib "BCrypt.dll" (ByVal hHash As LongPtr) As Long Public Declare PtrSafe Function BCryptGetProperty Lib "BCrypt.dll" (ByVal hObject As LongPtr, ByVal pszProperty As LongPtr, ByRef pbOutput As Any, ByVal cbOutput As Long, ByRef pcbResult As Long, ByVal dfFlags As Long) As Long Public Function NGHash(pData As LongPtr, lenData As Long, Optional HashingAlgorithm As String = "SHA1") As Byte() 'Erik A, 2019 'Hash data by using the Next Generation Cryptography API 'Loosely based on https://docs.microsoft.com/en-us/windows/desktop/SecCNG/creating-a-hash-with-cng 'Allowed algorithms: https://docs.microsoft.com/en-us/windows/desktop/SecCNG/cng-algorithm-identifiers. Note: only hash algorithms, check OS support 'Error messages not implemented On Error GoTo VBErrHandler Dim errorMessage As String Dim hAlg As LongPtr Dim algId As String 'Open crypto provider algId = HashingAlgorithm & vbNullChar If BCryptOpenAlgorithmProvider(hAlg, StrPtr(algId), 0, 0) Then GoTo ErrHandler 'Determine hash object size, allocate memory Dim bHashObject() As Byte Dim cmd As String cmd = "ObjectLength" & vbNullString Dim Length As Long If BCryptGetProperty(hAlg, StrPtr(cmd), Length, LenB(Length), 0, 0) <> 0 Then GoTo ErrHandler ReDim bHashObject(0 To Length - 1) 'Determine digest size, allocate memory Dim hashLength As Long cmd = "HashDigestLength" & vbNullChar If BCryptGetProperty(hAlg, StrPtr(cmd), hashLength, LenB(hashLength), 0, 0) <> 0 Then GoTo ErrHandler Dim bHash() As Byte ReDim bHash(0 To hashLength - 1) 'Create hash object Dim hHash As LongPtr If BCryptCreateHash(hAlg, hHash, bHashObject(0), Length, 0, 0, 0) <> 0 Then GoTo ErrHandler 'Hash data If BCryptHashData(hHash, ByVal pData, lenData) <> 0 Then GoTo ErrHandler If BCryptFinishHash(hHash, bHash(0), hashLength, 0) <> 0 Then GoTo ErrHandler 'Return result NGHash = bHash ExitHandler: 'Cleanup If hAlg <> 0 Then BCryptCloseAlgorithmProvider hAlg, 0 If hHash <> 0 Then BCryptDestroyHash hHash Exit Function VBErrHandler: errorMessage = "VB Error " & Err.Number & ": " & Err.Description ErrHandler: If errorMessage <> "" Then MsgBox errorMessage Resume ExitHandler End Function Public Function HashBytes(Data() As Byte, Optional HashingAlgorithm As String = "SHA512") As Byte() HashBytes = NGHash(VarPtr(Data(LBound(Data))), UBound(Data) - LBound(Data) + 1, HashingAlgorithm) End Function Public Function HashString(str As String, Optional HashingAlgorithm As String = "SHA512") As Byte() HashString = NGHash(StrPtr(str), Len(str) * 2, HashingAlgorithm) End Function
Sample demo to use Office365-REST-Python-Client to get SharePoint list data and output as excel. import json import pandas from office365.runtime.auth.authentication_context import AuthenticationContext from office365.runtime.client_request import ClientRequest from office365.runtime.utilities.request_options import RequestOptions url="https://xxx.sharepoint.com/" ctx_auth = AuthenticationContext(url) if ctx_auth.acquire_token_for_user("[email protected]", "password"): request = ClientRequest(ctx_auth) options = RequestOptions("{0}/sites/lee/_api/web/lists/getByTitle('ListA')/items?$select=ID,Title,ProjectType".format(url)) options.set_header('Accept', 'application/json; odata=minimalmetadata') options.set_header('Content-Type', 'application/json') data = request.execute_request_direct(options) s = json.loads(data.content) data=s['value'] pandas.read_json(json.dumps(data)).to_excel("output.xlsx") print("output") else: print (ctx_auth.get_last_error()) Update: Tried SharePlum in python 3.8. import json import pandas from shareplum import Site from shareplum import Office365 authcookie = Office365('https://xxx.sharepoint.com', username='[email protected]', password='password').GetCookies() site = Site('https://xxx.sharepoint.com/sites/lee/', authcookie=authcookie) sp_list = site.List('ListA') data = sp_list.GetListItems('All Items') pandas.read_json(json.dumps(data)).to_excel("output.xlsx") Debug screenshot:
I setup your code in Java and made an encryption with a (fixed) key and an random initialization vector: import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.security.SecureRandom; import java.util.Base64; import java.util.Random; public class SO_Main_Final { static final String ALGO = "AES"; //$NON-NLS-1$ static final String GCMALGO = "AES/GCM/NoPadding"; //$NON-NLS-1$ static final String UNICODE_FORMAT = "UTF8"; //$NON-NLS-1$ static final Random random = new SecureRandom(); public static void main(String[] args) throws Exception { System.out.println("https://stackoverflow.com/questions/62129604/decrypt-aes-128-gcm-encoded-content-with-java-cipher-using-php-openssl"); String myData = "Secret data for TytooF"; String myKey = "1234567890123456"; String encryptString = encrypt(myData, myKey, 16); String decryptString = decrypt(encryptString, myKey, 16); System.out.println("encryptString: " + encryptString); System.out.println("decryptString: " + decryptString); } private static String encrypt(String data, String mainKey, int ivLength) throws Exception { final byte[] dataBytes = data.getBytes(UNICODE_FORMAT); // byte[] initializationVector = generateInitializationVector(ivLength); byte[] initializationVector = new byte[ivLength]; random.nextBytes(initializationVector); SecretKeySpec secretKeySpec = new SecretKeySpec(mainKey.getBytes(UNICODE_FORMAT), ALGO); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector); Cipher cipher = Cipher.getInstance(GCMALGO); cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, gcmParameterSpec); final byte[] encryptedData = cipher.doFinal(dataBytes); final byte[] encryptedBytes = new byte[encryptedData.length + ivLength]; System.arraycopy(initializationVector, 0, encryptedBytes, 0, ivLength); System.arraycopy(encryptedData, 0, encryptedBytes, ivLength, encryptedData.length); System.out.println("data [String] : " + data); System.out.println("data length: " + dataBytes.length + " data: " + bytesToHex(dataBytes)); System.out.println("mainKey length: " + mainKey.getBytes(UNICODE_FORMAT).length + " data: " + bytesToHex(mainKey.getBytes(UNICODE_FORMAT))); System.out.println("initvector length: " + initializationVector.length + " data: " + bytesToHex(initializationVector)); System.out.println("encryptedBytes length: " + encryptedBytes.length + " data: " + bytesToHex(encryptedBytes)); return Base64.getEncoder().encodeToString(encryptedBytes); } private static String decrypt(String data, String mainKey, int ivLength) throws Exception { final byte[] encryptedBytes = Base64.getDecoder().decode(data.getBytes(UNICODE_FORMAT)); final byte[] initializationVector = new byte[ivLength]; System.arraycopy(encryptedBytes, 0, initializationVector, 0, ivLength); SecretKeySpec secretKeySpec = new SecretKeySpec(mainKey.getBytes(UNICODE_FORMAT), ALGO); GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector); Cipher cipher = Cipher.getInstance(GCMALGO); cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, gcmParameterSpec); return new String(cipher.doFinal(encryptedBytes, ivLength, encryptedBytes.length - ivLength), UNICODE_FORMAT); } private static String bytesToHex(byte[] bytes) { StringBuffer result = new StringBuffer(); for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1)); return result.toString(); } } In the end I got this result - the "encryptString" needs to get transfered to your website: https://stackoverflow.com/questions/62129604/decrypt-aes-128-gcm-encoded-content-with-java-cipher-using-php-openssl data [String] : Secret data for TytooF data length: 22 data: 536563726574206461746120666f72205479746f6f46 mainKey length: 16 data: 31323334353637383930313233343536 initvector length: 16 data: 3fc914fc67f6ecb53daa098ba40f20a5 encryptedBytes length: 54 data: 3fc914fc67f6ecb53daa098ba40f20a5f1e6755b96e5c0bb5de29522099bdeb806cf28c6d181d7e4ffdc15f451a19a54c714c42b38fc encryptString: P8kU/Gf27LU9qgmLpA8gpfHmdVuW5cC7XeKVIgmb3rgGzyjG0YHX5P/cFfRRoZpUxxTEKzj8 decryptString: Secret data for TytooF On webserver/PHP-side I slightly modified your code (the "main change" was the change on the line openssl_decrypt($ciphertext, $cipher, $key, true, $iv, $tag) because we do not present Base64-encoded data to the decrypt method as this is done some codelines before ($encrypt = base64_decode($str). Here is the PHP-code: <?php /** * @param string $str * The URL parameter string */ function test_decrypt($str) { $key = '1234567890123456'; $cipher = 'aes-128-gcm'; $iv_len = 16; $tag_length = 16; echo $str . '<br>'; /** * Decryption part */ $encrypt = base64_decode($str); $iv = substr($encrypt, 0, $iv_len); $tag = substr($encrypt, -$tag_length); $ciphertext = substr($encrypt, $iv_len, -$tag_length); echo "" . "\n"; $value = unpack('H*', $iv); echo '<br>iv:' . $value[1]; echo "" . "\n"; $value = unpack('H*', $ciphertext); echo '<br>ciphertext:' . $value[1]; echo "" . "\n"; $value = unpack('H*', $tag); echo '<br>tag:' . $value[1]; echo "<br>" . "\n"; $uncrypt = openssl_decrypt($ciphertext, $cipher, $key, true, $iv, $tag);//OPENSSL_RAW_DATA + OPENSSL_NO_PADDING echo '<br>DecryptedString: ' . $uncrypt . "\n"; $value = unpack('H*', $uncrypt); echo '<br>DecryptedString [byte[]]:' . $value[1]; exit; } echo '<b>Output for https://stackoverflow.com/questions/62129604/decrypt-aes-128-gcm-encoded-content-with-java-cipher-using-php-openssl</b><br>' . "\n"; echo '' . "\n"; echo 'Start decryption' . "\n"; $receivedData = "P8kU/Gf27LU9qgmLpA8gpfHmdVuW5cC7XeKVIgmb3rgGzyjG0YHX5P/cFfRRoZpUxxTEKzj8"; test_decrypt($receivedData); ?> This is the decryption output on the webserver: Output for https://stackoverflow.com/questions/62129604/decrypt-aes-128-gcm-encoded-content-with-java-cipher-using-php-openssl Start decryption P8kU/Gf27LU9qgmLpA8gpfHmdVuW5cC7XeKVIgmb3rgGzyjG0YHX5P/cFfRRoZpUxxTEKzj8 iv:3fc914fc67f6ecb53daa098ba40f20a5 ciphertext:f1e6755b96e5c0bb5de29522099bdeb806cf28c6d181 tag:d7e4ffdc15f451a19a54c714c42b38fc DecryptedString: Secret data for TytooF DecryptedString [byte[]]:536563726574206461746120666f72205479746f6f46 Edit Oct. 10th 2021: The code above is using an IV/nonce with a length of 16 bytes but the recommended IV/nonce length is 12.
It is the application authentication cookie that is growing, not identity server cookie. And you assumed well, cookie is growing because it encrypts all the claims, including roles in the cookie to persist them between server calls. Alternative solution would be to configure IdentityServer to pass only minimal amount of user data that is required throughout the application lifetime on initial login. Everything else, that you might need "at certain point", you could retrieve via backend call to user-info endpoint using access_token. Drawback of this approach is that managing access_token lifetime then becomes an issue, because, unlike cookie, it does not have rolling expiration. Other option would be to enable session for your web app, and to store cookie data into the server-side session storage, instead of the cookie itself. Update: Regarding your GetProfileDataAsync, it loads all claims, which is fine, but then you configure in IdentityResources configuration which filters claims you actually want to pass to the client. Configuration of IdentityServer is too big topic to discuss in details in SO question.
It's usually easier to BULK INSERT data with a format file. Use the bcp.exe utility to create a format file with a command such as the following: bcp.exe DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV format nul -c -t; -f C:\Temp\TBIMP_FOTOS_CSV.fmt -S(local) -T Where: DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV is the Database.Schema.Table we're interacting with. format specifies format file creation mode. nul specifies the input/output data file, which in this case means "don't write any data". -c specifies character mode, as opposed to native (binary) mode. -t; specifies to use ; as the field separator character. -f C:\Temp\TBIMP_FOTOS_CSV.fmt specifies the path to write the format file to, relative to your local computer. -S(local) is the SQL Server to connect to, (local) in my case. -T means Trusted Authentication (Windows authentication), use -uUsername and -pPassword if you have SQL Login authentication instead. This creates a format file something like the following (yours will have more and different columns): 14.0 2 1 SQLCHAR 0 510 ";" 1 Filename SQL_Latin1_General_Pref_CP1_CI_AS 2 SQLCHAR 0 510 "\r\n" 2 Resolution SQL_Latin1_General_Pref_CP1_CI_AS Now, in SSMS, you should be able to run something like the following to import your data file (adjust file paths relative to your SQL Server as appropriate): BULK INSERT DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV FROM 'C:\Temp\TBIMP_FOTOS_CSV.csv' WITH ( CODEPAGE = '65001', DATAFILETYPE = 'char', FORMAT = 'CSV', FORMATFILE = 'C:\Temp\TBIMP_FOTOS_CSV.fmt' ); -- edit -- On SQL Server and international character support. SQL Server and UTF-8 has had a bit of a checkered history, only gaining partial support with SQL Server 2016 and really only supporting UTF-8 code pages with SQL Server 2019. Importing and exporting files with international characters is still best handled using UTF-16 encoded files. Adjustments to the workflow are as follows... In PowerShell, use the Unicode encoding instead of UTF8: Export-Csv -Path $DirPath -Delimiter ';' -NoTypeInformation -Encoding Unicode When generating the BCP format file, use the -w switch (for widechar) instead of -c (for char): bcp.exe DEV_DS_SANTOGRAU..GB_TBIMP_FOTOS_CSV format nul -w -t; -f C:\Temp\TBIMP_FOTOS_CSV-widechar.fmt -S(local) -T This causes the SQLCHAR columns to be written out as SQLNCHAR, aka. national character support: 14.0 2 1 SQLNCHAR 0 510 ";\0" 1 Filename SQL_Latin1_General_Pref_CP1_CI_AS 2 SQLNCHAR 0 510 "\r\0\n\0" 2 Resolution SQL_Latin1_General_Pref_CP1_CI_AS When using BULK INSERT specify DATAFILETYPE = 'widechar' instead of DATAFILETYPE = 'char' and specifying a codepage, e.g.: BULK INSERT GB_TBIMP_FOTOS_CSV FROM 'C:\Temp\TBIMP_FOTOS_CSV.csv' WITH ( DATAFILETYPE = 'widechar', FORMATFILE = 'C:\Temp\TBIMP_FOTOS_CSV-widechar.fmt' );
You are trying to access an API which is not accepting requests from a website (except from localhost). If the browser comes across a request which is cross-origin, it tries to make a pre-flight request (an initial request to ask the server, it is okay to fetch from this remote address, which is different than the current domain). If the pre-flight request is not responded with a successful message, the Ajax request fails. This behavior is called CORS and it must be supported by the API. Your API does not seem to allow i.e. it actually forbids CORS requests explicitly. This is usually done, if the API wants to force the developer to make the request on the server-side. The benefit of this is, that the access key is not sent along with the JavaScript code to the visitor of the website but rather it stays on the server. Try to make the request on your server and then send the data to your front-end from your own server. This also allows to use your own authentication. You could also use a web service like CORS everywhere, but keep in mind that this service has access to all data you are sending and receiving (and it is able to modify the data both-ways).
You have mentioned "when the program has just finished loading the key from the disk and has not called the Protect()" If I rephrase the above sentence StorageInt.FetchKey() is fetching you an unprotected key and you want to protect it at this point. You could create an extension method for StorageInt.FetchKey(bool IsProtectKey = true) this method can call ProtectedMemory.Protect(). You can use only the extension method to fetch key. public int StorageInt.FetchKey(bool IsProtectKey = true) { encKey = StorageInt.FetchKey(); CodeEncryptedKey = EncryptAndStoreProtectedKey(); //Above function should encrypt your "encKey" to AES256 or to any secure encryption algorithm, store it in cache and return encrypted key ProtectedMemory.Protect(encKey, MemoryProtectionScope.SameProcess); } Public string UseKey(string CodeEncryptedKey) { encKey = GetProtectedKeyFromCache(CodeEncryptedKey) ProtectedMemory.Unprotect(encKey, MemoryProtectionScope.SameProcess); Task.Run(() => ProtectKeyAfter5Seconds(encKey)); return encKey; } Void ProtectKeyAfter5Seconds(encKey) { Thread.Sleep(5000); //I'm telling here to encrypt after 5 seconds, you can have your logic to encrypt after one-time use or any particular logic ProtectedMemory.Protect(encKey, MemoryProtectionScope.SameProcess); } Does this help?
You have to implement a custom authenticator and add it to your authentication flow in Keycloak. Implement the Authenticator interface of Keycloak. First, you need to get the list of sessions of the current user as follows: List<UserSessionModel> userSessions = session.sessions().getUserSessions(context.getRealm(), context.getUser()); session is a KeycloakSession. The context can be accessed inside the method authenticate you are going to override next. Here we can start implementing the behaviour you are looking for: private void logoutOldestSession(List<UserSessionModel> userSessions) { logger.info("Logging out oldest session"); Optional<UserSessionModel> oldest = userSessions.stream().sorted(Comparator.comparingInt(UserSessionModel::getStarted)).findFirst(); oldest.ifPresent(userSession -> AuthenticationManager.backchannelLogout(session, userSession, true)); } Don't forget to deploy the jar file containing this behavior under deployments of your Keycloak distribution. Also, you have to reference your authenticator under /META-INF/services.
The problem is probably related to not having sufficient rights from the account you use for the Exchange Service authentication to the target account. Use the command below to give rights and try again. Add-MailboxFolderPermission -Identity [email protected]:\Calendar -User [email protected] -AccessRights Reviewer This is a very annoying issue, I have opened an incident with MS in the past, but got the disappointing answer that this won't change soon. Below is the PS code to set rights to all users, rooms, resources, regardless of culture (language) and name of the calendar folder. Param( [parameter(position=0,Mandatory=$true)][string] $serviceaccount, [parameter(position=1,Mandatory=$true)][string] $mailboxtype ) $acl = "Reviewer" if ($mailboxtype -eq "All") { $mailboxes = Get-Mailbox | Where {$_.RecipientTypeDetails -eq "UserMailbox" -or $_.RecipientTypeDetails -eq "RoomMailbox" -or $_.RecipientTypeDetails -eq "EquipmentMailbox"} | Select -expand PrimarySmtpAddress | Select -expand Address | Where {$_ -NotLike "Administrator@*"} } elseif ($mailboxtype -eq "Users") { $mailboxes = Get-Mailbox | Where {$_.RecipientTypeDetails -eq "UserMailbox"} | Select -expand PrimarySmtpAddress | Select -expand Address | Where {$_ -NotLike "Administrator@*"} } elseif ($mailboxtype -eq "Resources") { $mailboxes = Get-Mailbox | Where {$_.RecipientTypeDetails -eq "RoomMailbox" -or $_.RecipientTypeDetails -eq "EquipmentMailbox"} | Select -expand PrimarySmtpAddress | Select -expand Address } else { "Error specifying target mailbox type. Choose one of: 'All', 'Users' or 'Resources'.`n 'All' - UserMailbox, RoomMailbox, EquipmentMailbox.`n 'Users' - UserMailbox.`n 'Resources' - RoomMailbox, EquipmentMailbox." } foreach ($mbx in $mailboxes) { $calName = Get-MailboxFolderStatistics -Identity $mbx -FolderScope Calendar | Where-Object { $_.FolderType -eq 'Calendar'} | Select-Object Name, FolderId #-ErrorAction Stop #echo "${mbx}:\$($calName.Name)" Add-MailboxFolderPermission -Identity ${mbx}:\$($calName.Name) -User $serviceaccount -AccessRights $acl | Select-Object Identity, FolderName, User, AccessRights } Save as PS script, call with two params: serviceaccount & mailboxtype
TLDR: Conditionally render your NavLinks in the Navigation component. Checkout the Sandbox. SOME Context. @soccerway, Since this question could be answered with the same approach in a previously answered one, for brevity, I recycled this Code Sandbox, with a few minor changes to try and reproduce your case wiht the following assumptions... It looks like you are using local state with useState on logging in based on this statement setLoginData(res.data.loginData), but since your component might be unmounted by the Navbar given the fact that you are not having another Navbar or a dashboard and your users are bound to be moving back and forth easily, unmounting that component will result in the app loosing that state. It's much better to use higher up state management keeping the Auth and Privilege data between pages. You could use React's Context and access it with useContext hook or use Redux and wrap session data around the entire app. Once the user is logged in, save the app state in context or a store and retrieve it in whichever component needs to have that permission/privilege condition. In my case, I use the context api api, and store the user-id in localStorage.(You can use whatever session storage you want.) Since I don't have access to your api, I created a simple fake Auth API, and to cover the handleSubmit. In the AuthProvider, I assumed the data you are getting from the server in this line res.data.loginData[0].privilege === "PLAYER" to be of the following format, but it can be anything. // Sample API FORMAT: Note this is normalized not array like -> loginData[0] const users = { "player-1": { id: "player-1", username: "Player One", // permissions: ["view-profile"], // Alternatively, you could have permission logic privilege: "PLAYER" // Fetched by => res.data.loginData[0].privilege === "PLAYER" }, "admin-1": { id: "admin-1", username: "Admin One", // permissions: ["view-profile", "register-user"], privilege: "ADMIN" } }; // NOTE: The authenticated user is saved in context as currentUser, // and the login state saved as isLoggedIn // Sample login Page const LoginPage = () => { const history = useHistory(); let location = useLocation(); const { isLoggedIn, login } = useContext(AuthContext); const { from } = location.state || { from: { pathname: "/" } }; const { pathname } = from; let handleSubmit= userId => { // login is to the fake Api, but yours could be to an axios server. login({ userId, history, from }); }; return isLoggedIn ? ( "you are already logged in" ) : ( <div className="login-btns"> {pathname !== "/" && ( <p>You must log in to view the page at {pathname}</p> )} <button onClick={() => handleSubmit("player-1")}>Player Logs in</button> <button onClick={() => handleSubmit("admin-1")}>Admin Logs in</button> </div> ); }; With your data readily accessible in all components via context, you can use it to translate the privilages into conditions to render the components. Tip Name conditions related to the views you are rendering not the api, since it changes a lot. You could retrieve the privilages from the context in whichever descendant component you wish to conditionally render as follows const { currentUser, isLoggedIn } = useContext(AuthContext); const privilege = currentUser?.privilege || []; // Create View conditions based on the privilages. You can be fancy all you want :) const canViewProfile = privilege === "PLAYER" || privilege === "ADMIN"; const canRegisterUser = privilege === "ADMIN"; You could use this logic directly in your Navigation component but chances are high, some Routes and Switch will depend on this logic for conditional redirection. So it's best to avoid repetition, to keep it in the siblings' parent, or even compute it in the context/store. (Tip: Trying to maintain the same related condition in many different places bites especially without TypeScript). In my case, I pass the conditions to the Navigation and Pages via props. See the AuthedComponents ==== to your App component below // This is similar to your App component const AuthedComponents = () => { const { currentUser, isLoggedIn } = useContext(AuthContext); const privilege = currentUser?.privilege || []; // Generate conditions here from the privilages. You could store them in the context too const canViewProfile = privilege === "PLAYER" || privilege === "ADMIN"; const canRegisterUser = privilege === "ADMIN"; return ( <Router> <div> <h1>{` ⚽ Soccerway `}</h1> <UserProfile /> {/* Pass the conditions to the Navigation. */} <Navigation isLoggedIn={isLoggedIn} canViewProfile={canViewProfile} canRegisterUser={canRegisterUser} /> <hr /> <Switch> <Route path="/login"> <LoginPage /> </Route> <Route path="/about-us"> <AboutUsPage /> </Route> {/* You can conditionally render hide these items from the tree using permissions */} <Route path="/profile"> {/* Passed down the conditions to the Pages via props to be used in redirection */} <ProfilePage canViewProfile={canViewProfile} /> </Route> <Route path="/register-user"> <RegistrationPage canRegisterUser={canRegisterUser} /> </Route> <Route path="/"> <HomePage /> </Route> </Switch> </div> </Router> ); }; In the Navigation component, use isLoggedIn prop to either show the login NavLink item or the (Profile and Registration pages) since they are mutually exclusive. Conditionally render privilege based NavLinks with the computed props. /* You could get these props from the auth context too... if you want */ const Navigation = ({ isLoggedIn, canViewProfile, canRegisterUser }) => ( <ul className="navbar"> <li> <NavLink exact to="/" activeClassName="active-link"> Home </NavLink> </li> {/* Check if the User is Logged in: Show the Login Button or Show Other Nav Buttons */} {!isLoggedIn ? ( <li> <NavLink to="/login" activeClassName="active-link"> Login </NavLink> </li> ) : ( // Now, here consitionally check for each permission. // Or you could group the different persmissions into a user-case // You could have this as s seperate navbar for complicated use-cases <> {canViewProfile && ( <li> <NavLink to="/profile" activeClassName="active-link"> Profile </NavLink> </li> )} {canRegisterUser && ( <li> <NavLink to="/register-user" activeClassName="active-link"> Register </NavLink> </li> )} </> )} {/* This is a public route like the Home, its viewable to every one */} <li> <NavLink to="/about-us" activeClassName="active-link"> AboutUs </NavLink> </li> </ul> ); In the components, if the user does not meet the permissions/privileges, forcefully redirect them to the login page. // Example usage in the Profile Page const ProfilePage = ({ canViewProfile }) => { return canViewProfile ? ( <> <h2>Profile</h2> <p>Full details about the Player</p> </> ) : ( <Redirect from="/profile" to="/login" /> ); };
While not directly related, a good discussion about your question appears here: Run a process from a windows service as the current user The main problem you're facing is that there can be multiple users logged on to the same desktop (https://www.codeproject.com/Articles/13822/Get-Information-About-the-Currently-Logged-on-Us-2). If that's the case, which user do you pick (the "Inspect Event Log Data" section below provides a potentially helpful answer to this question)? As the above SO link advises, you can take one of these approaches: Install a service with the application that captures the current user (rather than the "run-as user" in the background and stores that information in a repository that the launched application can access. Use the Windows API--the above link goes into details. Add User Authentication To Your App Of course, another way is for your app to require each user to identify him/herself at launch--this would work even if "run as" was used to impersonate another user. You could check this against valid users maintained by your application or through a repo such as active directory and then use that User's name to compose the user-path string you originally tried to detect. Inspect Event Log Data: With your feedback (in comments), I have a different take that might work for you. The Windows event log records successful desktop logon with Event ID 4624 under the Windows Logs -> Security event viewer branch. That event contains a timestamp value. It seems to me that if you filter these event log entries by Event ID 4624 and grab the latest one that indicates a Security ID of a user on the domain in question (you decide exactly how to filter this based on your needs), you should be able to determine the user ID of the user who "owns the desktop", as your post requested. I don't see how this approach could fail. I do understand that you might have access issues to the Event Log data, but I think that this might happen only for the non-Admin security context. In that case, System.Security.Principal.WindowsIdentity.GetCurrent().Name should give you the non-Admin user name every time; if that returns an Admin user name, then--and only then--would you need to delve into the Event Log in order to do your analysis. You can find posts (such as Read event viewer entries) that help you explore the Event Log from C#.
1) Using SSH passwordless login: One way to achieve that is to first install Git Bash on your Windows machine. This will also install several helper utilities including scp and ssh. Once you have those in place, you can then simply follow the instructions explained here. Pasting snippet from above link for reference. stage('SCP JAR file') { steps { bat '"c:\\Program Files\\git\\usr\\bin\\ssh.exe" -i "c:\\Users\\tom\\.ssh\\azure\\id_rsa" [email protected] ls -ltr' } } 2) Using password authentication: Using SSH is the preferred practice however, for any reason, if that's not feasible, you can connect using password authentication. Follow these steps: a) Change PasswordAuthentication no to PasswordAuthentication yes in /etc/ssh/sshd_config file on your Linux instance. Restart sshd service. Set password for the user with which you want to connect. Use passwd command for it. All steps mentioned in below link. https://aws.amazon.com/premiumsupport/knowledge-center/ec2-password-login/ b) You may use PuTTY to connect using password. Refer this link: https://unix.stackexchange.com/questions/116672/running-linux-script-on-remote-linux-system-using-putty Above link explains how you can use a file (containing commands) option and it also specifies how you can run a single command using the PuTTY Remote command box which is present in SSH section. In the fig. shown below, if i connect using a user ubuntu, it will create a directory abc under /home/ubuntu and after that PuTTY will exit immediately. Using command file option: putty.exe -ssh [email protected] -pw password -m C:\local\file\containing_command 3) Using plink: You can download the executable from here In case you wish to run multiple commands, create a file containing all your commands. For example, Content of cmds.txt: hostname touch file ls -ltr Command: c:\test>plink -ssh [email protected] -pw centos -m cmds.txt Output: Note: In case you're noticing that the first command runs and the second doesn't, try changing the format of your command file from: first_cmd ; second_cmd to first_cmd second_cmd Also, don't forget to press Enter after the last command. Your file should look something like this:
There are several things that you need to consider when moving from V4 to V5 it involves some changes and also you can consider using features like the hooks. The first change will be removing the Switch Navigator and conditionally render the navigator in its place. This will be done in your App.js. As you already have a reducer based implementation you can use the state values to take this decision. The next change will be the creation of stacks, in V4 you create the navigation by passing the screen, now everything is a component and you pass the screens as children. The option are also sent as props to either the navigator or the screen itself. The usage of navigation ref is still possible but you can also use hooks like usenavigation inside components and for your authentication flow you wont be using this as you conditionally render the navigators. I have made a simplified version based on your code. App.js const AuthStack = createStackNavigator(); const AppTabs = createMaterialBottomTabNavigator(); const ArticleStack = createStackNavigator(); const Articles = () => { return ( <ArticleStack.Navigator> <AppTabs.Screen name="ArticlesList" component={ArticleList} /> <AppTabs.Screen name="ArticlesDetails" component={ArticleDetail} /> </ArticleStack.Navigator> ); }; export default function App() { const [state, dispatch] = React.useReducer(authReducer, { isLoading: true, token: null, errorMessage: '', }); React.useEffect(() => { const bootstrapAsync = async () => { const userToken = await AsyncStorage.getItem('userToken'); dispatch({ type: 'RESTORE_TOKEN', token: userToken }); }; bootstrapAsync(); }, []); const authContext = React.useMemo( () => ({ signIn: async (data) => { dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' }); }, signOut: () => dispatch({ type: 'SIGN_OUT' }), signUp: async (data) => { dispatch({ type: 'SIGN_IN', token: 'dummy-auth-token' }); }, }), [] ); return ( <AuthContext.Provider value={authContext}> <NavigationContainer> {state.token === null ? ( <AuthStack.Navigator headerMode="none"> {state.isLoading ? ( <AuthStack.Screen name="Welcome" component={WelcomeScreen} /> ) : ( <> <AuthStack.Screen name="SignIn" component={SignInScreen} /> <AuthStack.Screen name="SignUp" component={SingUpScreen} /> </> )} </AuthStack.Navigator> ) : ( <AppTabs.Navigator activeColor="#f0edf6" inactiveColor="#3e2465" barStyle={{ backgroundColor: '#694fad' }}> <AppTabs.Screen name="Articles" component={Articles} options={{ tabBarLabel: 'Home', tabBarIcon: ({ color, size }) => ( <MaterialCommunityIcons name="home" color={color} size={size} /> ), }} /> <AppTabs.Screen name="Search" component={SearchScreen} /> <AppTabs.Screen name="Save" component={SaveScreen} /> <AppTabs.Screen name="Account" component={AccountScreen} /> </AppTabs.Navigator> )} </NavigationContainer> </AuthContext.Provider> ); } Auth Context const AuthContext = React.createContext(); export default AuthContext; Auth Reducer export const authReducer = (state, action) => { switch (action.type) { case 'RESTORE_TOKEN': return { ...state, token: action.token, isLoading: false, }; case 'SIGN_IN': { return { errorMessage: '', token: action.payload, }; } case 'SIGN_OUT': { return { errorMessage: '', token: null, }; } default: return state; } }; As you can see the flow will be showing the welcome screen till the token is loaded from async storage and then based on that show the tabs or the login screen. Also the parameters are passed as props. I've moved the actions to app.js but it can be separated as well. You can see a fully running sample here https://snack.expo.io/@guruparan/navigation-sample-3 Hope this helps, Feel free to ask if there are any questions.
Recently I faced the exact same error as I was trying to integrate my angular application to enable authentication for JWT based authentication using spring security. I see what you are missing in your security configuration. Maybe that is the problem. First of all, if you configure everything related to CORS in your security configuration then you don't need to create filter or extend WebMvcConfigurer. Below is what you are missing in your security config. http.csrf().disable().cors().configurationSource(corsConfigurationSource()) Here is complete code I copied and pasted it from my working code which I fixed yesterday. @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .configurationSource(corsConfigurationSource()) .and() .csrf() .disable() .authorizeRequests() .anyRequest() .authenticated() .and() .oauth2Login(); } And then cors config code is which is almost same as yours. @Bean CorsConfigurationSource corsConfigurationSource() { CorsConfiguration configuration = new CorsConfiguration(); configuration.setAllowedOrigins(Arrays.asList("*")); configuration.setAllowedMethods(Arrays.asList("HEAD", "GET", "PUT", "POST", "DELETE", "PATCH")); configuration.setAllowCredentials(true); //the below three lines will add the relevant CORS response headers configuration.addAllowedOrigin("*"); configuration.addAllowedHeader("*"); configuration.addAllowedMethod("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", configuration); return source; } Remove your MyCorsFilter and WebConfig class. Both are not needed.
When I looked at the file with a hex editor, I saw a lot of repeating patterns, which implied weak XOR encryption. Long strings of the 0x05 byte really made this seem likely, which I suspected were spaces (0x20) in the original Lua file. I XOR'd every byte of the file with 0x25 to test this theory, and it worked! Here's the result: EnterGame = { } -- private variables local loadBox local enterGame local motdWindow clientBox = nil local protocolLogin local motdEnabled = true local progressWindow local startTime -- private functions local function onError(protocol, message, errorCode) if loadBox then loadBox:destroy() loadBox = nil end if enterGame:getChildById('rememberPasswordBox'):isChecked() then --local account = g_crypt.xorCrypt(G.account, 123) --local password = g_crypt.xorCrypt(G.password, 123) local account = g_crypt.encrypt(G.account) local password = g_crypt.encrypt(G.password) if account ~= "" and password ~= "" then g_settings.set('account', account) g_settings.set('password', password) ServerList.setServerAccount(G.host, account) ServerList.setServerPassword(G.host, password) end else -- reset server list account/password ServerList.setServerAccount(G.host, '') ServerList.setServerPassword(G.host, '') EnterGame.clearAccountFields() end local errorBox = displayErrorBox(tr('Login Error'), message) connect(errorBox, { onOk = EnterGame.show }) end local function onMotd(protocol, motd) G.motdNumber = tonumber(motd:sub(0, motd:find("\n"))) G.motdMessage = motd:sub(motd:find("\n") + 1, #motd) if motdEnabled then end end local function onCharacterList(protocol, characters, account, otui) -- Try add server to the server list ServerList.add(G.host, G.port, g_game.getClientVersion()) if enterGame:getChildById('rememberPasswordBox'):isChecked() then local account = g_crypt.encrypt(G.account) local password = g_crypt.encrypt(G.password) --local account = g_crypt.xorCrypt(G.account, 123) --local password = g_crypt.xorCrypt(G.password, 123) if account ~= "" and password ~= "" then g_settings.set('account', account) g_settings.set('password', password) ServerList.setServerAccount(G.host, account) ServerList.setServerPassword(G.host, password) end else -- reset server list account/password ServerList.setServerAccount(G.host, '') ServerList.setServerPassword(G.host, '') EnterGame.clearAccountFields() end loadBox:destroy() loadBox = nil CharacterList.create(characters, account, otui) CharacterList.show() if motdEnabled then local lastMotdNumber = g_settings.getNumber("motd") if G.motdNumber and G.motdNumber ~= lastMotdNumber then g_settings.set("motd", G.motdNumber) motdWindow = displayInfoBox(tr('Message of the day'), G.motdMessage) connect(motdWindow, { onOk = function() CharacterList.show() motdWindow = nil end }) CharacterList.hide() end end end -- public functions function EnterGame.init() connect(g_app, { onExit = onExitFunc }) enterGame = g_ui.displayUI('entergame') g_keyboard.bindKeyDown('Ctrl+G', EnterGame.openWindow) local account = g_settings.get('account') local password = g_settings.get('password') local host = g_settings.get('host') local port = g_settings.get('port') local clientVersion = g_settings.getInteger('client-version') local proxy = g_settings.get('proxy') if clientVersion == 0 then clientVersion = 772 end if port == nil or port == 0 then port = 7181 end if account ~= "" then EnterGame.setAccountName(account) end if password ~= "" then EnterGame.setPassword(password) end enterGame:getChildById('serverHostTextEdit'):setText(host) enterGame:getChildById('serverPortTextEdit'):setText(port) clientBox = enterGame:getChildById('clientComboBox') clientBox:addOption("Prosperity") clientBox:addOption("Encounter") clientBox:addOption("Redemption") clientBox:addOption("War") --clientBox:addOption("test") clientBox:setCurrentOption(proxy) clientBox.menuHeight = 97 --clientBox:hide() enterGame:hide() if g_app.isRunning() and not g_game.isOnline() then enterGame:show() end end function EnterGame.terminate() disconnect(g_app, { onExit = onExitFunc }) g_keyboard.unbindKeyDown('Ctrl+G') enterGame:destroy() enterGame = nil clientBox = nil if motdWindow then motdWindow:destroy() motdWindow = nil end if loadBox then loadBox:destroy() loadBox = nil end if protocolLogin then protocolLogin:cancelLogin() protocolLogin = nil end cancelDownload() EnterGame = nil end function EnterGame.show() if modules.client.startBox or modules.client.failDownloadBox or modules.client.finishBox or modules.client.failCheckBox then return false end if modules.client.updateBox and modules.client.updateBox:isVisible() then return false end if g_game.isLogging() or CharacterList.isVisible() then return false end if loadBox or progressWindow then return end enterGame:show() enterGame:raise() enterGame:focus() end function EnterGame.hide() enterGame:hide() end function EnterGame.openWindow() if g_game.isOnline() then CharacterList.show() elseif not g_game.isLogging() and not CharacterList.isVisible() then EnterGame.show() end end function EnterGame.setAccountName(account) local account = g_crypt.decrypt(account) --local account = g_crypt.xorCrypt(account, 123) enterGame:getChildById('accountNameTextEdit'):setText(account) enterGame:getChildById('accountNameTextEdit'):setCursorPos(-1) enterGame:getChildById('rememberPasswordBox'):setChecked(#account > 0) end function EnterGame.setPassword(password) local password = g_crypt.decrypt(password) --local password = g_crypt.xorCrypt(password, 123) enterGame:getChildById('accountPasswordTextEdit'):setText(password) end function EnterGame.clearAccountFields() local accountText = enterGame:getChildById('accountNameTextEdit') local passwordText = enterGame:getChildById('accountPasswordTextEdit') if accountText:getText() ~= "" then accountText:clearText() end if passwordText:getText() ~= "" then passwordText:clearText() end enterGame:getChildById('accountNameTextEdit'):focus() g_settings.remove('account') g_settings.remove('password') end function EnterGame.doLogin(cast, cams) G.account = enterGame:getChildById('accountNameTextEdit'):getText() G.password = enterGame:getChildById('accountPasswordTextEdit'):getText() G.host = enterGame:getChildById('serverHostTextEdit'):getText() G.port = tonumber(enterGame:getChildById('serverPortTextEdit'):getText()) local clientVersion = tonumber("772") EnterGame.hide() if g_game.isOnline() then local errorBox = displayErrorBox(tr('Login Error'), tr('You are already logged in.')) connect(errorBox, { onOk = EnterGame.show }) return end g_settings.set('host', G.host) g_settings.set('port', G.port) g_settings.set('client-version', clientVersion) g_settings.set('proxy', clientBox:getCurrentOption().text) protocolLogin = ProtocolLogin.create() protocolLogin.onLoginError = onError protocolLogin.onMotd = onMotd protocolLogin.onCharacterList = onCharacterList protocolLogin.onUpdateNeeded = onUpdateNeeded loadBox = displayCancelBox(tr('Please wait'), tr('Your character list is being loaded. Please wait.')) connect(loadBox, { onCancel = function(msgbox) loadBox = nil protocolLogin:cancelLogin() EnterGame.show() end }) g_game.setProtocolVersion(g_game.getClientProtocolVersion(clientVersion)) g_game.chooseRsa(G.host) if modules.game_things.isLoaded() then if clientBox:getCurrentOption().text == "Redemption" then G.port = "7171" elseif clientBox:getCurrentOption().text == "Prosperity" then G.port = "7175" elseif clientBox:getCurrentOption().text == "War" then G.port = "7181" elseif clientBox:getCurrentOption().text == "test" then G.port = "7177" elseif clientBox:getCurrentOption().text == "Encounter" then G.port = "7185" end if cast then G.account = "" end if cams then G.account = "" G.port = 7194 end protocolLogin:login(G.host, G.port, G.account, G.password) else loadBox:destroy() loadBox = nil EnterGame.show() end end function EnterGame.displayMotd() if not motdWindow then motdWindow = displayInfoBox(tr('Message of the day'), G.motdMessage) motdWindow.onOk = function() motdWindow = nil end end end function EnterGame.setDefaultServer(host, port, protocol) local hostTextEdit = enterGame:getChildById('serverHostTextEdit') local portTextEdit = enterGame:getChildById('serverPortTextEdit') local clientLabel = enterGame:getChildById('clientLabel') local accountTextEdit = enterGame:getChildById('accountNameTextEdit') local passwordTextEdit = enterGame:getChildById('accountPasswordTextEdit') if hostTextEdit:getText() ~= host then hostTextEdit:setText(host) portTextEdit:setText(port) accountTextEdit:setText('') passwordTextEdit:setText('') end end function EnterGame.setUniqueServer(host, port, protocol, windowWidth, windowHeight) local hostTextEdit = enterGame:getChildById('serverHostTextEdit') hostTextEdit:setText(host) hostTextEdit:setVisible(false) hostTextEdit:setHeight(0) local portTextEdit = enterGame:getChildById('serverPortTextEdit') portTextEdit:setText(port) portTextEdit:setVisible(false) portTextEdit:setHeight(0) local portLabel = enterGame:getChildById('portLabel') portLabel:setVisible(false) portLabel:setHeight(0) local clientLabel = enterGame:getChildById('clientLabel') clientLabel:setVisible(false) clientLabel:setHeight(0) local serverListButton = enterGame:getChildById('serverListButton') serverListButton:setVisible(false) serverListButton:setHeight(0) serverListButton:setWidth(0) local rememberPasswordBox = enterGame:getChildById('rememberPasswordBox') if not windowWidth then windowWidth = 240 end enterGame:setWidth(windowWidth) if not windowHeight then windowHeight = 230 end enterGame:setHeight(windowHeight) end function EnterGame.setServerInfo(message) local label = enterGame:getChildById('serverInfoLabel') label:setText(message) end function EnterGame.disableMotd() motdEnabled = false end
Asymmetric encryption is done with the Public Key and the decryption is performed with the Private Key. As the app has to be capable to decrypt the data the app needs to know the Private Key and that's the problem with the common used algorithms, because for RSA or ECIES the Public key can get derived from the Private key. Therefore it's not a real problem to derive the Public key and store changed/appended data after encryption with the Public key. Second thing is - you did not specify how "large" your text will be - some KB, MB, GB? Some months ago I tested some "new" algorithms that are "Post quantum safe" and as an example I used the McEliece Fujisaki algorithm that is available with the Bouncy Castle Crypto provider (I used version 1.65, bcprov-jdk15to18-165.jar). The program creates a 50 MB large byte array that gets encrypted with the Public key and decrypted with the Private key. At the moment I did not find any Public key deriving methods so you definitely need to know the Private and the Public key. I did not test larger byte arrays because this parameter depends on the memory of the target system (you need the double memory as the complete data is captured in ciphertextByte and then again in decryptedtextByte). Edit June 16th 2020: President James K. Polk programmed a method that easily retrieves a public key from a given private key. The source is available in his GitHub-Repo (https://github.com/james-k-polk/McEliece/blob/master/McElieceRecoverPublicFromPrivate.java) and for later convenience shown at the end of this answer. So everyone that has access to a private McEliece key is been able to encrypt data with the retrieved public key! Thanks to President James for his help. Here are the outputs on the console: McEliece Fujisaki Pqc Encryption key generation PrivateKey length: 4268 algorithm: McEliece-CCA2 format: PKCS#8 PublicKey length: 103429 algorithm: McEliece-CCA2 format: X.509 initialize cipher for encryption pt length: 52428800 (50 mb) ct length: 52429056 (50 mb) initialize cipher for decryption dt length: 52428800 (50 mb) compare plaintext <-> decryptedtext: true class McElieceFujisakiPqcEncryptionLargeData.java import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.params.AsymmetricKeyParameter; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.pqc.crypto.mceliece.*; import org.bouncycastle.pqc.jcajce.provider.BouncyCastlePQCProvider; import org.bouncycastle.pqc.jcajce.provider.mceliece.BCMcElieceCCA2PrivateKey; import org.bouncycastle.pqc.jcajce.provider.mceliece.BCMcElieceCCA2PublicKey; import java.security.*; import java.util.Arrays; import java.util.Random; public class McElieceFujisakiPqcEncryptionLargeData { public static void main(String[] args) throws InvalidCipherTextException { System.out.println("McEliece Fujisaki Pqc Encryption"); if (Security.getProvider("BCPQC") == null) { Security.addProvider(new BouncyCastlePQCProvider()); // used Bouncy Castle: bcprov-jdk15to18-165.jar } System.out.println("key generation"); SecureRandom keyRandom = new SecureRandom(); McElieceCCA2Parameters params = new McElieceCCA2Parameters(); McElieceCCA2KeyPairGenerator mcElieceCCA2KeyGen = new McElieceCCA2KeyPairGenerator(); McElieceCCA2KeyGenerationParameters genParam = new McElieceCCA2KeyGenerationParameters(keyRandom, params); mcElieceCCA2KeyGen.init(genParam); AsymmetricCipherKeyPair pair = mcElieceCCA2KeyGen.generateKeyPair(); AsymmetricKeyParameter mcEliecePrivateKey = pair.getPrivate(); AsymmetricKeyParameter mcEliecePublicKey = pair.getPublic(); PrivateKey privateKey = new BCMcElieceCCA2PrivateKey((McElieceCCA2PrivateKeyParameters) pair.getPrivate()); // conversion neccessary only for key data PublicKey publicKey = new BCMcElieceCCA2PublicKey((McElieceCCA2PublicKeyParameters) pair.getPublic()); // conversion neccessary only for key data System.out.println("PrivateKey length: " + privateKey.getEncoded().length + " algorithm: " + privateKey.getAlgorithm() + " format: " + privateKey.getFormat()); System.out.println("PublicKey length: " + publicKey.getEncoded().length + " algorithm: " + publicKey.getAlgorithm() + " format: " + publicKey.getFormat()); // generate cipher for encryption System.out.println("\ninitialize cipher for encryption"); ParametersWithRandom param = new ParametersWithRandom(mcEliecePublicKey, keyRandom); McElieceFujisakiCipher mcElieceFujisakiDigestCipher = new McElieceFujisakiCipher(); mcElieceFujisakiDigestCipher.init(true, param); // random plaintext byte[] plaintext = new byte[52428800]; // 50 mb, 50 * 1024 * 1024 new Random().nextBytes(plaintext); System.out.println("pt length: " + plaintext.length + " (" + (plaintext.length / (1024 * 1024)) + " mb)"); byte[] ciphertext = mcElieceFujisakiDigestCipher.messageEncrypt(plaintext); System.out.println("ct length: " + ciphertext.length + " (" + (ciphertext.length / (1024 * 1024)) + " mb)"); System.out.println("\ninitialize cipher for decryption"); mcElieceFujisakiDigestCipher.init(false, mcEliecePrivateKey); byte[] decryptedtext = mcElieceFujisakiDigestCipher.messageDecrypt(ciphertext); System.out.println("dt length: " + decryptedtext.length + " (" + (decryptedtext.length / (1024 * 1024)) + " mb)"); System.out.println("\ncompare plaintext<-> decryptedtext: " + Arrays.equals(plaintext, decryptedtext)); } } Public key Retrieval class by President James K. Polk, available under MIT-Licence: package com.github.jameskpolk; import org.bouncycastle.crypto.AsymmetricCipherKeyPair; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.pqc.crypto.mceliece.*; import org.bouncycastle.pqc.jcajce.provider.mceliece.BCMcElieceCCA2PrivateKey; import org.bouncycastle.pqc.jcajce.provider.mceliece.BCMcElieceCCA2PublicKey; import org.bouncycastle.pqc.math.linearalgebra.*; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; public class McElieceRecoverPublicFromPrivate { private static final SecureRandom RAND = new SecureRandom(); public static AsymmetricCipherKeyPair generateKeyPair() { McElieceCCA2KeyPairGenerator kpg = new McElieceCCA2KeyPairGenerator(); McElieceCCA2Parameters params = new McElieceCCA2Parameters(); McElieceCCA2KeyGenerationParameters genParam = new McElieceCCA2KeyGenerationParameters(RAND, params); kpg.init(genParam); return kpg.generateKeyPair(); } public static McElieceCCA2PublicKeyParameters recoverPubFromPriv(McElieceCCA2PrivateKeyParameters priv) { GF2mField field = priv.getField(); PolynomialGF2mSmallM gp = priv.getGoppaPoly(); GF2Matrix h = GoppaCode.createCanonicalCheckMatrix(field, gp); Permutation p = priv.getP(); GF2Matrix hp = (GF2Matrix) h.rightMultiply(p); GF2Matrix sInv = hp.getLeftSubMatrix(); GF2Matrix s = (GF2Matrix) sInv.computeInverse(); GF2Matrix shp = (GF2Matrix)s.rightMultiply(hp); GF2Matrix m = shp.getRightSubMatrix(); GoppaCode.MaMaPe mmp = new GoppaCode.MaMaPe(sInv, m, p); GF2Matrix shortH = mmp.getSecondMatrix(); GF2Matrix shortG = (GF2Matrix) shortH.computeTranspose(); // generate public key return new McElieceCCA2PublicKeyParameters( priv.getN(), gp.getDegree(), shortG, priv.getDigest()); } public static void main(String[] args) throws Exception{ // generate a McEliece key pair AsymmetricCipherKeyPair bcKeyPair = generateKeyPair(); McElieceCCA2PrivateKeyParameters bcPriv = (McElieceCCA2PrivateKeyParameters) bcKeyPair.getPrivate(); BCMcElieceCCA2PrivateKey priv = new BCMcElieceCCA2PrivateKey(bcPriv); // get the first public key McElieceCCA2PublicKeyParameters bcPub1 = (McElieceCCA2PublicKeyParameters) bcKeyPair.getPublic(); BCMcElieceCCA2PublicKey pub1 = new BCMcElieceCCA2PublicKey(bcPub1); // Now generate a second public key for the private key McElieceCCA2PublicKeyParameters bcPub2 = recoverPubFromPriv(bcPriv); BCMcElieceCCA2PublicKey pub2 = new BCMcElieceCCA2PublicKey(bcPub2); // print some info about sizes System.out.printf("Size of encrypted messages in bits(bytes): %d(%d)\n", priv.getEncoded().length, priv.getEncoded().length / 8); System.out.printf("private key length: %d\n", bcPriv.getK()); System.out.printf("public key1 length: %d\n", pub1.getEncoded().length); System.out.printf("public key2 length: %d\n", pub2.getEncoded().length); // now encrypt different messages with each public key. String message1 = "Deposits should be made to account # 3.1415929"; String message2 = "Deposits should be made to account # 2.71828"; ParametersWithRandom params1 = new ParametersWithRandom(bcPub1, RAND); ParametersWithRandom params2 = new ParametersWithRandom(bcPub2, RAND); McElieceFujisakiCipher mcElieceFujisakiDigestCipher1 = new McElieceFujisakiCipher(); McElieceFujisakiCipher mcElieceFujisakiDigestCipher2 = new McElieceFujisakiCipher(); mcElieceFujisakiDigestCipher1.init(true, params1); mcElieceFujisakiDigestCipher2.init(true, params2); byte[] ciphertext1 = mcElieceFujisakiDigestCipher1.messageEncrypt(message1.getBytes(StandardCharsets.UTF_8)); byte[] ciphertext2 = mcElieceFujisakiDigestCipher2.messageEncrypt(message2.getBytes(StandardCharsets.UTF_8)); System.out.println("ct1 length: " + ciphertext1.length + " (" + (ciphertext1.length / (1024 * 1024)) + " mb)"); System.out.println("ct2 length: " + ciphertext2.length + " (" + (ciphertext2.length / (1024 * 1024)) + " mb)"); mcElieceFujisakiDigestCipher1.init(false, bcPriv); mcElieceFujisakiDigestCipher2.init(false, bcPriv); byte[] decryptedtext1 = mcElieceFujisakiDigestCipher1.messageDecrypt(ciphertext1); byte[] decryptedtext2 = mcElieceFujisakiDigestCipher2.messageDecrypt(ciphertext2); System.out.printf("Decrypted message 1: %s\n", new String(decryptedtext1, StandardCharsets.UTF_8)); System.out.printf("Decrypted message 2: %s\n", new String(decryptedtext2, StandardCharsets.UTF_8)); } }
Content stored in Amazon S3 is private by default. There are several ways that access can be granted: Use a bucket policy to make the entire bucket (or a directory within it) publicly accessible to everyone. This is good for websites where anyone can read the content. Assign permission to IAM Users to grant access only to users or applications that need to access to the bucket. This is typically used within your organization. Never create an IAM User for somebody outside your organization. Create presigned URLs to grant temporary access to private objects. This is typically used by applications to grant web-based access to content stored in Amazon S3. To provide an example for pre-signed URLs, imagine that you have a photo-sharing website. Photos provided by users are private. The flow would be: A user logs in. The application confirms their identity against a database or an authentication service (eg Login with Google). When the user wants to view a photo, the application first checks whether they are entitled to view the photo (eg it is their photo). If they are entitled to view the photo, the application generates a pre-signed URL and returns it as a link, or embeds the link in an HTML page (eg in a <img> tag). When the user accesses the link, the browser sends the URL request to Amazon S3, which verifies the encrypted signature in the signed URL. If if it is correct and the link has not yet expired, the photo is returned and is displayed in the web browser. Users can also share photos with other users. When another user accesses a photo, the application checks the database to confirm that it was shared with the user. If so, it provides a pre-signed URL to access the photo. This architecture has the application perform all of the logic around Access Permissions. It is very flexible since you can write whatever rules you want, and then the user is sent to Amazon S3 to obtain the file. Think of it like buying theater tickets online -- you just show the ticket and the door and you are allowed to sit in the seat. That's what Amazon S3 is doing -- it is checking the ticket (signed URL) and then giving you access to the file. See: Amazon S3 pre-signed URLs Mobile apps Another common architecture is to generate temporary credentials using the AWS Security Token Service (STS). This is typically done with mobile apps. The flow is: A user logs into a mobile app. The app sends the login details to a back-end application, which verifies the user's identity. The back-end app then uses AWS STS to generate temporary credentials and assigns permissions to the credentials, such as being permitted to access a certain directory within an Amazon S3 bucket. (The permissions can actually be for anything in AWS, such as launching computers or creating databases.) The back-end app sends these temporary credentials back to the mobile app. The mobile app then uses those credentials to make calls directly to Amazon S3 to access files. Amazon S3 checks the credentials being used and, if they have permission for the files being requests, grants access. This can be done for uploads, downloads, listing files, etc. This architecture takes advantage of the fact that mobile apps are quite powerful and they can communicate directly with AWS services such as Amazon S3. The permissions granted are based upon the user who logs in. These permissions are determined by the back-end application, which you would code. Think of it like a temporary employee who has been granted a building access pass for the day, but they can only access certain areas. See: IAM Role Archives - Jayendra's Blog The above architectures are building blocks for how you wish to develop your applications. Every application is different, just like the two use-cases in your question. You can securely incorporate Amazon S3 in your applications while maintaining full control of how access is granted. Your applications can then concentrate on the business logic of controlling access, without having to actually serve the content (which is left up to Amazon S3). It's like selling the tickets without having to run the theater. You ask whether Amazon S3 is "ready for the current reality". Many of the popular web sites you use every day run on AWS, and you probably never realize it.
UPDATE: CORS issue with Google Oauth2 for server side webapps CORS issue while making an Ajax request for oauth2 access token When you use the Authorization code grant (OAuth2 for backend apps - &response_type=code), you must redirect the browser to the /auth endpoint - you cannot use XHR for that. The user will be redirected back after authentication. After redirecting to the /auth endpoint, user needs to see in an address bar that the page is from Google (trusted source) and Google may need to do some more redirects in order to authenticate the user and present the consent page. So using XHR is not possible. You may use UrlBasedCorsConfigurationSource with CorsFilter as used below. Please comment or remove the other CORS configurations and try with it. package com.learning.jhipster.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.filter.CorsFilter; import java.util.Arrays; @Configuration @EnableWebSecurity @EnableGlobalMethodSecurity( securedEnabled = true, jsr250Enabled = true, prePostEnabled = true ) public class SecurityConfig extends WebSecurityConfigurerAdapter { private final CorsFilter corsFilter; public SecurityConfig(@Lazy CorsFilter corsFilter) { this.corsFilter = corsFilter; } @Override protected void configure(HttpSecurity http) throws Exception { http .cors() .disable()//some stackoverflow solution(not accepted) said so .csrf() .disable() .addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class) .authorizeRequests() .anyRequest() .authenticated() .and() .oauth2Login(); } @Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowedOrigins(Arrays.asList("*")); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("OPTIONS"); config.addAllowedMethod("GET"); config.addAllowedMethod("POST"); config.addAllowedMethod("PUT"); config.addAllowedMethod("DELETE"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); } }
You need a comma between each entry. It also doesnt make sense to have the key "users" repeated. That should be your key, then within that key, your list of user parameters/info Couple of other things: I'm not sure what this is doing for you: x = foo["Email"] y = foo["Password"] x == y is True I took it out as x == y will always return False, so I'm not sure why store as x and y variables, and x == y is True just doesn't make sense. Another thing to consider is emails (unlike passwords) are not case sensitive, so you need to anticipate that. so someone should not be able to register [email protected] and [email protected]'s the same email address. So store emails as either all upper or lower case. I made a few minor changes as well, doesn't change the logic, but added a few prints (If wrong password, if email already exists, etc.) You can also continue to add some checks in there too using regex. So things like, email address needs to be in the form of [email protected] So if it doesn't have the @ or .com, .edu, dot whatever, it'll not accept the email address. Or phone number needs to follow a certain pattern. But that you can do later, if needed. You also don't NEED to 'user' key in there (unless you'll be adding some other key into the json later??) I'm not sure as I don't know what your end is to look like or be used for. It doesn't hurt to have it there though, so not a big deal, but it just adds another level that may or may not be needed. Try this: import json import os from main import * from jobs import * def registration(): #### Register a user #### print('Welcome!\nRegister to get started\n') inputdata = {} # Container that will hold user details before writing to a file fullname = input('Full name: ') email = input('Email address: ').lower() phone_number = input('Phone number: ') password = input('Password: ') # append to users dictionary inputdata['users'] = {} inputdata['users'][email] = {} inputdata['users'][email].update({ 'Fullname': fullname, 'Phonenumber': phone_number, 'Password': password }) # appending to a file if os.path.isfile('data.txt'): with open('data.txt', 'r') as users_file: dataFile = json.load(users_file) # Check if email already exists if email in dataFile['users'].keys(): print ('Can not register this email. Email already in use.') return login() dataFile['users'].update(inputdata['users']) with open('data.txt', 'w') as users_file: json.dump(dataFile, users_file, indent=4) else: with open('data.txt', 'w') as users_file: json.dump(inputdata, users_file, indent=4) login() def login(): ''' Check if a user has registered and login the user after authentication''' print('''Don't have an account yet?\n 1. Create account\n 2. Continue to login ''') user_response = input() if user_response == '1': return registration() with open('data.txt') as users_file: data = json.load(users_file) Email = input("Email: ").lower() Password =input("Password: ") userEmailList = list(data['users'].keys()) if Email not in userEmailList: print ('Email is not registered.') return login() fooPassword = data['users'][Email]['Password'] if fooPassword == Password: x = Email y = fooPassword x == y is True #Creates a login session for a staff and saves it to session.txt print (f"Welcome! logged in as {Email}") keyword_post = input('1. Search job by keyword\n2. Register a job') if keyword_post == '1': return keywords() return job_list() else: print('Invalid password.') return login()
You need react-native-modal in order to achieve this behavior. What you have to do is, 1) Create a Modal which contains a TextInput to type password and a Submit button. 2) Once the user clicked on the button in the Home.js screen, the Modal should be opened and ask for the password. (Please make sure that you have a ref to the modal and you have implemented necessary things to open the modal on button press using ref. 3) When the user entered the password, you can authenticate and then navigate to the screen you want if it is authenticated. (You can write the code for authentication and navigation inside your Modal implementation js file.) Here is a sample code... PasswordInputModal.js import React, { Component } from 'react'; import { View, TextInput, Button } from 'react-native'; import Modal from 'react-native-modal'; export default class PasswordInputModal extends Component { constructor(props) { super(props); this.state = { password : '', isVisible : false, navigateTo: null, }; } open = (navigateTo) => this.setState({ isVisible: true, navigateTo: navigateTo }); close = () => this.setState({ isVisible: false }); onPressSubmitButton = () => { //Use any authentication method you want according to your requirement. //Here, it is taken as authenticated if and only if the input password is "12345". const isAuthenticated = ("12345" == this.state.password); //If input password is '12345', isAuthenticated gets true boolean value and false otherwise. if(isAuthenticated) { this.props.navigation.navigate(this.state.navigateTo); } else { console.log("Invalid password"); //Prompt an error alert or whatever you prefer. } this.close(); } renderModalContent = () => ( <View> <TextInput type={'password'} value={this.state.password} onChangeText={(password) => this.setState({ password })} /> <Button onPress={() => this.onPressSubmitButton()} title="Submit" color="#841584" /> </View> ); render() { return ( <Modal isVisible={this.state.isVisible} backdropColor="#000000" backdropOpacity={0.9} animationIn="zoomInDown" animationOut="zoomOutUp" animationInTiming={600} animationOutTiming={600} backdropTransitionInTiming={600} backdropTransitionOutTiming={600} > {this.renderModalContent()} </Modal> ); } } Home.js import React, { Component } from 'react'; import { Text, View, TouchableOpacity, ScrollView } from 'react-native'; import PasswordInputModal from './PasswordInputModal.js' export default class HomeScreen extends Component { render() { return ( <View style={styles.container}> <ScrollView style={styles.flatlist}> <View style={styles.flatlist1}> <TouchableOpacity onPress={() => this.PasswordInputModal.open('Helder')}> <Text style={styles.item}>Empresa do Helder</Text> </TouchableOpacity> </View> <View style={styles.flatlist1}> <TouchableOpacity onPress={() => this.PasswordInputModal.open('Lols')}> <Text style={styles.item}>Lols Inc</Text> </TouchableOpacity> </View> <View style={styles.flatlist1}> <TouchableOpacity onPress={() => this.PasswordInputModal.open('Athlean')}> <Text style={styles.item}>Tesla Portugal</Text> </TouchableOpacity> </View> </ScrollView> <PasswordInputModal ref={modal => this.PasswordInputModal = modal} navigation={this.props.navigation} /> </View> ); } } When opening the modal, I've passed the name of the screen which you want to navigate after successful authentication. That screen name is passed as an argument of the open() function and, a state is set for using when to navigate. I didn't test this code and the styles of the modal are not applied by me. Please go through this and try to do it as you want. Feel free to ask me if you have any problems. Good luck!
To setup Blazor WASM to an existing project you need to : Add a reference to the Blazor WASM project in your ASP.Net Core project Add package reference to Microsoft.AspNetCore.Components.WebAssembly.Server Add UseBlazorFrameworkFiles() in your middleware pipeline Add UseStaticFiles() in your middleware pipeline Add MapFallbackToFile to endpoints pointing to your Blazor WASM index.html public void Configure(IApplicationBuilder app) { if (Environment.IsDevelopment()) { app.UseDeveloperExceptionPage() .UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error") .UseHsts(); } app.UseHttpsRedirection() .UseBlazorFrameworkFiles() .UseStaticFiles() .UseRouting() .UseAuthentication() .UseAuthorization() .UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapFallbackToFile("index.html"); }); }
We differentiate channel types like public and private. Public: Illuminate\Broadcasting\Channel. It works without any authentication, so anonymus users can listen to this broadcast. Like football match scores available for everyone. Private: Illuminate\Broadcasting\PrivateChannel. It works with an authentication, so only authenticated users can listen to this broadcast. Like admins watching what specific users do or user watching their orders status. On the otherhand there is another private channel which is Illuminate\Broadcasting\PresenceChannel. Also require authentication. In example would be much like an any chat room. Ex.: only authenticated users can communicate with each other. So these types will define your method. And you have to follow different paths. I am very suggesting to read the Laravel documentation (https://laravel.com/docs/broadcasting), it will guide you very carefully. In the routes/channels.php you have to decide or verify if the authenticated user can listen on this particular channel. So you have to return boolean value (true or false). So here, you are not returning any value to the client side. Every public property in your MessagePushed broadcast event will be serialized and sent to the client side. You have to give every informational data to the MessagePushed constructor and set to property/properties. Now you can handle the received data by like that, ex: window.Echo = new Echo({ broadcaster: 'socket.io', host: window.location.hostname + ':6001', auth: { headers: { 'X-Auth-Token': "<token>" } } }); window.Echo.private('userInAddProduct') .listen('MessagePushed ', (e) => { console.log(e.auction); }); I recommend to create custom authentication with token usage. Above I sent token to the server to authenticate user. https://laravel.com/docs/authentication#adding-custom-guards In your situation I would separate these two mechanism. check the user for going to the App Product page notify the admin For the 2. point would be enough to use the Illuminate\Broadcasting\PrivateChannel. So there is need for websocket on the admin page. The 1. point could be tricky, because it's depends on your requirments. It is enough to notify the admin about user goes to exact App Product page? If yes, then you will trigger this broadcast event in your controller when user goes to that page. If not enough, then you need another websocket on the user page to "poll" your server and send tick broadcast to the admin in every X seconds. Trigger broadcast event: broadcast(new App\Events\MessagePushed($user)); My taste of usage is: client side: socket.io-client sever side: laravel-echo-server redis broadcaster custom authentication mechanism Hope, I could help!
If you want to manage Azure ARM Resource with Azure Runbook, you can create Run As accounts in your Azure automation account. When we create it, it will create a new service principal user in Azure Active Directory (AD) and assigns the Contributor role to this user at the subscription level. For more details, please refer to the document and the document. For example Create Run As accounts a. Search for and select Automation Accounts. b. On the Automation Accounts page, select your Automation account from the list. c. In the left pane, select Run As Accounts in the account settings section. d. Depending on which account you require, select either Azure Run As Account or Azure Classic Run As Account. e. Depending on the account of interest, use the Add Azure Run As or Add Azure Classic Run As Account pane. After reviewing the overview information, click Create. Create a PowerShell Workflow runbook Script workflow START_STOP_APP_SERVICE_BY_RESOURCE { Param( [Parameter (Mandatory= $true)] [bool]$Stop, [Parameter (Mandatory= $true)] [string]$ResourcegroupName ) try { # use Azure As Account to log in Azure $servicePrincipalConnection=Get-AutomationConnection -Name "AzureRunAsConnection" Add-AzureRmAccount ` -ServicePrincipal ` -TenantId $servicePrincipalConnection.TenantId ` -ApplicationId $servicePrincipalConnection.ApplicationId ` -CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint } catch { if (!$servicePrincipalConnection) { $ErrorMessage = "Connection $connectionName not found." throw $ErrorMessage } else{ Write-Error -Message $_.Exception throw $_.Exception } } $status = 'Stopped' if ($Stop) { $status = 'Running' } # Get Running WebApps (website_Processings_Running) $website_Processings_Running = Get-AzureRMWebAPP -ResourceGroupName $ResourcegroupName | where-object -FilterScript{$_.state -eq $status } foreach -parallel ($website_Processing In $website_Processings_Running) { if ($Stop) { $result = Stop-AzureRmWebApp -ResourceGroupName $ResourcegroupName -Name $website_Processing.Name if($result) { Write-Output "- $($website_Processing.Name) shutdown successfully" } else { Write-Output "+ $($website_Processing.Name) did not shutdown successfully" } } else { $result = Start-AzureRmWebApp -ResourceGroupName $ResourcegroupName -Name $website_Processing.Name if($result) { Write-Output "- $($website_Processing.Name) start successfully" } else { Write-Output "+ $($website_Processing.Name) did not started successfully" } } } }
I've always found bulk-copy to be the best, external to R. The insert can be significantly faster, and your overhead is (1) writing to file, and (2) the shorter run-time. Setup for this test: win10 (2004) docker postgres:11 container, using port 35432 on localhost, simple authentication a psql binary in the host OS (where R is running); should be easy with linux, with windows I grabbed the "zip" (not installer) file from https://www.postgresql.org/download/windows/ and extracted what I needed I'm using data.table::fwrite to save the file because it's fast; in this case write.table and write.csv are still much faster than using DBI::dbWriteTable, but with your size of data you might prefer something quick DBI::dbCreateTable(con2, "mt", mtcars) DBI::dbGetQuery(con2, "select count(*) as n from mt") # n # 1 0 z1000 <- data.table::rbindlist(replicate(1000, mtcars, simplify=F)) nrow(z1000) # [1] 32000 system.time({ DBI::dbWriteTable(con2, "mt", z1000, create = FALSE, append = TRUE) }) # user system elapsed # 1.56 1.09 30.90 system.time({ data.table::fwrite(z1000, "mt.csv") URI <- sprintf("postgresql://%s:%s@%s:%s", "postgres", "mysecretpassword", "127.0.0.1", "35432") system( sprintf("psql.exe -U postgres -c \"\\copy %s (%s) from %s (FORMAT CSV, HEADER)\" %s", "mt", paste(colnames(z1000), collapse = ","), sQuote("mt.csv"), URI) ) }) # COPY 32000 # user system elapsed # 0.05 0.00 0.19 DBI::dbGetQuery(con2, "select count(*) as n from mt") # n # 1 64000 While this is a lot smaller than your data (32K rows, 11 columns, 1.3MB of data), a speedup from 30 seconds to less than 1 second cannot be ignored. Side note: there is also a sizable difference between dbAppendTable (slow) and dbWriteTable. Comparing psql and those two functions: z100 <- rbindlist(replicate(100, mtcars, simplify=F)) system.time({ data.table::fwrite(z100, "mt.csv") URI <- sprintf("postgresql://%s:%s@%s:%s", "postgres", "mysecretpassword", "127.0.0.1", "35432") system( sprintf("/Users/r2/bin/psql -U postgres -c \"\\copy %s (%s) from %s (FORMAT CSV, HEADER)\" %s", "mt", paste(colnames(z100), collapse = ","), sQuote("mt.csv"), URI) ) }) # COPY 3200 # user system elapsed # 0.0 0.0 0.1 system.time({ DBI::dbWriteTable(con2, "mt", z100, create = FALSE, append = TRUE) }) # user system elapsed # 0.17 0.04 2.95 system.time({ DBI::dbAppendTable(con2, "mt", z100, create = FALSE, append = TRUE) }) # user system elapsed # 0.74 0.33 23.59 (I don't want to time dbAppendTable with z1000 above ...) (For kicks, I ran it with replicate(10000, ...) and ran the psql and dbWriteTable tests again, and they took 2 seconds and 372 seconds, respectively. Your choice :-) ... now I have over 650,000 rows of mtcars ... hrmph ... drop table mt ...
Your PHP script is not returning JSON when the login fails. The JavaScript code expect it to return JSON with a result property equal to the string false. But the script returns nothing if the username isn't found, and returns Hello if the username is found but the password is wrong. In the code below I initialize an array with a false result. If authentication succeeds I change that to true and merge in the data from the row. Either way, it echoes the JSON at the end. I've also converted the code to use a prepared statement to prevent SQL injection. <?php function login() { session_start(); // Starts the session for the user include "../../config.php"; // Includes the config file to connect the the database $uName = $_POST['userName']; $pWord = $_POST['password']; $json_array = ['result' => 'false']; $sql = "SELECT * FROM `tbl_police` WHERE Username= ? "; // Selects all data from the tbl_user where email is equal to the user input $stmt = $connection->prepare($sql); $stmt->bind_param("s", $uName); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows === 1) { // If the result is identical to 1 $row = $result->fetch_assoc(); // Fetch result if (password_verify($pWord, $row['Password'])) { // Verify the password against the users input by using the password_verify function. If it's correct... Do this: $json_array['result'] = 'true'; $json_array = array_merge($json_array, $row); $_SESSION['uName'] = $uName; } } mysqli_close($connection); // Close the connection to the database echo json_encode($json_array); } In the jQuery, you should either use dataType: 'json' or dataJson = JSON.parse(msg), but not both. Your code will work as is because you mistyped dataType: (JS is case sensitive).
Yes and no. Java bytecode is much less restrictive than Java (source) in this regard. You can put any bytecode you want before the constructor call, as long as you don't actually access the uninitialized object. (The only operations allowed on an uninitialized this value are calling a constructor, setting private fields declared in the same class, and comparing it against null). Bytecode is also more flexible in where and how you make the constructor call. For example, you can call one of two different constructors in an if statement, or you can wrap the super constructor call in a "try block", both things that are impossible at the Java language level. Apart from not accessing the uninitialized this value, the only restriction* is that the object has to be definitely initialized along any path that returns from the constructor call. This means the only way to avoid initializing the object is to throw an exception. While being much laxer than Java itself, the rules for Java bytecode were still very deliberately constructed so it is impossible to observe uninitialized objects. In general, Java bytecode is still required to be memory safe and type safe, just with a much looser type system than Java itself. Historically, Java applets were designed to run untrusted code in the JVM, so any method of bypassing these restrictions was a security vulnerability. * The above is talking about traditional bytecode verification, as that is what I am most familiar with. I believe stackmap verification behaves similarly though, barring implementation bugs in some versions of Java. P.S. Technically, Java can have code execute before the constructor call. If you pass arguments to the constructor, those expressions are evaluated first, and hence the ability to place bytecode before the constructor call is required in order to compile Java code. Likewise, the ability to set private fields declared in the same class is used to set synthetic variables that arise from the compilation of nested classes. If the class contains final instance fields, I also cannot enter a return before all of those fields have been initialised in the constructor. This, however, is eminently possible. The only restriction is that you call some constructor or superconstructor on the uninitialized this value. (Since all constructors recursively have this restriction, this will ultimately result in java.lang.Object's constructor being called). However, the JVM doesn't care what happens after that. In particular, it only cares that the fields have some well typed value, even if it is the default value (null for objects, 0 for ints, etc.) So there is no need to execute the field initializers to give them a meaningful value. Is there any other way to get the type to be instantiated other than this.getClass() from a super class constructor? Not as far as I am aware. There's no special opcode for magically getting the Class associated with a given value. Foo.class is just syntactic sugar which is handled by the Java compiler.
Try something like this... builder.Services.AddMsalAuthentication(options => { ... options.ProviderOptions.AdditionalScopesToConsent.Add( "https://graph.microsoft.com/Mail.Send"); options.ProviderOptions.AdditionalScopesToConsent.Add( "https://graph.microsoft.com/User.Read"); } https://docs.microsoft.com/en-us/aspnet/core/security/blazor/webassembly/additional-scenarios?view=aspnetcore-3.1#request-additional-access-tokens Hope it helps! EDIT 1: My client Program.cs using System.Net.Http; using Microsoft.AspNetCore.Components.WebAssembly.Authentication; Add the below reference in Index.html page <script src="_content/Microsoft.AspNetCore.Components.WebAssembly.Authentication/AuthenticationService.js"></script> public static async Task Main(string[] args) { var builder = WebAssemblyHostBuilder.CreateDefault(args); builder.RootComponents.Add<App>("app"); builder.Services.AddHttpClient("BlazorWasmAADMsal.ServerAPI", client => client.BaseAddress = new Uri(builder.HostEnvironment.BaseAddress)) .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>(); // Supply HttpClient instances that include access tokens when making requests to the server project builder.Services.AddTransient(sp => sp.GetRequiredService<IHttpClientFactory>().CreateClient("BlazorWasmAADMsal.ServerAPI")); builder.Services.AddMsalAuthentication(options => { builder.Configuration.Bind("AzureAd", options.ProviderOptions.Authentication); options.ProviderOptions.DefaultAccessTokenScopes.Add("api://XXXXXXXXXXXXXXXXXX/API.Access"); }); await builder.Build().RunAsync(); } EDIT 2: Did some minor changes. The working project has been uploaded here. Successful login screen shot added in answer for reference. :-) EDIT 3: Azure Active Directory (AAD) Microsoft Graph API scopes are required by an app to read user data and send mail. After adding the Microsoft Graph API permissions in the Azure AAD portal, the additional scopes are configured in the Client app. Last time i missed to enabled below lines, I have enabled it in Program.cs builder.Services.AddMsalAuthentication(options => { options.ProviderOptions.DefaultAccessTokenScopes.Add("https://graph.microsoft.com/User.Read"); } It was a bizarre error, never expected and had seen it. The reference of AuthenticationService.js in Index.html was not correct. I have corrected it to be... <script src="_content/Microsoft.Authentication.WebAssembly.Msal/AuthenticationService.js"></script> I have also uploaded the latest code here The IAccessTokenProvider.RequestToken method provides an overload that allows an app to provision an access token with a given set of scopes. In a Razor component, you can write something like below: @using Microsoft.AspNetCore.Components.WebAssembly.Authentication @inject IAccessTokenProvider TokenProvider ... var tokenResult = await TokenProvider.RequestAccessToken( new AccessTokenRequestOptions { Scopes = new[] { "https://graph.microsoft.com/Mail.Send", "https://graph.microsoft.com/User.Read" } }); if (tokenResult.TryGetToken(out var token)) { ... } AccessTokenResult.TryGetToken returns: true with the token for use. false if the token isn't retrieved. Hope it helps you.
The solution involves seven PHP files app/Http/Controllers/HomeController.php - homepage controller; the destination for an authenticated user app/Providers/ApiUserProvider.php - a custom provider to bootstrap and register the logged-in user, and implements the interface Illuminate\Contracts\Auth\UserProvider app/CoreExtensions/SessionGuardExtended.php - custom guard-controller to log-in the user and receives the authentication values and stores them in session array; extends class Illuminate\Auth\SessionGuard app/ApiUser - if you're using OAuth2 (Laravel's Passport); custom user class that exposes the OAuth access_token; extends Illuminate\Auth\GenericUser and implements the interface Illuminate\Contracts\Auth\Authenticatable config/auth.php - the auth config which instructs the Auth() facade to return the custom session guard app/Providers/AuthServiceProvider.php - the auth bootstrap app/Providers/AppServiceProvider.php - the main application bootstrap Source research/investigation material are cited for you to investigate for yourself and comprehend the background context to their existence. I make no claims to be a genius who created the solution from scratch through my own mojo, but rather that - like all innovators - I build on the efforts of others. The unique selling point of my article is that I provide a complete packaged solution, whereas the cited sources provide solutions to niche parts of the overall answer. Together, after much trial and error, they helped me to form a complete solution. A really useful article to understands how config/auth.php affects execution in AuthManager.php is https://www.2hatslogic.com/blog/laravel-custom-authentication/ No code modifications are made to the following, but they're included to acknowledge the role they play and their importance in the process: vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php - main authorization factory manager Auth() facade - returns the shrink-wrapped Illuminate\Auth\SessionGuard class instance by default, unless it's instructed to do otherwise through the config/auth.php file - Auth() is used ubiquitously throughout Laravel code to retrieve the session guard The Code app/Http/Controllers/HomeController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; /** * Handles and manages the home-page * * @category controllers */ class HomeController extends Controller { /** * Create a new controller instance. * * @return void */ public function __construct() { $this->middleware('auth'); } public function index() { blah } ... other methods ... } app/Providers/ApiUserProvider.php Sources: Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider) https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication Custom user authentication base on the response of an API call <?php namespace App\Providers; use Illuminate\Contracts\Auth\UserProvider; use Illuminate\Contracts\Auth\Authenticatable as UserContract; use App\ApiUser; /** * Delegates API user login and authentication * * @category providers */ class ApiUserProvider implements UserProvider { /** * Custom API Handler * Used to request API and capture responses * * @var \Path\To\Your\Internal\Api\Handler */ private $_oApi = null; /** * POST request to API * * @param string $p_url Endpoint URL * @param array $p_arrParam Parameters * @param boolean $p_isOAuth2 Is OAuth2 authenticated request? [Optional, Default=True] * * @return array */ private function _post(string $p_url, array $p_arrParam, bool $p_isOAuth2=true) { if (!$this->_oApi) { $this->_oApi = new \Path\To\Your\Internal\Api\Handler(); } $arrResponse = $this->_oApi->post($p_url, $p_arrParam, $p_isOAuth2); return $arrResponse; } /** * GET request to API * * @param string $p_url Endpoint URL * @param array $p_arrParam Parameters [Optional, Default = array()] * * @return array */ private function _get(string $p_url, array $p_arrParam=[], bool $p_isOAuth2=true) { if (!$this->_oApi) { $this->_oApi = new \Path\To\Your\Internal\Api\Handler(); } $arrResponse = $this->_oApi->get($p_url, $p_arrParam); return $arrResponse; } /** * Retrieve a user by the given credentials. * * @param array $p_arrCredentials * * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveByCredentials(array $p_arrCredentials) { $arrResponse = $this->_post('/login', $p_arrCredentials, false); if ( $arrResponse['result'] ) { $arrPayload = array_merge( $arrResponse['data'], $p_arrCredentials ); return $this->getApiUser($arrPayload); } } /** * Retrieve a user by their unique identifier. * * @param mixed $p_id * * @return \Illuminate\Contracts\Auth\Authenticatable|null */ public function retrieveById($p_id) { $arrResponse = $this->_get("user/id/{$p_id}"); if ( $arrResponse['result'] ) { return $this->getApiUser($arrResponse['data']); } } /** * Validate a user against the given credentials. * * @param \Illuminate\Contracts\Auth\Authenticatable $p_oUser * @param array $p_arrCredentials * * @return bool */ public function validateCredentials(UserContract $p_oUser, array $p_arrCredentials) { return $p_oUser->getAuthPassword() == $p_arrCredentials['password']; } /** * Get the api user. * * @param mixed $p_user * * @return \App\Auth\ApiUser|null */ protected function getApiUser($p_user) { if ($p_user !== null) { return new ApiUser($p_user); } return null; } protected function getUserById($id) { $user = []; foreach ($this->getUsers() as $item) { if ($item['account_id'] == $id) { $user = $item; break; } } return $user ?: null; } protected function getUserByUsername($username) { $user = []; foreach ($this->getUsers() as $item) { if ($item['email_address'] == $username) { $user = $item; break; } } return $user ?: null; } /** * The methods below need to be defined because of the Authenticatable contract * but need no implementation for 'Auth::attempt' to work and can be implemented * if you need their functionality */ public function retrieveByToken($identifier, $token) { } public function updateRememberToken(UserContract $user, $token) { } } app/CoreExtensions/SessionGuardExtended.php Sources: Extending Laravel 5.2 SessionGuard Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider) <?php namespace App\CoreExtensions; use Illuminate\Auth\SessionGuard; use Illuminate\Contracts\Auth\Authenticatable; /** * Extended SessionGuard() functionality * Provides added functionality to store the OAuth tokens in the session for later use * * @category guards * * @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard */ class SessionGuardExtended extends SessionGuard { /** * Log a user into the application. * * @param \Illuminate\Contracts\Auth\Authenticatable $p_oUser * @param bool $p_remember * @return void */ public function login(Authenticatable $p_oUser, $p_remember = false) { parent::login($p_oUser, $p_remember); /** * Writing the OAuth tokens to the session */ $key = 'authtokens'; $this->session->put( $key, [ 'access_token' => $p_oUser->getAccessToken(), 'refresh_token' => $p_oUser->getRefreshToken(), ] ); } /** * Log the user out of the application. * * @return void */ public function logout() { parent::logout(); /** * Deleting the OAuth tokens from the session */ $this->session->forget('authtokens'); } } app/ApiUser Sources: Using Laravel 5.8 authentication with external JSON API (Creating own ServiceProvider) *https://laracasts.com/discuss/channels/laravel/replacing-the-laravel-authentication-with-a-custom-authentication Custom user authentication base on the response of an API call <?php namespace App; use Illuminate\Auth\GenericUser; use Illuminate\Contracts\Auth\Authenticatable as UserContract; class ApiUser extends GenericUser implements UserContract { /** * Returns the OAuth access_token * * @return mixed */ public function getAccessToken() { return $this->attributes['access_token']; } public function getRefreshToken() { return $this->attributes['refresh_token']; } } app/Providers/AuthServiceProvider.php <?php namespace App\Providers; use Illuminate\Support\Facades\Auth; use Illuminate\Foundation\Support\Providers\AuthServiceProvider as ServiceProvider; class AuthServiceProvider extends ServiceProvider { /** * Register any authentication / authorization services. * * @return void */ public function boot() { $this->registerPolicies(); Auth::provider('frank_sinatra', function ($app, array $config) { // Return an instance of Illuminate\Contracts\Auth\UserProvider... return new ApiUserProvider(); }); } } app/Providers/AppServiceProvider.php Sources: Extending Laravel 5.2 SessionGuard Note: There is a couple of nuanced issues regarding the change to coding in this PHP file. If you want to understand more, look at vendor/laravel/framework/src/Illuminate/Auth/AuthManager.php, AuthManager::resolve() in particular. References to config/auth.php 'session' and 'token' are served by hard-coded methods AuthManager::createSessionDriver() and AuthManager::createTokenDriver() (Tell me please if you know of a way to extend AuthManager.php in the app) AppServiceProvider.php to the rescue! Custom guards can be registered in AppServiceProvider::boot() and intercepted before the default code can be executed. I'm OK with point 2 above, but couldn't we do something clever like return the custom session-guard name or instance from AppServiceProvider, have setCookieJar(), setDispatcher(), setRequest() in a specialized public method in AuthManager.php, which can be hooked into AppServiceProvider.php or driven by config/auth.php to execute after creating the custom session-guard in AuthManager.php? Without the cookies or sessions, the user's identity isn't preserved through the redirect. The only way to resolve this is to include the setCookieJar(), setDispatcher() and setRequest() in AppServiceProvider within our current solution. <?php namespace App\Providers; use Illuminate\Support\ServiceProvider; use Illuminate\Support\Facades\Auth; use App\CoreExtensions\SessionGuardExtended; class AppServiceProvider extends ServiceProvider { /** * Register any application services. * * @return void */ public function register() { // } /** * Bootstrap any application services. * * @see https://stackoverflow.com/questions/36087061/extending-laravel-5-2-sessionguard * * @return void */ public function boot() { /** * Extending Illuminate\Auth\SessionGuard() * This is so we can store the OAuth tokens in the session */ Auth::extend( 'sessionExtended', function ($app) { $guard = new SessionGuardExtended( 'sessionExtended', new ApiUserProvider(), app()->make('session.store'), request() ); // When using the remember me functionality of the authentication services we // will need to be set the encryption instance of the guard, which allows // secure, encrypted cookie values to get generated for those cookies. if (method_exists($guard, 'setCookieJar')) { $guard->setCookieJar($this->app['cookie']); } if (method_exists($guard, 'setDispatcher')) { $guard->setDispatcher($this->app['events']); } if (method_exists($guard, 'setRequest')) { $guard->setRequest($this->app->refresh('request', $guard, 'setRequest')); } return $guard; } ); } } config/auth.php Sources: https://www.2hatslogic.com/blog/laravel-custom-authentication/ <?php return [ /* |-------------------------------------------------------------------------- | Authentication Defaults |-------------------------------------------------------------------------- | | This option controls the default authentication "guard" and password | reset options for your application. You may change these defaults | as required, but they're a perfect start for most applications. | */ 'defaults' => [ //'guard' => 'web', /** This refers to the settings under ['guards']['web'] */ 'guard' => 'webextended', /** This refers to the settings under ['guards']['webextended'] */ 'passwords' => 'users', /** This refers to the settings under ['passwords']['users'] */ ], /* |-------------------------------------------------------------------------- | Authentication Guards |-------------------------------------------------------------------------- | | Next, you may define every authentication guard for your application. | Of course, a great default configuration has been defined for you | here which uses session storage and the Eloquent user provider. | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | Supported: "session", "token" | */ 'guards' => [ 'web' => [ 'driver' => 'session', /** This refers to Illuminate/Auth/SessionGuard */ 'provider' => 'users', /** This refers to the settings under ['providers']['users'] */ ], 'webextended' => [ 'driver' => 'sessionExtended', /** @see app/Providers/AppServiceProvider::boot() */ 'provider' => 'users', /** This refers to the settings under ['providers']['users'] */ ], 'api' => [ 'driver' => 'token', /** This refers to Illuminate/Auth/TokenGuard */ 'provider' => 'users', 'hash' => false, ], ], /* |-------------------------------------------------------------------------- | User Providers |-------------------------------------------------------------------------- | | All authentication drivers have a user provider. This defines how the | users are actually retrieved out of your database or other storage | mechanisms used by this application to persist your user's data. | | If you have multiple user tables or models you may configure multiple | sources which represent each model / table. These sources may then | be assigned to any extra authentication guards you have defined. | | Supported: "database", "eloquent" | */ 'providers' => [ 'users' => [ 'driver' => 'frank_sinatra', /** @see app/Providers/AuthServiceProvider::boot() */ //'model' => App\User::class, ], // 'users' => [ // 'driver' => 'database', // 'table' => 'users', // ], ], [ blah ], [ other settings ], ]; How To Use This Solution Very simple. There's no change in the overall approach. In other words, we use the Auth() facade. When logging in with your custom API /login?username=<username>&password=<password> request()->flash(); $arrData = request()->all(); if ( Auth::attempt($arrData, true) ) { return redirect('home'); } else { return back()->withErrors( [ 'username' => "Those credentials can't be found", 'password' => "Those credentials can't be found", ] ); } When logging out with your custom API /logout Auth::logout(); return redirect('home');
In a function parameter, a T[] (where T is char in your case) is really a T*. In C++, a string literal is a const char[N] fixed array, which decays into a const char* pointer to the 1st element. But you don't have any constructors that accept either of those types as a parameter. A const char* can't be given to a char*. You need to add const to your constructors: String(const char s[]) Pstring(const char s[]) Also, calling String(s) in the body of the Pstring constructor does not initialize the Pstring object using the base class String constructor, like you are expecting. It instead constructs a temporary String object that goes out of scope immediately. The Pstring object is not affected by that. The only place that a base class constructor can be called by a derived constructor is in the member initialization list. In your case, there is no such call, so the compiler implicitly calls the base class default (0-param) constructor before entering the body of the derived constructor. Which doesn't help you, since you want the base class to initialize the str buffer with data. One way you can do that is add another constructor to String that takes a user-defined length as input, and then call that from the Pstring constructor, eg: String(const char s[], size_t len) { len = std::min(len, SZ-1); memcpy(str, s, len); str[len] = '\0'; } Pstring::Pstring(const char s[]) : String(s, strlen(s)) { } Note that your 1-param String constructor has a buffer overflow waiting to happen, since the user can directly construct a String object with input that is greater than SZ characters in length. The String constructor should use strncpy() instead of strcpy(): String(const char s[]) { strncpy(str, s, SZ); str[SZ-1] = '\0'; // in case s is >= SZ chars } Which then makes the 1-param Pstring constructor redundant - especially since it is not handling the null terminator correctly to begin with, as the assignment of the terminator needs to be outside of the for loop, eg: Pstring::Pstring(const char s[]) { if (strlen(s) >= SZ) { for (int j = 0; j < SZ - 1; j++) { str[j] = s[j]; } // alternatively: memcpy(str, sz, SZ-1); str[SZ-1] = '\0'; // <-- moved here } else strcpy(str, s); }
You can replace a report's connection info programmatically by looping through the ConnectionInfos and swapping out the provider. There's a (IMO hack-y) explanation about adding connection/driver info here which references an SAP KB that assists in writing DB logon code, but the link in the article is dead (instead, use this one - this may be more-useful for you needs). UPDATE 2020-Jul-7 (includes subreport handling) // Add these using's (for readability in here): using RasTables = CrystalDecisions.ReportAppServer.DataDefModel.Tables; using RasTable = CrystalDecisions.ReportAppServer.DataDefModel.Table; using RasConnectionInfo = CrystalDecisions.ReportAppServer.DataDefModel.ConnectionInfo; // ... /// <summary> /// Updates all of the tables contained within the given Crystal Report with new OLEDB connection parameters /// </summary> /// <param name="reportDocument">A <see cref="CrystalDecisions.CrystalReports.Engine.ReportDocument"/> of the Crystal Report</param> /// <param name="server">The new server (Data Source) to use</param> /// <param name="database">The new database (Initial Catalog) to use</param> /// <param name="oledbProvider">The new OLEDB provider (see remarks)</param> /// <param name="integratedSecurity">Whether to use a trusted connection</param> /// <param name="userId">The new user id to use</param> /// <param name="password">The new user's password</param> /// <remarks>Some valid values for a SQL Server OLEDB provider (note: matching vendor components <b>must</b> be installed)<br/> /// <p> /// <dt>OLEDBSQL</dt> /// <dd>Legacy OLE DB provider for Microsoft SQL Server</dd> /// <dt>SQLNCLI11</dt> /// <dd>SQL Native Client v11</dd> /// <dt>MSOLEDBSQL</dt> /// <dd>latest OLE DB provider for Microsoft SQL Server (use this if TLS 1.0/1.1 are disabled on the SQL Server).</dd> /// </remarks> internal static void ChangeOleDbConnectionInfo(ReportDocument reportDocument, string server, string database, string oledbProvider, bool integratedSecurity, string userId, string password) { // boMainPropertyBag: These hold the attributes of the tables ConnectionInfo object var boMainPropertyBag = new PropertyBag(); // boInnerPropertyBag: These hold the attributes for the QE_LogonProperties // In the main property bag (boMainPropertyBag) var boInnerPropertyBag = new PropertyBag(); // Set the attributes for the boInnerPropertyBag boInnerPropertyBag.Add("Application Intent", "READWRITE"); boInnerPropertyBag.Add("Auto Translate", "-1"); boInnerPropertyBag.Add("Connect Timeout", "15"); boInnerPropertyBag.Add("Data Source", server); boInnerPropertyBag.Add("DataTypeCompatibility", "0"); boInnerPropertyBag.Add("General Timeout", "0"); boInnerPropertyBag.Add("Initial Catalog", database); boInnerPropertyBag.Add("Integrated Security", integratedSecurity ? "True" : "False"); boInnerPropertyBag.Add("Locale Identifier", "1033"); boInnerPropertyBag.Add("MARS Connection", "0"); boInnerPropertyBag.Add("OLE DB Services", "-5"); boInnerPropertyBag.Add("Provider", oledbProvider); boInnerPropertyBag.Add("Tag with column collation when possible", "0"); boInnerPropertyBag.Add("Trust Server Certificate", "0"); boInnerPropertyBag.Add("Use DSN Default Properties", "False"); boInnerPropertyBag.Add("Use Encryption for Data", "0"); // Set the attributes for the boMainPropertyBag boMainPropertyBag.Add("Database DLL", "crdb_ado.dll"); boMainPropertyBag.Add("QE_DatabaseName", database); boMainPropertyBag.Add("QE_DatabaseType", "OLE DB (ADO)"); // Add the QE_LogonProperties we set in the boInnerPropertyBag Object boMainPropertyBag.Add("QE_LogonProperties", boInnerPropertyBag); boMainPropertyBag.Add("QE_ServerDescription", server); boMainPropertyBag.Add("QE_SQLDB", "True"); boMainPropertyBag.Add("SSO Enabled", "False"); // Create a new ConnectionInfo object var boConnectionInfo = new RasConnectionInfo { // Pass the database properties to a connection info object Attributes = boMainPropertyBag, // Set the connection kind Kind = CrConnectionInfoKindEnum.crConnectionInfoKindCRQE }; if (!integratedSecurity) { boConnectionInfo.UserName = userId; boConnectionInfo.Password = password; } // Local function will return a copy of the given table using the provided connection info RasTable CreateBoTableCopy(RasTable originalTable, RasConnectionInfo connectionInfo) { // Create a new Database Table to replace the reports current table. return new RasTable { // Pass the connection information to the table ConnectionInfo = connectionInfo, Name = originalTable.Name, QualifiedName = originalTable.QualifiedName, Alias = originalTable.Alias }; } var reportClientDocument = reportDocument.ReportClientDocument; // Get the Database Tables Collection for your report RasTables boTables = reportClientDocument.DatabaseController.Database.Tables; // For each table in the report, set the report's table location to use a newly-modified // copy of itself with the new connection info foreach (RasTable table in boTables) { reportClientDocument.DatabaseController.SetTableLocation(table, CreateBoTableCopy(table, boConnectionInfo)); } // Now drop this same science on all of the subreports foreach (ReportDocument subreport in reportDocument.Subreports) { var subreportName = subreport.Name; foreach (RasTable table in reportClientDocument.SubreportController.GetSubreportDatabase(subreportName).Tables) { reportClientDocument.SubreportController.SetTableLocation(subreportName, table, CreateBoTableCopy(table, boConnectionInfo)); } } // Verify the database after adding substituting the new table to ensure that the table // updates properly when adding Command tables or Stored Procedures. reportDocument.VerifyDatabase(); } Usage: var newSqlProvider = "MSOLEDBSQL"; if (!string.IsNullOrWhiteSpace(overrideSqlProvider)) ChangeOleDbConnectionInfo(myReportDocument, newServerName, newDatabase, newSqlProvider, false, userName, userPassword);
In your startup.cs app.UseOktaMvc(new OktaMvcOptions() { OktaDomain = ConfigurationManager.AppSettings["okta:OktaDomain"], ClientId = ConfigurationManager.AppSettings["okta:ClientId"], ClientSecret = ConfigurationManager.AppSettings["okta:ClientSecret"], RedirectUri = ConfigurationManager.AppSettings["okta:RedirectUri"], PostLogoutRedirectUri = ConfigurationManager.AppSettings["okta:PostLogoutRedirectUri"], Scope = new List<string> { "openid", "profile", "email", "offline_access" }, }); In your web.config make sure you have redirect uri as below <add key="okta:RedirectUri" value="https://localhost:{port}/authorization-code/callback" /> You should not write controller for this route. This is provided by the Okta.AspNet package already. The sign in process is handled by this route itself unless you want to do something out of the box. Your default route's action should look something like: if (!HttpContext.User.Identity.IsAuthenticated) { HttpContext.GetOwinContext().Authentication.Challenge(OpenIdConnectAuthenticationDefaults.AuthenticationType); return new HttpUnauthorizedResult(); } return RedirectToAction("Index", "Home"); Now, you should be able to read all the userclaims in your application. var claims = HttpContext.GetOwinContext().Authentication.User.Claims.ToList(); You can also decorate your controllers/action by [Authorize] attribute to secure them from unauthenticated access.
You can use Gmail SMTP via TLS private static String USER_NAME = "Gmail Username"; // GMail user name (just the part before "@gmail.com") private static String PASSWORD = "gbxxfgfhujdfqndd"; // GMail password public static boolean sendEmail(String RECIPIENT, String sub, String title, String body, String under_line_text, String end_text) { String from = USER_NAME; String pass = PASSWORD; String[] to = { RECIPIENT }; // list of recipient email addresses String subject = sub; Properties props = System.getProperties(); String host = "smtp.gmail.com"; props.put("mail.smtp.starttls.enable", "true"); props.put("mail.smtp.host", host); props.put("mail.smtp.user", from); props.put("mail.smtp.password", pass); props.put("mail.smtp.port", "587"); props.put("mail.smtp.auth", "true"); Session session = Session.getDefaultInstance(props); MimeMessage message = new MimeMessage(session); try { message.setFrom(new InternetAddress(from)); InternetAddress[] toAddress = new InternetAddress[to.length]; // To get the array of addresses for (int i = 0; i < to.length; i++) { toAddress[i] = new InternetAddress(to[i]); } for (int i = 0; i < toAddress.length; i++) { message.addRecipient(Message.RecipientType.TO, toAddress[i]); } message.setSubject(subject); BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "<div style=\" background-color: white;width: 25vw;height:auto;border: 20px solid grey;padding: 50px;margin:100 auto;\">\n" + "<h1 style=\"text-align: center;font-size:1.5vw\">" + title + "</h1>\n" + "<div align=\"center\">" + "<h2 style=\"text-align: center;font-size:1.0vw\">" + body + "</h2>" + "<h3 style=\"text-align: center;text-decoration: underline;text-decoration-color: red;font-size:0.9vw\">" + under_line_text + "</h3><br><h4 style=\"text-align: center;font-size:0.7vw\">" + end_text + " </h4></div>"; messageBodyPart.setContent(htmlText, "text/html"); Multipart multipart = new MimeMultipart(); // Set text message part multipart.addBodyPart(messageBodyPart); message.setContent(multipart); Transport transport = session.getTransport("smtp"); transport.connect(host, from, pass); transport.sendMessage(message, message.getAllRecipients()); transport.close(); } catch (AddressException ae) { ae.printStackTrace(); } catch (MessagingException me) { me.printStackTrace(); } return true; } Or Gmail via SSL in which you should add //change port number prop.put("mail.smtp.port", "465"); prop.put("mail.smtp.socketFactory.port", "465"); prop.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); Output: Also you can change BodyPart accordingly i have included an html responsive template I recommend you to visit your Google Account and generate a new Application Password , this allows your password field to be encoded and not used as plain text Otherwise you will come up with this exception javax.mail.AuthenticationFailedException: 534-5.7.9 Application-specific password required. Hope it helped!
I'm not sure if this totally answers your question and I'm a bit confused by what you want. but from what I'm understanding, I followed this documentation here:https://docs.microsoft.com/en-us/microsoftteams/platform/bots/how-to/authentication/add-authentication?tabs=dotnet%2Cdotnet-sample the sample has a bot that authenticates with azure ad, it pops up the azure log in window every time for me in teams. a please sign in button appears, then you click sign in, and it pops up the login window which then you can get the token for and use that to call graph and etc. I tested this out and when I talk to the bot, it always asks me to sign in, so hopefully this is what you're looking for? if not, please specify which part its missing, thanks edit: the instructions are for the aad v1 endpoint, but if you want to use the v2 endpoint, it's nearly the same. just less to type, also you need to enter the scopes that you give api permissions to, eg "User.Read User.ReadBasic.All etc etc" Update So upon further discussion I saw what your issue was. what you need to do is the following. in the bot channels registration -> settings -> oauthconnectionsettings, take note of your values and delete it. Then create a new one, under same name, with these parameters, service provider: Oauth 2 Generic Provider ClientID: same as before secret: same as before. scope list delimiter: ' ' authorization URL Template: https://login.microsoftonline.com/common/oauth2/v2.0/authorize (Replace Common with your tenant, just because i was using common) Auth URL Query string template (this is key): ?client_id={ClientId}&response_type=code&redirect_uri={RedirectUrl}&scope={Scopes}&state={State}&prompt=login token url template: https://login.microsoftonline.com/common/oauth2/v2.0/token (again replace common with your tenant id) token url query string tempalte : ? token body template: code={Code}&grant_type=authorization_code&redirect_uri={RedirectUrl}&client_id={ClientId}&client_secret={ClientSecret} refresh url template: https://login.microsoftonline.com/common/oauth2/v2.0/token (again replace common with your tenant id) refresh url query string: ? refresh body template: refresh_token={RefreshToken}&redirect_uri={RedirectUrl}&grant_type=refresh_token&client_id={ClientId}&client_secret={ClientSecret} scopes: Mail.Read Mail.Send User.Read User.ReadBasic.All (or whatever your scopes are)
Let's discuss from the very beginning: JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective. So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user. The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. Just like this, the user is authenticated and basically logged into our application without leaving any state on the server. So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application. So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless. Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route. Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system. So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted. So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server. And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token. So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature. But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.
You have to call the AuthenticationManagerin your custom subclass of AbstractAuthenticationProcessingFilter, see Spring Security Reference: The filter calls the configured AuthenticationManager to process each authentication request. See also AbstractAuthenticationProcessingFilter#attemptAuthentication: Performs actual authentication. The implementation should do one of the following: Return a populated authentication token for the authenticated user, indicating successful authentication Return null, indicating that the authentication process is still in progress. Before returning, the implementation should perform any additional work required to complete the process. Throw an AuthenticationException if the authentication process fails Your implementation doesn't return an authenticated token, see logs: SecurityContext stored to HttpSession: 'org.springframework.security.core.context.SecurityContextImpl@17085d: Authentication: com.mycompany.myapp.configuration.MyToken@17085d: Principal: null; Credentials: [PROTECTED]; Authenticated: false; Details: null; Not granted any authorities' See also: GaeAuthenticationFilter UsernamePasswordAuthenticationFilter OpenIDAuthenticationFilter CasAuthenticationFilter
Since you have App Service Authentication/Authorization enabled, that will already validate the token. It assumes things about your token structure, such as having the audience and issuer be the same as your app URL (as a default). app.UseAppServiceAuthentication() will also validate the token, as it is meant for local development. So in your example, the token will be validated twice. Aside from the potential performance impact, this is generally fine. However, that means the tokens must pass validation on both layers, and I suspect that this is not the case, hence the error. One way to check this is to inspect the tokens themselves. Set a breakpoint in your client app and grab the token you get from LoginAsync(), which will be part of that user object. Then head to a service like http://jwt.io to see what the token contents look like. I suspect that the Facebook token will have a different aud and iss claim than the Identifiers.Environment.ApiUrl you are configuring for app.UseAppServiceAuthentication(), while the custom token probably would match it since you're using that value in your first code snippet. If that holds true, than you should be in a state where both tokens are failing. The Facebook token would pass the hosted validation but fail on the local middleware, while the custom token would fail the hosted validation but pass the local middleware. The simplest solution here is to remove app.UseAppServiceAuthentication() when hosting in the cloud. You will also need to make sure that your call to CreateToken() uses the cloud-based URL as the audience and issuer. For other folks that find this issue The documentation for custom authentication can be found here. A general overview of App Service Authentication / Authorization can be found here.
Hi You can write Custom backend for this problem. from django.contrib.auth.hashers import check_password from django.contrib.auth.models import User from apps.staffs.models import Staff(Custom User) class StaffBackend: # Create an authentication method # This is called by the standard Django login procedure def authenticate(self, username=None, password=None): try: # Try to find a user matching your username user = Staff.objects.get(username=username) # Check the password is the reverse of the username if check_password(password, user.password): # Yes? return the Django user object return user else: # No? return None - triggers default login failed return None except Staff.DoesNotExist: # No user was found, return None - triggers default login failed return None # Required for your backend to work properly - unchanged in most scenarios def get_user(self, user_id): try: return Staff.objects.get(pk=user_id) except Staff.DoesNotExist: return None
So, finally I came out with a solution. In my case I don't need the session middleware from passport, as I'm developing a REST API. First, the passport declaration in config.json: "passport": { "enabled": true, "priority": 10, "module": { "name": "passport", "method": "initialize" } } Then in index.js, I say passport to use my strategy: passport.use(auth.localApiKeyStrategy()); Finally, in the controller of the model I implemented a custom callback as the Passport docs say you can, that I located in auth.js router.get('/', function(req, res, next) { auth.authenticate(req, res, next, function() { // authenticated // stuff to do when authenticated }); }); // auth.js exports.authenticate = function(req, res, next, callback) { passport.authenticate('localapikey', function(err, device) { if (err) { return next(err); } if (!device) { err = new Error(); err.code = statusWell.UNAUTHORIZED; return next(err); } callback(); })(req, res, next); }; Now I can handle authentication and pass the error to my errorHandler middleware later using the next function.
To use Common Crypto from Swift Add a bridging header Add #import <CommonCrypto/CommonCrypto.h> to the header. The example uses CBC mode and prefixes the encrypted data with the IV which is a method generally used for handling the IV. Example from deprecated documentation section: AES encryption in CBC mode with a random IV (Swift 3.0) The iv is prefixed to the encrypted data aesCBC128Encrypt will create a random IV and prefixed to the encrypted code. aesCBC128Decrypt will use the prefixed IV during decryption. Inputs are the data and key are Data objects. If an encoded form such as Base64 if required convert to and/or from in the calling method. The key should be exactly 128-bits (16-bytes), 192-bits (24-bytes) or 256-bits (32-bytes) in length. If another key size is used an error will be thrown. PKCS#7 padding is set by default. This example requires Common Crypto It is necessary to have a bridging header to the project: #import <CommonCrypto/CommonCrypto.h> Add the Security.framework to the project. This is example, not production code. enum AESError: Error { case KeyError((String, Int)) case IVError((String, Int)) case CryptorError((String, Int)) } // The iv is prefixed to the encrypted data func aesCBCEncrypt(data:Data, keyData:Data) throws -> Data { let keyLength = keyData.count let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256] if (validKeyLengths.contains(keyLength) == false) { throw AESError.KeyError(("Invalid key length", keyLength)) } let ivSize = kCCBlockSizeAES128; let cryptLength = size_t(ivSize + data.count + kCCBlockSizeAES128) var cryptData = Data(count:cryptLength) let status = cryptData.withUnsafeMutableBytes {ivBytes in SecRandomCopyBytes(kSecRandomDefault, kCCBlockSizeAES128, ivBytes) } if (status != 0) { throw AESError.IVError(("IV generation failed", Int(status))) } var numBytesEncrypted :size_t = 0 let options = CCOptions(kCCOptionPKCS7Padding) let cryptStatus = cryptData.withUnsafeMutableBytes {cryptBytes in data.withUnsafeBytes {dataBytes in keyData.withUnsafeBytes {keyBytes in CCCrypt(CCOperation(kCCEncrypt), CCAlgorithm(kCCAlgorithmAES), options, keyBytes, keyLength, cryptBytes, dataBytes, data.count, cryptBytes+kCCBlockSizeAES128, cryptLength, &numBytesEncrypted) } } } if UInt32(cryptStatus) == UInt32(kCCSuccess) { cryptData.count = numBytesEncrypted + ivSize } else { throw AESError.CryptorError(("Encryption failed", Int(cryptStatus))) } return cryptData; } // The iv is prefixed to the encrypted data func aesCBCDecrypt(data:Data, keyData:Data) throws -> Data? { let keyLength = keyData.count let validKeyLengths = [kCCKeySizeAES128, kCCKeySizeAES192, kCCKeySizeAES256] if (validKeyLengths.contains(keyLength) == false) { throw AESError.KeyError(("Invalid key length", keyLength)) } let ivSize = kCCBlockSizeAES128; let clearLength = size_t(data.count - ivSize) var clearData = Data(count:clearLength) var numBytesDecrypted :size_t = 0 let options = CCOptions(kCCOptionPKCS7Padding) let cryptStatus = clearData.withUnsafeMutableBytes {cryptBytes in data.withUnsafeBytes {dataBytes in keyData.withUnsafeBytes {keyBytes in CCCrypt(CCOperation(kCCDecrypt), CCAlgorithm(kCCAlgorithmAES128), options, keyBytes, keyLength, dataBytes, dataBytes+kCCBlockSizeAES128, clearLength, cryptBytes, clearLength, &numBytesDecrypted) } } } if UInt32(cryptStatus) == UInt32(kCCSuccess) { clearData.count = numBytesDecrypted } else { throw AESError.CryptorError(("Decryption failed", Int(cryptStatus))) } return clearData; } Example usage: let clearData = "clearData0123456".data(using:String.Encoding.utf8)! let keyData = "keyData890123456".data(using:String.Encoding.utf8)! print("clearData: \(clearData as NSData)") print("keyData: \(keyData as NSData)") var cryptData :Data? do { cryptData = try aesCBCEncrypt(data:clearData, keyData:keyData) print("cryptData: \(cryptData! as NSData)") } catch (let status) { print("Error aesCBCEncrypt: \(status)") } let decryptData :Data? do { let decryptData = try aesCBCDecrypt(data:cryptData!, keyData:keyData) print("decryptData: \(decryptData! as NSData)") } catch (let status) { print("Error aesCBCDecrypt: \(status)") } Example Output: clearData: <636c6561 72446174 61303132 33343536> keyData: <6b657944 61746138 39303132 33343536> cryptData: <92c57393 f454d959 5a4d158f 6e1cd3e7 77986ee9 b2970f49 2bafcf1a 8ee9d51a bde49c31 d7780256 71837a61 60fa4be0> decryptData: <636c6561 72446174 61303132 33343536> Notes: One typical problem with CBC mode example code is that it leaves the creation and sharing of the random IV to the user. This example includes generation of the IV, prefixed the encrypted data and uses the prefixed IV during decryption. This frees the casual user from the details that are necessary for CBC mode. For security the encrypted data also should have authentication, this example code does not provide that in order to be small and allow better interoperability for other platforms. Also missing is key derivation of the key from a password, it is suggested that PBKDF2 be used is text passwords are used as keying material. For robust production ready multi-platform encryption code see RNCryptor.
My code. this is sample. @Autowired private ProductService productService; @RequestMapping(value = "/settings/product") public ModelAndView showProduct(ModelAndView mav, HttpServletRequest req, Authentication auth) { CustomUserDetail customUserDetail = (CustomUserDetail) auth.getPrincipal(); int associationIdx = customUserDetail.getAccount().getAssociation().getIdx(); String language = CookieUtil.getCookieValue(req, "lang"); Association association = associationService.findAssociationByIdx(associationIdx); List<AssociationProductColumnDefine> columns = associationService.findByAssociationAndLanguage(association, language); List<AssociationProductColumnDefine> source = associationService.findByAssociationAndLanguage(association, "ko-kr"); mav.addObject("association", association); mav.addObject("source", source); mav.addObject("columns", columns); mav.setViewName("/association/association_settings_product"); return mav; } Yes, you choice model and ModelAndView. Yes, simple.
Hey i worked alot with Preferences and this code seems the best for me ! easy to maintain , you can custom it , and add encryption for example ;). in this class "MyPref" you can custom the type of data stored in you preferences. public class MyPref implements SharedPreferences { private SharedPreferences sharedPreferences; public MyPref(Context context, final String sharedPrefFilename) { if (sharedPreferences == null) { sharedPreferences = getSharedPreferenceFile(context, sharedPrefFilename); } } private SharedPreferences getSharedPreferenceFile(Context context, String prefFilename) { if (TextUtils.isEmpty(prefFilename)) { return PreferenceManager .getDefaultSharedPreferences(context); } else { return context.getSharedPreferences(prefFilename, Context.MODE_PRIVATE); } } //----- SHARED PREFERENCES INTERFACE---- @Override public Map<String, ?> getAll() { return sharedPreferences.getAll(); } @Override public String getString(String s, String s1) { return sharedPreferences.getString(s,s1); } @Override public Set<String> getStringSet(String s, Set<String> set) { return sharedPreferences.getStringSet(s,set); } @Override public int getInt(String s, int i) { return sharedPreferences.getInt(s,i); } @Override public long getLong(String s, long l) { return sharedPreferences.getLong(s,l); } @Override public float getFloat(String s, float v) { return sharedPreferences.getFloat(s,v); } @Override public boolean getBoolean(String s, boolean b) { return sharedPreferences.getBoolean(s,b); } @Override public boolean contains(String s) { return sharedPreferences.contains(s); } @Override public Editor edit() { return new MyEditor(); } @Override public void registerOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { sharedPreferences.registerOnSharedPreferenceChangeListener(listener); } @Override public void unregisterOnSharedPreferenceChangeListener( OnSharedPreferenceChangeListener listener) { sharedPreferences.unregisterOnSharedPreferenceChangeListener(listener); } /** * Inner class implements the Preference editor ,this class is responsible of preference editing (you can add encryption here). */ class MyEditor implements SharedPreferences.Editor { private SharedPreferences.Editor mEditor; private MyEditor() { mEditor = sharedPreferences.edit(); } @Override public Editor putString(String s, String s1) { mEditor.putString(s,s1); return this; } @Override public Editor putStringSet(String s, Set<String> set) { mEditor.putStringSet(s,set); return this; } @Override public Editor putInt(String s, int i) { mEditor.putInt(s,i); return this; } @Override public Editor putLong(String s, long l) { mEditor.putLong(s,l); return this; } @Override public Editor putFloat(String s, float v) { mEditor.putFloat(s,v); return this; } @Override public Editor putBoolean(String s, boolean b) { mEditor.putBoolean(s,b); return this; } @Override public Editor remove(String s) { mEditor.remove(s); return this; } @Override public Editor clear() { mEditor.clear(); return this; } @Override public boolean commit() { return mEditor.commit(); } @Override public void apply() { mEditor.apply(); } } } in this class you have just to add the Key & Getter and Setter public class Pref { private static final String MY_KEY1 = "MY_KEY1"; private static final String MY_KEY2 = "MY_KEY2"; private static final String MY_KEY3 = "MY_KEY3"; private static final String PREF_FILENAME = "MY_PREF_FILENAME"; private static SharedPreferences getSharedPreferences(Context context) { return new MyPref(context , PREF_FILENAME); } private static SharedPreferences.Editor getEditor(Context context) { return getSharedPreferences(context) .edit(); } /* You have just to ADD you KEY & Getter and Setter*/ public static void putKey1(Context context, String date) { getEditor(context).putString(MY_KEY1, date).apply(); } public static String getKey1(Context context) { return getSharedPreferences(context).contains(MY_KEY1) ? getSharedPreferences(context).getString(MY_KEY1, null) : null; } public static void putKey2(Context context, String date) { getEditor(context).putString(MY_KEY1, date).apply(); } public static String getKey2(Context context) { return getSharedPreferences(context).contains(MY_KEY2) ? getSharedPreferences(context).getString(MY_KEY2, null) : null; } public static void putKey3(Context context, String date) { getEditor(context).putString(MY_KEY1, date).apply(); } public static String getKey3(Context context) { return getSharedPreferences(context).contains(MY_KEY3) ? getSharedPreferences(context).getString(MY_KEY3, null) : null; } } Use : public class MainActivity extends Activity { TextView hello; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Pref.putKey1(this,"HELLO FROM PREFS"); hello = (TextView) findViewById(R.id.hello); hello.setText(Pref.getKey1(this)); } }
PHP: For decoding authentication_code part, here is a code snippet that you can refer to implement. function jsonWebTokenBase64Decode($string) { $string = str_replace('-', '+', $string); $string = str_replace('_', '/', $string); switch (strlen($string) % 4) { case 0: break; case 2: $string .= '=='; break; case 3: $string .= '='; break; default: throw createInvalidAuthenticationTokenException(); } return base64_decode($string); } function jsonWebTokenBase64Encode($string) { $string = base64_encode($string); $string = trim($string, '='); $string = str_replace('+', '-', $string); return str_replace('/', '_', $string); } function decodeAuthenticationToken($authenticationToken, $clientSecret) { // Break the token into segments delimited by dots and verify there are three segments $segments = explode('.', $authenticationToken); if (count($segments) != 3) { throw createInvalidAuthenticationTokenException(); } // Decode the segments to extract two JSON objects and the signature $envelope = json_decode(jsonWebTokenBase64Decode($segments[0]), true); $claims = json_decode(jsonWebTokenBase64Decode($segments[1]), true); $signature = $segments[2]; // If the authentication token is expired, return false if ($claims['exp'] < time()) { return false; } // Verify that the algorithm and token type are correct if ($envelope['alg'] != 'HS256') { throw createInvalidAuthenticationTokenException(); } if ($envelope['typ'] != 'JWT') { throw createInvalidAuthenticationTokenException(); } // Compute the signing key by hashing the client secret $encodedClientSecret = utf8_encode($clientSecret . 'JWTSig'); $signingKey = hash('sha256', $encodedClientSecret, true); // Concatenate the first two segments of the token and perform an HMAC hash with the signing key $input = utf8_encode($segments[0] . '.' . $segments[1]); $hashValue = hash_hmac('sha256', $input, $signingKey, true); // Validate the token by base64 encoding the hash value and comparing it to the signature $encodedHashValue = jsonWebTokenBase64Encode($hashValue); if ($encodedHashValue != $signature) { throw createInvalidAuthenticationTokenException(); } // If the token passes validation, return the user ID stored in the token return $claims['uid']; }
Just Follow these Steps for Google SignIn: 1.) Create a Project at Google Developers Console Log in to Google Plus account and click on create project.Creating google project 2.) Fill the details according to your choice, Then Now we need a configuration file for our android app.Select your app we just created on developer console. And write the package name of your android studio project you had created. Finally choose country and click on continue. 3.) Hit this command to Cmd for finding the SHA1 key. For windows: keytool -list -v -keystore "%USERPROFILE%\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android For Linux: keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android Copy the SHA1 and paste it to the Enable Google Services Page. Now click on Enable Google Signin. And click on Continue to Generate Configuration Files. Now click on download google-services.json to get your configuration file. Now come to android studio. Copy the json configuration file (you just downloaded) and paste it inside your google login android studio project (Inside app/ directory). Like this configuration file Open the Top Level build.gradle file and add the following line inside dependencies. classpath 'com.google.gms:google-services:1.5.0-beta2' Inside build.gradle file add the following dependencies and sync your google login android project. compile 'com.google.android.gms:play-services-auth:8.3.0' compile 'com.mcxiaoke.volley:library-aar:1.0.0' // this is for fetching the profile image of the user Now come to activity_main.xml. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin"> <com.google.android.gms.common.SignInButton android:id="@+id/sign_in_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_horizontal" /> <com.android.volley.toolbox.NetworkImageView android:id="@+id/profileImage" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="Name" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textViewName" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:text="email" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <TextView android:id="@+id/textViewEmail" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout> Now come to MainActivity.java and write the following code. import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.android.volley.toolbox.ImageLoader; import com.android.volley.toolbox.NetworkImageView; import com.google.android.gms.auth.api.Auth; import com.google.android.gms.auth.api.signin.GoogleSignInAccount; import com.google.android.gms.auth.api.signin.GoogleSignInOptions; import com.google.android.gms.auth.api.signin.GoogleSignInResult; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.SignInButton; import com.google.android.gms.common.api.GoogleApiClient; import org.w3c.dom.Text; public class MainActivity extends AppCompatActivity implements View.OnClickListener, GoogleApiClient.OnConnectionFailedListener { //Signin button private SignInButton signInButton; //Signing Options private GoogleSignInOptions gso; //google api client private GoogleApiClient mGoogleApiClient; //Signin constant to check the activity result private int RC_SIGN_IN = 100; //TextViews private TextView textViewName; private TextView textViewEmail; private NetworkImageView profilePhoto; //Image Loader private ImageLoader imageLoader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //Initializing Views textViewName = (TextView) findViewById(R.id.textViewName); textViewEmail = (TextView) findViewById(R.id.textViewEmail); profilePhoto = (NetworkImageView) findViewById(R.id.profileImage); //Initializing google signin option gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN) .requestEmail() .build(); //Initializing signinbutton signInButton = (SignInButton) findViewById(R.id.sign_in_button); signInButton.setSize(SignInButton.SIZE_WIDE); signInButton.setScopes(gso.getScopeArray()); //Initializing google api client mGoogleApiClient = new GoogleApiClient.Builder(this) .enableAutoManage(this /* FragmentActivity */, this /* OnConnectionFailedListener */) .addApi(Auth.GOOGLE_SIGN_IN_API, gso) .build(); //Setting onclick listener to signing button signInButton.setOnClickListener(this); } //This function will option signing intent private void signIn() { //Creating an intent Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient); //Starting intent for result startActivityForResult(signInIntent, RC_SIGN_IN); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); //If signin if (requestCode == RC_SIGN_IN) { GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data); //Calling a new function to handle signin handleSignInResult(result); } } //After the signing we are calling this function private void handleSignInResult(GoogleSignInResult result) { //If the login succeed if (result.isSuccess()) { //Getting google account GoogleSignInAccount acct = result.getSignInAccount(); //Displaying name and email textViewName.setText(acct.getDisplayName()); textViewEmail.setText(acct.getEmail()); //Initializing image loader imageLoader = CustomVolleyRequest.getInstance(this.getApplicationContext()) .getImageLoader(); imageLoader.get(acct.getPhotoUrl().toString(), ImageLoader.getImageListener(profilePhoto, R.mipmap.ic_launcher, R.mipmap.ic_launcher)); //Loading image profilePhoto.setImageUrl(acct.getPhotoUrl().toString(), imageLoader); } else { //If login fails Toast.makeText(this, "Login Failed", Toast.LENGTH_LONG).show(); } } @Override public void onClick(View v) { if (v == signInButton) { //Calling signin signIn(); } } @Override public void onConnectionFailed(ConnectionResult connectionResult) { } } For loading image from URL I have used a Custom Volley Request.For the custom volley request you have to create the following class. import android.content.Context; import android.graphics.Bitmap; import android.support.v4.util.LruCache; import com.android.volley.Cache; import com.android.volley.Network; import com.android.volley.RequestQueue; import com.android.volley.toolbox.BasicNetwork; import com.android.volley.toolbox.DiskBasedCache; import com.android.volley.toolbox.HurlStack; import com.android.volley.toolbox.ImageLoader; public class CustomVolleyRequest { private static CustomVolleyRequest customVolleyRequest; private static Context context; private RequestQueue requestQueue; private ImageLoader imageLoader; private CustomVolleyRequest(Context context) { this.context = context; this.requestQueue = getRequestQueue(); imageLoader = new ImageLoader(requestQueue, new ImageLoader.ImageCache() { private final LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(20); @Override public Bitmap getBitmap(String url) { return cache.get(url); } @Override public void putBitmap(String url, Bitmap bitmap) { cache.put(url, bitmap); } }); } public static synchronized CustomVolleyRequest getInstance(Context context) { if (customVolleyRequest == null) { customVolleyRequest = new CustomVolleyRequest(context); } return customVolleyRequest; } public RequestQueue getRequestQueue() { if (requestQueue == null) { Cache cache = new DiskBasedCache(context.getCacheDir(), 10 * 1024 * 1024); Network network = new BasicNetwork(new HurlStack()); requestQueue = new RequestQueue(cache, network); requestQueue.start(); } return requestQueue; } public ImageLoader getImageLoader() { return imageLoader; } Now add internet permission to your manifest and run your google login android application. This,is all the full process for G-SignIn Authentication !!!
I solved the problem, here is the solution. I tried all variants of the code injection method but the problem was the the YouTube API script was defining an anonymous function that expected the window as an input argument. So even after following the advice of not loading external scripts (chrome web store might remove your extension) and having a local file that I included with different means I was not able to get the onYouTubeIframeAPIReady to be triggered by the YouTube API script. Only after pasting the script into the same file where I defined onYouTubeIframeAPIReady I was able to see the video. However to organize the code better, so it works with ES6 imports (via Webpack) I did the following steps. Download the YouTube API script (https://www.youtube.com/iframe_api see https://developers.google.com/youtube/iframe_api_reference) to a local file. Adopt the script to work as module by changing the the script from (function(){var g,k=this;function l(a){a=a.split("."); ... Ub=l("onYouTubePlayerAPIReady");Ub&&Ub();})(); to export default function(){var g,k=window;function l(a){a=a.split(".") ... Ub=l("onYouTubePlayerAPIReady");Ub&&Ub();} This changes the anonymous function call to a function that is exported in a ES6 module style and the this object in the anonymous function is exchanged with the window. I saved it in the file as youtube-iframe-api.js Now I was able to use the YouTube API in another module with the following code import youtubeApi from './youtube-iframe-api'; function onPlayerReady(event) { event.target.playVideo(); }, window.onYouTubeIframeAPIReady = () => { this.player = new YT.Player('youtube-iframe', { height: '100', width: '100', videoId: 'M7lc1UVf-VE', events: { 'onReady': onPlayerReady, } }); } youtubeApi();
You need to add different authentication filters for each different endpoint. For HttpSecurity you can define something like this, giving the constructor your UserDetailsService and passing the authentication manager as well: .addFilterBefore(new FirstLoginFilter("/api/login/first", userDetailsService, authenticationManager()), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new SecondLoginFilter("/api/login/second", userDetailsService, authenticationManager()), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(new AdminLoginFilter("/api/login/admin", userDetailsService, authenticationManager()), UsernamePasswordAuthenticationFilter.class) The implementation for the filters would look something like this. Let's start with abstract authentication filter which is parent for all the above ones: public abstract class LoginFilter extends AbstractAuthenticationProcessingFilter { protected final SimpleUserDetailsService userService; public LoginFilter(String pattern, SimpleUserDetailsService userService, AuthenticationManager authManager) { super(new AntPathRequestMatcher(pattern)); this.userService = userService; this.setAuthenticationManager(authManager); this.setAuthenticationSuccessHandler(new FormAuthenticationSuccessHandler()); this.setAuthenticationFailureHandler(new FormAuthenticationFailureHandler()); } protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authentication) throws ServletException { User authenticatedUser = this.userService.loadUserByUsername(authentication.getName()); UserAuthentication userAuthentication = new UserAuthentication(authenticatedUser); SecurityContextHolder.getContext().setAuthentication(userAuthentication); } } And for example one of the implementations for the actual filter: public class FirstLoginFilter extends LoginFilter { public FirstLoginFilter(String pattern, SimpleUserDetailsService userDetailsService, AuthenticationManager authManager) { super(pattern, userDetailsService, authManager); } public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException { User user = (User)(new ObjectMapper()).readValue(request.getInputStream(), User.class); UsernamePasswordAuthenticationToken loginToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword()); Authentication authentication = this.getAuthenticationManager().authenticate(loginToken); if(!Role.isRolePresent(authentication.getAuthorities(), Role.YOUR_ROLE)) { throw new BadCredentialsException("Bad credentials"); } else { return authentication; } } } My example uses stateless authentication mechanism, so you need to modify the filter accordingly. As I see from your initial example, you are using sessions instead, so in fact it should be much easier for you, since it is already built in to Spring Security Hope it helps.
Raw signing is nothing more than modular exponentiation. Now there seem to be two options, but basically only one will remain. I'll explain below. First of all, you'd think that using a Signature with "NoneWithRSA" should work. The algorithm does exist, but unfortunately it still pads; it just strips the ASN.1 structure indicating the hash function and value. So that one is not available. Although signing is not the same as encryption, both operations in the end rely on modular exponentiation. So it is fortunately possible to use a Cipher instance to create the functionality you need: Security.addProvider(new BouncyCastleProvider()); Cipher rsa = Cipher.getInstance("RSA/ECB/NoPadding", BouncyCastleProvider.PROVIDER_NAME); rsa.init(Cipher.DECRYPT_MODE, kp.getPrivate()); byte[] signatureUsingCipher = rsa.doFinal("owlstead" .getBytes(StandardCharsets.UTF_8)); System.out.println(Hex.toHexString(signatureUsingCipher)); Now one thing to notice here is that Bouncy Castle does perform a somewhat different operation than the SunJCE provider of Oracle. Instead of just removing the padding, it also forgets to put the ciphertext through the I2OSP algorithm (see the PKCS#1 standard), which properly encodes to the output size of the modulus. So you can have a smaller ciphertext than 128 bytes for specific key / plaintext combinations. This is very easy to see by encrypting the value 0, where the output will be zero bytes. Finally note that specifying Cipher.ENCRYPT mode or Cipher.DECRYPT mode doesn't make a difference; both simply perform modular exponentiation. However, Cipher.DECRYPT is more likely to expect a private key, which is why I used it in above code. You can generate a key pair for testing above code like this: KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.generateKeyPair(); Warning: signature generation without secure padding is insecure; it may result in existential forgery attacks. You can only use this as building block for to create a secure scheme.
Dot Net 3.5 and onward introduced many shortcut keywords that abstract away the complexity of things like Parallel for multi threading or Async for Async IO. Unfortunately this also provides no opportunity for understanding whats involved in these tasks. For example a colleague of mine was recently trying to use Async for a login method which returned an authentication token. Here is the full blown multi threaded sample code for your scenario. to make it more real the sample code pretends that: X is Longitude Y is Lattitude and Z is Rainfall Samples at the coordinates The sample code also follows the Unit of Work design pattern where Rainfall Samples at each coordinate becomes a work item. It also creates discrete foreground threads instead of using a background threadpool. Due to the simplicity of the work item and short compute time involved I've split the thread synchronization locks into two locks. one for the work queue and one for the output data. Note: I have not used any Dot net shortcuts such as Lync so this code should run on Dot Net 2.0 as well. In real world app development something like whats below would only be needed in complex scenarios such as stream processing of a continuous stream of work items in which case you would also need to implement output data buffers cleared regularly as the threads would effectively run forever. public static class MultiThreadSumRainFall { const int LongitudeSize = 64; const int LattitudeSize = 64; const int RainFallSamplesSize = 64; const int SampleMinValue = 0; const int SampleMaxValue = 1000; const int ThreadCount = 4; public static void SumRainfallAndOutputValues() { int[][][] SampleData; SampleData = GenerateSampleRainfallData(); for (int Longitude = 0; Longitude < LongitudeSize; Longitude++) { for (int Lattitude = 0; Lattitude < LattitudeSize; Lattitude++) { QueueWork(new WorkItem(Longitude, Lattitude, SampleData[Longitude][Lattitude])); } } System.Threading.ThreadStart WorkThreadStart; System.Threading.Thread WorkThread; List<System.Threading.Thread> RunningThreads; WorkThreadStart = new System.Threading.ThreadStart(ParallelSum); int NumThreads; NumThreads = ThreadCount; if (ThreadCount < 1) { NumThreads = 1; } else if (NumThreads > (Environment.ProcessorCount + 1)) { NumThreads = Environment.ProcessorCount + 1; } OutputData = new int[LongitudeSize, LattitudeSize]; RunningThreads = new List<System.Threading.Thread>(); for (int I = 0; I < NumThreads; I++) { WorkThread = new System.Threading.Thread(WorkThreadStart); WorkThread.Start(); RunningThreads.Add(WorkThread); } bool AllThreadsComplete; AllThreadsComplete = false; while (!AllThreadsComplete) { System.Threading.Thread.Sleep(100); AllThreadsComplete = true; foreach (System.Threading.Thread WorkerThread in RunningThreads) { if (WorkerThread.IsAlive) { AllThreadsComplete = false; } } } for (int Longitude = 0; Longitude < LongitudeSize; Longitude++) { for (int Lattitude = 0; Lattitude < LattitudeSize; Lattitude++) { Console.Write(string.Concat(OutputData[Longitude, Lattitude], @" ")); } Console.WriteLine(); } } private class WorkItem { public WorkItem(int _Longitude, int _Lattitude, int[] _RainFallSamples) { Longitude = _Longitude; Lattitude = _Lattitude; RainFallSamples = _RainFallSamples; } public int Longitude { get; set; } public int Lattitude { get; set; } public int[] RainFallSamples { get; set; } } public static int[][][] GenerateSampleRainfallData() { int[][][] Result; Random Rnd; Rnd = new Random(); Result = new int[LongitudeSize][][]; for(int Longitude = 0; Longitude < LongitudeSize; Longitude++) { Result[Longitude] = new int[LattitudeSize][]; for (int Lattidude = 0; Lattidude < LattitudeSize; Lattidude++) { Result[Longitude][Lattidude] = new int[RainFallSamplesSize]; for (int Sample = 0; Sample < RainFallSamplesSize; Sample++) { Result[Longitude][Lattidude][Sample] = Rnd.Next(SampleMinValue, SampleMaxValue); } } } return Result; } private static object SyncRootWorkQueue = new object(); private static Queue<WorkItem> WorkQueue = new Queue<WorkItem>(); private static void QueueWork(WorkItem SamplesWorkItem) { lock(SyncRootWorkQueue) { WorkQueue.Enqueue(SamplesWorkItem); } } private static WorkItem DeQueueWork() { WorkItem Samples; Samples = null; lock (SyncRootWorkQueue) { if (WorkQueue.Count > 0) { Samples = WorkQueue.Dequeue(); } } return Samples; } private static int QueueSize() { lock(SyncRootWorkQueue) { return WorkQueue.Count; } } private static object SyncRootOutputData = new object(); private static int[,] OutputData; private static void SetOutputData(int Longitude, int Lattitude, int SumSamples) { lock(SyncRootOutputData) { OutputData[Longitude, Lattitude] = SumSamples; } } private static void ParallelSum() { WorkItem SamplesWorkItem; int SummedResult; SamplesWorkItem = DeQueueWork(); while (SamplesWorkItem != null) { SummedResult = 0; foreach (int SampleValue in SamplesWorkItem.RainFallSamples) { SummedResult += SampleValue; } SetOutputData(SamplesWorkItem.Longitude, SamplesWorkItem.Lattitude, SummedResult); SamplesWorkItem = DeQueueWork(); } } }
Default code snippet. Just Replace the above code snippet with the one given below in Startup.Auth.cs class and replace your own Consumer Key and Consumer Secret. app.UseTwitterAuthentication(new TwitterAuthenticationOptions { ConsumerKey = "XXXXXXXXXXXXXXXXXXXXXX", ConsumerSecret = " XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX ", BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary CA - G5 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3 "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5 "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA }) });
You can loop from list of legacy user, and do create Liferay users by using this class: package com.yourcompany.yourapp.util; import java.util.Date; import java.util.List; import org.apache.log4j.Logger; import com.liferay.counter.service.CounterLocalServiceUtil; import com.liferay.portal.kernel.dao.orm.DynamicQuery; import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil; import com.liferay.portal.kernel.dao.orm.OrderFactoryUtil; import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.uuid.PortalUUIDUtil; import com.liferay.portal.kernel.workflow.WorkflowConstants; import com.liferay.portal.model.Account; import com.liferay.portal.model.ClassName; import com.liferay.portal.model.Company; import com.liferay.portal.model.Contact; import com.liferay.portal.model.Group; import com.liferay.portal.model.LayoutSet; import com.liferay.portal.model.User; import com.liferay.portal.security.permission.PermissionChecker; import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil; import com.liferay.portal.security.permission.PermissionThreadLocal; import com.liferay.portal.service.AccountLocalServiceUtil; import com.liferay.portal.service.ClassNameLocalServiceUtil; import com.liferay.portal.service.CompanyLocalServiceUtil; import com.liferay.portal.service.ContactLocalServiceUtil; import com.liferay.portal.service.GroupLocalServiceUtil; import com.liferay.portal.service.LayoutSetLocalServiceUtil; import com.liferay.portal.service.RoleLocalServiceUtil; import com.liferay.portal.service.UserLocalServiceUtil; import com.liferay.portlet.asset.model.AssetEntry; import com.liferay.portlet.asset.service.AssetEntryLocalServiceUtil; public class UserUtil { private static final Logger logger = Logger.getLogger(UserUtil.class); private long companyId; private long creatorUserId; private long accountId; private Date date; public UserUtil() { try { DynamicQuery queryCompany = DynamicQueryFactoryUtil.forClass(Company.class) .addOrder(OrderFactoryUtil.asc("companyId")); List<Company> listCompany = (List<Company>) CompanyLocalServiceUtil.dynamicQuery(queryCompany, 0, 1); companyId = listCompany.get(0).getCompanyId(); //----------- DynamicQuery queryAccount = DynamicQueryFactoryUtil.forClass(Account.class) .addOrder(OrderFactoryUtil.asc("accountId")); List<Account> listAccount = (List<Account>) AccountLocalServiceUtil.dynamicQuery(queryAccount, 0, 1); accountId = listAccount.get(0).getAccountId(); //----------- DynamicQuery queryUser = DynamicQueryFactoryUtil.forClass(User.class) .add(PropertyFactoryUtil.forName("defaultUser").eq(false)) .addOrder(OrderFactoryUtil.asc("createDate")); List<User> listUser = (List<User>) UserLocalServiceUtil.dynamicQuery(queryUser, 0, 1); creatorUserId = listUser.get(0).getUserId(); date = new Date(); } catch (SystemException ex) { logger.error(ex.getMessage()); } } public void create(String screenName, String emailAddress, String hashedPassword, String fullName) { try { long contactId = CounterLocalServiceUtil.increment();//or use Contact.class.getName() as param Contact contact = ContactLocalServiceUtil.createContact(contactId); contact.setAccountId(accountId); //contact.setBirthday(DateUtil.getDate("dd MM yyyy", "01 11 1986")); contact.setCachedModel(true); contact.setCompanyId(companyId); contact.setCreateDate(date); contact.setEmailAddress(emailAddress); //contact.setEmployeeNumber(employeeNumber); //contact.setEmployeeStatusId(employeeStatusId); contact.setFirstName(fullName); contact.setMale(true); contact.setNew(true); //contact.setUserId(creatorUserId); User creatorUser = UserLocalServiceUtil.getUserById(creatorUserId); contact.setUserName(creatorUser.getFullName()); contact.setUserUuid(creatorUser.getUuid()); ContactLocalServiceUtil.addContact(contact); //---------------------- long userId = CounterLocalServiceUtil.increment();//or use User.class.getName() as param //---------------------- User user = UserLocalServiceUtil.createUser(userId); user.setAgreedToTermsOfUse(true); user.setCachedModel(true); user.setCompanyId(companyId); user.setContactId(contactId); user.setCreateDate(date); user.setDefaultUser(false); user.setDigest(null); user.setEmailAddress(emailAddress); user.setEmailAddressVerified(true); user.setFirstName(fullName); user.setGreeting("Hi " + user.getFirstName()); user.setLanguageId("en_US"); user.setModifiedDate(date); user.setNew(true); user.setPassword(hashedPassword); user.setPasswordEncrypted(true); user.setPasswordReset(false); //user.setPasswordUnencrypted(); user.setScreenName(screenName); user.setStatus(WorkflowConstants.STATUS_APPROVED); user.setTimeZoneId("UTC+7"); user.setUserUuid(creatorUser.getUuid()); user.setUuid(PortalUUIDUtil.generate()); UserLocalServiceUtil.addUser(user); //---------------------- try { // to avoid "PermissionChecker not Initialized" PermissionChecker checker = PermissionCheckerFactoryUtil.create(creatorUser); PermissionThreadLocal.setPermissionChecker(checker); } catch (Exception e) { logger.error(e.getMessage(), e); } //---------------------- ClassName clsNameUser = ClassNameLocalServiceUtil.getClassName(Constants.USER_CLASS); long classNameId = clsNameUser.getClassNameId(); long groupId = CounterLocalServiceUtil.increment();// or use Group.class.getName() as param Group group = GroupLocalServiceUtil.createGroup(groupId); group.setActive(true); group.setCachedModel(true); group.setClassNameId(classNameId); group.setClassPK(userId); group.setCompanyId(companyId); group.setCreatorUserId(creatorUser.getUserId()); group.setCreatorUserUuid(creatorUser.getUuid()); group.setFriendlyURL(String.valueOf(userId)); group.setName(String.valueOf(userId)); group.setNew(true); group.setSite(false); group.setTreePath("/" + groupId + "/"); group.setType(0); group.setUuid(PortalUUIDUtil.generate()); GroupLocalServiceUtil.addGroup(group); //----------------------------- long layoutSetId1 = CounterLocalServiceUtil.increment();//or use LayoutSet.class.getName() as param LayoutSet layoutSet1 = LayoutSetLocalServiceUtil.createLayoutSet(layoutSetId1); layoutSet1.setCachedModel(true); //layoutSet.setColorSchemeId(colorSchemeId); layoutSet1.setCompanyId(companyId); layoutSet1.setCreateDate(date); //layoutSet.setCss(css); layoutSet1.setGroupId(groupId); //layoutSet.setLogo(logo); //layoutSet.setLogoId(logoId); layoutSet1.setModifiedDate(date); layoutSet1.setNew(true); layoutSet1.setPrivateLayout(true); //layoutSet.setThemeId(themeId); LayoutSetLocalServiceUtil.addLayoutSet(layoutSet1); //----------------------------- long layoutSetId2 = CounterLocalServiceUtil.increment();// or use LayoutSet.class.getName() as param LayoutSet layoutSet2 = LayoutSetLocalServiceUtil.getLayoutSet(layoutSetId1); layoutSet2.setLayoutSetId(layoutSetId2); layoutSet2.setPrivateLayout(false); LayoutSetLocalServiceUtil.addLayoutSet(layoutSet2); //----------------------------- long assetEntryId = CounterLocalServiceUtil.increment();//or use AssetEntry.class.getName() as param AssetEntry assetEntry = AssetEntryLocalServiceUtil.createAssetEntry(assetEntryId); assetEntry.setCompanyId(companyId); assetEntry.setClassPK(userId); assetEntry.setGroupId(groupId); assetEntry.setClassNameId(classNameId); //ae.setTitle(title); assetEntry.setUserId(userId); AssetEntryLocalServiceUtil.addAssetEntry(assetEntry); //-------------------------------------------------- //long orgAdminRoleId = RoleLocalServiceUtil.getRole(companyId, Constants.ORG_ADMIN_ROLE_NAME).getRoleId(); //UserGroupRoleLocalServiceUtil.addUserGroupRoles(userId, groupId, new long[] { orgAdminRoleId }); long orgUserRoleId = RoleLocalServiceUtil.getRole(companyId, Constants.ORG_USER_ROLE_NAME).getRoleId(); RoleLocalServiceUtil.addUserRole(userId, orgUserRoleId); long siteMemberRoleId = RoleLocalServiceUtil.getRole(companyId, Constants.SITE_MEMBER_ROLE_NAME).getRoleId(); RoleLocalServiceUtil.addUserRole(userId, siteMemberRoleId); //----------------------------------------------------------- } catch (SystemException | PortalException ex) { logger.error(ex.getMessage(), ex); } } } then you can create new instance of UserUtil and call method create() inside your loop of legacy user list, something like this: UserUtil userUtil = new UserUtil(); for (LegacyUser user : listOfLegacyUser) { userUtil.create(........); } note that hashedPassword depends on what your hash method is, defined in portal-ext.properties, default value is: passwords.ecnryption.algorithm=PBKDF2WithHmacSHA1/160/128000 but you can use one of values below: passwords.encryption.algorithm=BCRYPT/10 passwords.encryption.algorithm=MD2 passwords.encryption.algorithm=MD5 passwords.encryption.algorithm=NONE passwords.encryption.algorithm=PBKDF2WithHmacSHA1/160/128000 passwords.encryption.algorithm=SHA passwords.encryption.algorithm=SHA-256 passwords.encryption.algorithm=SHA-384 passwords.encryption.algorithm=SSHA passwords.encryption.algorithm=UFC-CRYPT
I don't know how I managed to fix it but some progress and this is how I did it and it seems to work for now: In my app.js --> .config I removed $httpProvider.defaults.withCredentials = true; and replaced it var xhr = new XMLHttpRequest(); xhr.open('GET', 'http://localhost:8102/', true); xhr.withCredentials = true; xhr.send(null); and then worked but then when these headers where called in the controller it crashed again. // add the following headers for authentication $http.defaults.headers.common['X-Mashape-Key'] = NOODLIO_PAY_API_KEY; $http.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'; $http.defaults.headers.common['Accept'] = 'application/json'; So I decided to Add these header in the function and just call them when the button is clicked. just like this $scope.headerscheck = function(){ // add the following headers for authentication $http.defaults.headers.common['X-Mashape-Key'] = NOODLIO_PAY_API_KEY; $http.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded'; $http.defaults.headers.common['Accept'] = 'application/json'; } but now I don't know how to kill the scope function after use without doing a refresh.
Given your original idea how to solve this, I'd suggest that you take a look at node-xmpp-client and node-xmpp-server. It's an excellent set of libraries and you can use them to fully integrate your application on a nodejs level. So you'd be able to control authentication yourself (use existing users/pws in your app?), and be notified when a message in a (group) chat appears. Of course you can use an existing server like prosody or ejabberd, as a backend for chats. In my experience it's not much work to get node-xmpp-client integrated. But building/running an XMPP-server with nodejs (that can actually talk to other servers) is not that trivial - a little more that the examples thrown together yield, unfortunately. Also, XMPP being text-based, actually even worse, xml-based... it's not really the definition of efficient. Let alone the complexity of all the modules supporting node-xmpp :) So If you are worried about performance and don't need XMPP per-se and really only want the features above, XMPP is a bad choice. It's far to wasteful for your original purposes. So something like zmq should enable you to implement group and personal chats. redis could be used to save chat histories, presence information and message reciepts. To my knowledge there is no library for node that would just give you what you want for free, and IMHO the way using XMPP is even harder than implementing your features with tools like zmq and a datastore as backing on your own.
I was able to add dry ice through the following code $path_to_wsdl = "wsdl/RateService_v20.wsdl"; ini_set("soap.wsdl_cache_enabled", "0"); $client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information $request['WebAuthenticationDetail'] = array( 'ParentCredential' => array( 'Key' => getProperty('parentkey'), 'Password' => getProperty('parentpassword') ), 'UserCredential' => array( 'Key' => getProperty('key'), 'Password' => getProperty('password') ) ); $request['ClientDetail'] = array( 'AccountNumber' => getProperty('shipaccount'), 'MeterNumber' => getProperty('meter') ); $request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request using PHP ***'); $request['Version'] = array( 'ServiceId' => 'crs', 'Major' => '20', 'Intermediate' => '0', 'Minor' => '0' ); $request['ReturnTransitAndCommit'] = true; $request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ... $request['RequestedShipment']['ShipTimestamp'] = date('c'); /* * *********Adding Dry Ice * */ $request['RequestedShipment']['SpecialServicesRequested']['SpecialServiceTypes'] = 'DRY_ICE'; $request['RequestedShipment']['SpecialServicesRequested']['DryIceWeight'] = '5'; $request['RequestedShipment']['SpecialServicesRequested']['ShipmentDryIceDetail']['PackageCount'] = '1'; $request['RequestedShipment']['ServiceType'] = 'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ... $request['RequestedShipment']['PackagingType'] = 'YOUR_PACKAGING'; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ... $request['RequestedShipment']['TotalInsuredValue'] = array( 'Ammount' => 100, 'Currency' => 'USD' ); $request['RequestedShipment']['Shipper'] = addShipper(); $request['RequestedShipment']['Recipient'] = addRecipient(); $request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment(); $request['RequestedShipment']['PackageCount'] = '1'; $request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1(); try { if (setEndpoint('changeEndpoint')) { $newLocation = $client->__setLocation(setEndpoint('endpoint')); } $response = $client->getRates($request); if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') { $rateReply = $response->RateReplyDetails; echo '<table border="1">'; echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr><tr>'; $serviceType = '<td>' . $rateReply->ServiceType . '</td>'; if ($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails)) { $amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ",") . '</td>'; } elseif ($rateReply->RatedShipmentDetails && !is_array($rateReply->RatedShipmentDetails)) { $amount = '<td>$' . number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount, 2, ".", ",") . '</td>'; } if (array_key_exists('DeliveryTimestamp', $rateReply)) { $deliveryDate = '<td>' . $rateReply->DeliveryTimestamp . '</td>'; } else if (array_key_exists('TransitTime', $rateReply)) { $deliveryDate = '<td>' . $rateReply->TransitTime . '</td>'; } else { $deliveryDate = '<td> </td>'; } echo $serviceType . $amount . $deliveryDate; echo '</tr>'; echo '</table>'; printSuccess($client, $response); } else { printError($client, $response); } writeToLog($client); // Write to log file } catch (SoapFault $exception) { printFault($exception, $client); }
This is the way using platform independent groovy script. If anyone has questions please ask in the comments. def file = new File("java/jcifs-1.3.18.jar") this.class.classLoader.rootLoader.addURL(file.toURI().toURL()) def auth_server = Class.forName("jcifs.smb.NtlmPasswordAuthentication").newInstance("domain", "username", "password") def auth_local = Class.forName("jcifs.smb.NtlmPasswordAuthentication").newInstance(null, "local_username", "local_password") def source_url = args[0] def dest_url = args[1] def auth = auth_server //prepare source file if(!source_url.startsWith("\\\\")) { source_url = "\\\\localhost\\"+ source_url.substring(0, 1) + "\$" + source_url.substring(1, source_url.length()); auth = auth_local } source_url = "smb:"+source_url.replace("\\","/"); println("Copying from Source -> " + source_url); println("Connecting to Source.."); def source = Class.forName("jcifs.smb.SmbFile").newInstance(source_url,auth) println(source.canRead()); // Reset the authentication to default auth = auth_server //prepare destination file if(!dest_url.startsWith("\\\\")) { dest_url = "\\\\localhost\\"+ dest_url.substring(0, 1) + "\$" +dest_url.substring(2, dest_url.length()); auth = auth_local } def dest = null dest_url = "smb:"+dest_url.replace("\\","/"); println("Copying To Destination-> " + dest_url); println("Connecting to Destination.."); dest = Class.forName("jcifs.smb.SmbFile").newInstance(dest_url,auth) println(dest.canWrite()); if (dest.exists()){ println("Destination folder already exists"); } source.copyTo(dest);
There are several reasons why your code is not working, but they are lied mainly to spring-data-solr missing features. First of all spring-data-solr version 2.0.4 does not have support for Solr 5 (cloud) features. So this is the reason why you are getting the NullPointerException in the method org.springframework.data.solr.server.support.SolrClientUtils#cloneLBHttpSolrClient I've tried to see whether it the scenario exposed by you works with the latest SNAPSHOT (2.1.0-SNAPSHOT) of spring-data-solr and after a few modifications on the SolrContext spring configuration class : @Configuration @EnableSolrRepositories(basePackages = {"com.acme.solr"}) // notice that the multicoresupport is left false // see org.springframework.data.solr.repository.config.SolrRepositoryConfigExtension#postProcess(org.springframework.beans.factory.support.BeanDefinitionBuilder, org.springframework.data.repository.config.AnnotationRepositoryConfigurationSource) for details public class SolrContext { @Bean public Credentials credentials(@Value("${solr.username}") String username, @Value("${solr.password}") String password) { return new UsernamePasswordCredentials(username, password); } @Bean public BasicCredentialsProvider credentialsProvider(Credentials credentials) { BasicCredentialsProvider provider = new BasicCredentialsProvider(); provider.setCredentials(AuthScope.ANY, credentials); return provider; } @Bean public SolrClientFactory solrClientFactory(SolrClient solrClient, Credentials credentials) { return new HttpSolrClientFactory(solrClient, "", credentials, "BASIC"); } // create a solrtemplate bean, so that it is used in // org.springframework.data.solr.repository.support.SolrRepositoryFactoryBean#doCreateRepositoryFactory method // for using org.springframework.data.solr.repository.support.SolrRepositoryFactory#SolrRepositoryFactory(org.springframework.data.solr.core.SolrOperations) constructor @Bean public SolrTemplate solrTemplate(SolrClientFactory solrClientFactory){ return new SolrTemplate(solrClientFactory); } @Bean public CloudSolrClient solrClient(@Value("${zkHost}") String zkHost) { CloudSolrClient solrClient = new CloudSolrClient.Builder().withZkHost(zkHost).build(); solrClient.setDefaultCollection("gettingstarted"); return solrClient; } } I still received a 401 authentication issue when performing a solr request (when the basic authentication was enabled on solr). In a vanilla solrj application, this is how you'd make an authenticated request: CloudSolrClient solr = new CloudSolrClient.Builder() .withZkHost("localhost:9983") .build(); SolrQuery query = new SolrQuery(); query.setQuery("*:*"); SolrRequest<QueryResponse> req = new QueryRequest(query); req.setBasicAuthCredentials("solr", "SolrRocks"); QueryResponse rsp = req.process(solr, "gettingstarted"); System.out.println("numFound: " + rsp.getResults().getNumFound()); When looking whether the method SolrRequest#setBasicAuthCredentials(String, String) is used in the code of spring-data-solr I didn't notice anywhere this method being used. So, it is very likely, that this feature is not implemented yet not even on the SNAPSHOT build of the spring-data-solr. I've created a feature request on spring-data-solr project to add support for this functionality.
After some searching and bug fixings, I found that the easiest way to achieve it, is to use Regex, so I changed my security.yml: api: pattern: ^/api/v\d+\.\d+/ provider: api_domain anonymous: false guard: authenticators: - app.token_authenticator lexik_jwt: ~ api_login: pattern: ^/api/login stateless: true anonymous: true provider: fos_userbundle form_login: check_path: /api/login_check success_handler: lexik_jwt_authentication.handler.authentication_success failure_handler: lexik_jwt_authentication.handler.authentication_failure require_previous_session: false api_doc: pattern: ^/api/doc stateless: true anonymous: true and in routers.yml added a version at the end of api uri: rest: type : rest resource : "routers/rest_api.yml" prefix : /api/v1.2
I think this happens because you didn't go through the authentication process and just created the user token which didn't trigger Symfony's event that store the user's username, roles and so on. I did a similar thing recently by actually going through login form, filling data and sending it. Just like I was doing a real login attempt and it works well. use Symfony\Component\DependencyInjection\ContainerInterface; abstract class AuthenticatedTestCase extends KernelTestCase { static protected $client; static public function setUpBeforeClass() { parent::setUpBeforeClass(); self::$client = static::$kernel->getContainer()->get('test.client'); } static public function login($login, $password) { $crawler = self::$client->request('GET', '/test_admin/login'); $form = $crawler->filter('input[type="submit"]')->form([ '_username' => $login, '_password' => $password, ]); self::$client->submit($form); // Redirect after successful login self::assertEquals(302, self::$client->getResponse()->getStatusCode()); self::$client->followRedirect(); if (200 === self::$client->getResponse()->getStatusCode()) { // Redirected URL is OK // ... } } }
I use two very important tools for getting visibility into memory problems. The first is compiler warnings. They're not on by default, you have to turn them on with -Wall. Your program doesn't have any warnings, good. Second is to use a memory checker, something that will look for memory problems. This avoids having to do a lot of careful study. I use valgrind which shows memory violations along with the stack. ==90314== Conditional jump or move depends on uninitialised value(s) ==90314== at 0x1013AD570: _platform_memmove$VARIANT$Nehalem (in /usr/lib/system/libsystem_platform.dylib) ==90314== by 0x10112A421: stpcpy (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x10119DBED: __strcpy_chk (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x100000E9A: insert (test.c:31) ==90314== by 0x100000D8A: main (test.c:44) ==90314== ==90314== Use of uninitialised value of size 8 ==90314== at 0x1013AD5C0: _platform_memmove$VARIANT$Nehalem (in /usr/lib/system/libsystem_platform.dylib) ==90314== by 0x10112A421: stpcpy (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x10119DBED: __strcpy_chk (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x100000E9A: insert (test.c:31) ==90314== by 0x100000D8A: main (test.c:44) ==90314== ==90314== Invalid write of size 1 ==90314== at 0x1013AD5C0: _platform_memmove$VARIANT$Nehalem (in /usr/lib/system/libsystem_platform.dylib) ==90314== by 0x10112A421: stpcpy (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x10119DBED: __strcpy_chk (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x100000E9A: insert (test.c:31) ==90314== by 0x100000D8A: main (test.c:44) ==90314== Address 0x0 is not stack'd, malloc'd or (recently) free'd ==90314== ==90314== ==90314== Process terminating with default action of signal 11 (SIGSEGV) ==90314== Access not within mapped region at address 0x0 ==90314== at 0x1013AD5C0: _platform_memmove$VARIANT$Nehalem (in /usr/lib/system/libsystem_platform.dylib) ==90314== by 0x10112A421: stpcpy (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x10119DBED: __strcpy_chk (in /usr/lib/system/libsystem_c.dylib) ==90314== by 0x100000E9A: insert (test.c:31) ==90314== by 0x100000D8A: main (test.c:44) That indicates there's a problem with your call to strcpy. strcpy((*people[nextfreeplace]).name,name); One of the arguments is uninitialized, either name or *people[nextfreeplace]).name. name came from names so that's probably not it. The problem is how people is allocated. people is a pointer to an array of person pointers. But you blow over that with memory for a single person. people = malloc(sizeof(person)); C will let you do that without a warning because malloc returns a void * that will happily morph into whatever pointer type. Instead you should allocate space for one person, and then put a pointer to that into people. static void insert(person *people[], char *name, int age) { static int nextfreeplace = 0; // Allocating memory here person *human = malloc(sizeof(person)); if (human == NULL) { printf("Couldn't allocate memory"); exit(-1); } strcpy(human->name, name); human->age = age; people[nextfreeplace] = human; nextfreeplace++; } That also points out that you should name your types like Person or Person_t to avoid conflicting with built in types and good variable names. That reveals the next problem, and again it's strcpy. It's always strcpy. ==5111== Process terminating with default action of signal 6 (SIGABRT) ==5111== at 0x101269F36: __pthread_sigmask (in /usr/lib/system/libsystem_kernel.dylib) ==5111== by 0x10117876C: __abort (in /usr/lib/system/libsystem_c.dylib) ==5111== by 0x1011786ED: abort (in /usr/lib/system/libsystem_c.dylib) ==5111== by 0x101178855: abort_report_np (in /usr/lib/system/libsystem_c.dylib) ==5111== by 0x10119EA0B: __chk_fail (in /usr/lib/system/libsystem_c.dylib) ==5111== by 0x10119E9DB: __chk_fail_overflow (in /usr/lib/system/libsystem_c.dylib) ==5111== by 0x10119EC28: __strcpy_chk (in /usr/lib/system/libsystem_c.dylib) ==5111== by 0x100000E8F: insert (test.c:31) ==5111== by 0x100000D8A: main (test.c:44) strcpy is vulnerable to overflowing a buffer. Is there enough space allocated in person->name? Let's see... typedef struct{ char name[HOW_MANY]; int age; }person; Nope. HOW_MANY is 7. The mistake there is thinking name is a list of names. Instead it's how long a name can be. If we change that to something reasonable like 32, it works! The person's name is Adam and the age is 22. The person's name is James and the age is 24. The person's name is Matt and the age is 46. The person's name is Affleck and the age is 56. The person's name is Benedict and the age is 21. The person's name is Kayne and the age is 32. The person's name is Evans and the age is 30. Valgrind is happy, but because of the static allocations in your code it's vulnerable to buffer overflow. If one of those names was "Johnathan Jacob Jingleheimerschmit" you'd have a buffer overflow. You have two choices. Statically allocate WAY more memory than you need, or use dynamic memory. In general... Avoid static memory allocations. It's a really bad habit to get into. It invites all sorts of memory overflows. Get used to dynamically allocating and reallocating memory, or use structures that will grow naturally like linked lists and trees. Use a string library. Strings in C are just a nightmare. A general purpose C library like Gnome Lib provides functions for manipulating strings safely and their own improved String type. Always write a new and destroy for your structs. Allocating and deallocating memory for structures can get tricky. It's best to put that all into their own functions rather than relying on your code to get it right willy-nilly. Even if you think it's trivial, it might get not trivial later. typedef struct { char *name; int age; } Person_t; /* So we don't have to check if a thing is null before freeing it */ static void free_if(void *thing) { if( thing != NULL ) { free(thing); } } static Person_t* Person_new() { /* calloc() is used here to 0 the structure so we don't use garbage */ Person_t *person = calloc(1, sizeof(Person_t)); if (person == NULL) { fprintf(stderr, "Couldn't allocate memory for Person_t: %s", strerror(errno)); exit(-1); } return person; } static void Person_destroy(Person_t *person) { free_if(person->name); free(person); } Note that I've moved to using dynamically allocated memory for the name. Which brings us to the next point. Write functions to deal with struct memory. When you need to mess with allocating and copying things into your struct, make it a function that handles all that for you. static void Person_set_name(Person_t *person, char *name) { free_if(person->name); person->name = malloc( (strlen(name) + 1) * sizeof(char) ); strcpy( person->name, name ); } Treat structs like objects, write methods for them. If you're familiar with object-oriented programming in other languages you can see where this is all going. Treat a struct like an object. Write "methods" for it. Do all the work in those methods, not in the code using the struct. This encapsulates all the work of managing the struct into pieces you can easily build, manage, and test.
Additionally to the answer above, change the connection string in your web.config by changing the name of the data source to your Server Name (the name you use to get into SQL Server) and change the initial catalog to the name of your local database. Provide additional username and password fields if you're using SQL Server authentication. If you're using Windows Authentication specify it. Example string for SQL Server Authentication: <add name="YourEntities" connectionString="*your metadata link*;provider=System.Data.SqlClient;provider connection string="Data Source=**your server name**;Initial Catalog=**your database name**;User ID=**your username**;Password=**your password**; MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" /> Just change the values of the attributes data source, initial catalog, username and password. For windows authentication: Add the following attribute: Integrated Security=True; and remove attributes username and password.
Another android enthusiast here: I'm learning too, and I think you could change some things: First, we (the community) need to know where you have the error using the debugging method (The icon is a green bug with a play icon), so put some breakpoints and click on the button mentioned. Second, as firebase says: By default, read and write access to your database is restricted so only authenticated users can read or write data. To get started without setting up Authentication, you can configure your rules for public access. This does make your database open to anyone, even people not using your app, so be sure to restrict your database again when you set up authentication. So, I recommend you authenticate users with their emails, so read this. You will realize that you have to comment this final Firebase ref = new Firebase("https://texter-20d04.firebaseio.com/"); Because the user doesn't have permissions to write on the database without being authenticated first. And change the method ref.createUser(... Because you need the method signInWithEmailAndPassword to add users with their email. Try to do these things and tell me. I hope it helps and If I'm wrong, please, correct me.
I recently had a need to do the exact same thing. My solution may not be the most sophisticated, but simple isn't always bad either. I have two Authentication Filters... The first filter is applied to all controllers that could potentially be hit with query string parameters prior to authorization. It checks if the principal is authenticated. If false it caches the complete url string in a cookie. If true it looks for any cookies present and clears them, just for cleanup. public class AuthCheckActionFilter : ActionFilterAttribute, IAuthenticationFilter { public void OnAuthentication(AuthenticationContext filterContext) { if (!filterContext.Principal.Identity.IsAuthenticated) { HttpCookie cookie = new HttpCookie("OnAuthenticateAction"); cookie.Value = filterContext.HttpContext.Request.Url.OriginalString; filterContext.HttpContext.Response.Cookies.Add(cookie); } else { if (filterContext.HttpContext.Request.Cookies.AllKeys.Contains("OnAuthenticateAction")) { HttpCookie cookie = filterContext.HttpContext.Request.Cookies["OnAuthenticateAction"]; cookie.Expires = DateTime.Now.AddDays(-1); filterContext.HttpContext.Response.Cookies.Add(cookie); } } } public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) { } } The second filter is applied only to the default landing page, or in other words where the identity server is redirecting after login. This second filter looks for a cookie and if it exists it calls response.Redirect on cookie value. public class AutoRedirectFilter : ActionFilterAttribute, IAuthenticationFilter { public void OnAuthentication(AuthenticationContext filterContext) { if(filterContext.Principal.Identity.IsAuthenticated) { if(filterContext.HttpContext.Request.Cookies.AllKeys.Contains("OnAuthenticateAction")) { HttpCookie cookie = filterContext.HttpContext.Request.Cookies["OnAuthenticateAction"]; filterContext.HttpContext.Response.Redirect(cookie.Value); } } } public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext) { } }
You can create a custom JAAS login module to use when consuming the username token. You can use a JAAS config that first calls the built-in token consumer, then your custom consumer. Doing it this way means that you can use the built-in consumer to parse the token and do timestamp and nonce processing and you only have to do the username/password validation in your own login module. The instructions can be found here: http://www14.software.ibm.com/webapp/wsbroker/redirect?version=phil&product=was-nd-dist&topic=twbs_replace_authmethod_usernametoken (Please forgive the formatting. I'm doing the best I can with what I have available here.) Replacing the authentication method of the UsernameToken consumer using a stacked JAAS login module By default, the Web services security UsernameToken consumer, UNTConsumeLoginModule, always validates the username and password that are contained within the token against the WebSphere registry. You can use the SPIs that GenericSecurityTokenFactory provides to bypass this authentication method. About this task If you want to replace the authentication method that UNTConsumeLoginModule uses, you must provide your own custom JAAS login module to do the authentication. The custom login module is stacked under UNTConsumeLoginModule in a custom JAAS configuration. The UNTConsumeLoginModule consumes and validates the token XML. The validation of the values provided for username and password is deferred to the custom stacked login module. Because the use of UNTConsumeLoginModule carries with it the assumption that the username and password will be authenticated, more requirements are put on a stacked login module that intends to perform this function than are put on login modules that are only intended to provide dynamic token functionality. To indicate to UNTConsumeLoginModule that it should not authenticate the username and password, you must set the following property on the configured callback handler: com.ibm.wsspi.wssecurity.token.UsernameToken.authDeferred=true Like most WS-Security login modles, UNTConsumeLoginModule always puts the consumed token in the shared state map to which all login modules in the stack have access. When authDeferred=true is specified, in the commit phase, UNTConsumeLoginModule ensures that the same UsernameToken object that had originally been put on the shared state has been put in another location in the shared state. If this UsernameToken object cannot be found, a LoginException occurs. Therefore, you cannot just set authDeferred=true on the callback handler without having an accompanying login module return the token to the shared state. Procedure Develop a JAAS login module to do the authentication and make it available to your application code. This new login module stacks under the com.ibm.ws.wssecurity.wssapi.token.impl.UNTConsumeLoginModule. This login module must: Use the following method to get the UsernameToken that UNTConsumeLoginModule consumes. UsernameToken unt = UsernameToken)factory.getConsumerTokenFromSharedState(sharedState,UsernameToken.ValueType); In this code example, factory is an instance of com.ibm.websphere.wssecurity.wssapi.token.GenericSecurityTokenFactory. Check the username and password in the manner that you choose. You can call unt.getUsername() and unt.getPassword() to get the username and password. Your login module should throw a LoginException if there is an authentication error. Put the UsernameToken, that was obtained in the previous substep, back on the shared state. Use the following method to put the UsernameToken back on the shared state. factory.putAuthenticatedTokenToSharedState(sharedState, unt); Following is an example login module: package test.tokens; import com.ibm.websphere.wssecurity.wssapi.token.GenericSecurityTokenFactory; import com.ibm.websphere.wssecurity.wssapi.WSSUtilFactory; import java.util.HashMap; import java.util.Map; import javax.security.auth.Subject; import javax.security.auth.callback.CallbackHandler; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; import com.ibm.websphere.wssecurity.wssapi.token.UsernameToken; import java.util.ArrayList; import com.ibm.wsspi.security.registry.RegistryHelper; import com.ibm.websphere.security.UserRegistry; public class MyUntAuthenticator implements LoginModule { private Map _sharedState; private Map _options; private CallbackHandler _handler; public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) { this._handler = callbackHandler; this._sharedState = sharedState; this._options = options; } public boolean login() throws LoginException { //For the sake of readability, this login module does not //protect against all NPE's GenericSecurityTokenFactory factory = null; WSSUtilFactory utilFactory = null; try { factory = GenericSecurityTokenFactory.getInstance(); utilFactory = WSSUtilFactory.getInstance(); } catch (Exception e) { throw new LoginException(e.toString()); } if (factory == null) { throw new LoginException("GenericSecurityTokenFactory.getInstance() returned null"); } UsernameToken unt = (UsernameToken)factory.getConsumerTokenFromSharedState(this._sharedState,UsernameToken.ValueType); String username = unt.getUsername(); char [] password = unt.getPassword(); //authenticate the username and password //to validate a PasswordDigest password (fixpack 8.5.5.8 and later) //String pw = yourCodeToLookUpPasswordForUsername(username); //boolean match = utilFactory.verifyDigestedPassword(unt, pw.toCharArray()); //if (!match) throw new LoginException("Digested passwords do not match"); //Example: try { simpleUserGroupCheck(username, password, "cn=group1,o=ibm,c=us"); } catch (Exception e) { LoginException le = new LoginException(e.getMessage()); le.initCause(e); throw le; } //Put the authenticated token to the shared state factory.putAuthenticatedTokenToSharedState(this._sharedState, unt); return true; } private boolean simpleUserGroupCheck(String username, char [] password, String group) throws Exception { String allowedGroup = null; //get the default user registry UserRegistry user_reg = RegistryHelper.getUserRegistry(null); //authenticate the user against the user registry user_reg.checkPassword(username, new String(password)); //get the list of groups that the user belongs to java.util.List<String> groupList = user_reg.getGroupsForUser(username); //you can either use a hard-coded group allowedGroup = group; //or get the value from your own custom property on the callback handler //WSSUtilFactory util = WSSUtilFactory.getInstance(); //Map map = util.getCallbackHandlerProperties(this._handler); //allowedGroup = (String) map.get("MY_ALLOWED_GROUP_1"); //check if the user belongs to an allowed group if (!groupList.contains(allowedGroup)) { throw new LoginException("user ["+username+"] is not in allowed group ["+allowedGroup+"]"); } return true; } //implement the rest of the methods required by the //LoginModule interface } Create a new JAAS login configuration. In the administrative console, select Security > Global security. Under Authentication, select Java Authentication and Authorization Service. Select System logins. Click New, and then specify Alias = test.consume.unt. Click New, and then specify Module class name = com.ibm.ws.wssecurity.wssapi.token.impl.UNTConsumeLoginModule Click OK. Click New, and then specify Module class name = test.tokens.MyUntAuthenticator Select Use login module proxy. Click OK, and then click SAVE. Configure your UsernameToken token consumer to use the new JAAS configuration. Open your bindings configuration that you want to change. In the administrative console, select WS-Security > Authentication and protection. Under Authentication tokens, select the UsernameToken inbound token that you want to change. Select JAAS login = test.consume.unt. Set the required property on the callback handler that is configured for the UsernameToken consumer. Click Callback handler. Add the com.ibm.wsspi.wssecurity.token.UsernameToken.authDeferred=true custom property. Click OK. Click SAVE. Restart the application server to apply the JAAS configuration changes. Test your service.
You need to Create a UsernamePasswordCountryAuthenticationToken. public class UsernamePasswordCountryAuthenticationToken extends UsernamePasswordAuthenticationToken { private String country; public UsernamePasswordCountryAuthenticationToken(Object principal, Object credentials, String country, Collection<? extends GrantedAuthority> authorities) { super(principal, credentials, country, authorities); } public UsernamePasswordCountryAuthenticationToken(Object principal, Object credentials, String country) { super(principal, credentials, country); } public String getCountry() { return country; } } And override ResourceOwnerPasswordTokenGranter public class CustomResourceOwnerPasswordTokenGranter extends AbstractTokenGranter { private static final String GRANT_TYPE = "password"; private final AuthenticationManager authenticationManager; public CustomResourceOwnerPasswordTokenGranter(AuthenticationManager authenticationManager, AuthorizationServerTokenServices tokenServices, ClientDetailsService clientDetailsService) { super(tokenServices, clientDetailsService, GRANT_TYPE); this.authenticationManager = authenticationManager; } protected OAuth2Authentication getOAuth2Authentication(AuthorizationRequest clientToken) { Map<String, String> parameters = clientToken.getAuthorizationParameters(); String username = parameters.get("username"); String password = parameters.get("password"); String country = parameters.get("country"); Authentication userAuth = new UsernamePasswordCountryAuthenticationToken(username, password, country); try { userAuth = authenticationManager.authenticate(userAuth); } catch (AccountStatusException ase) { //covers expired, locked, disabled cases (mentioned in section 5.2, draft 31) throw new InvalidGrantException(ase.getMessage()); } catch (BadCredentialsException e) { // If the username/password are wrong the spec says we should send 400/bad grant throw new InvalidGrantException(e.getMessage()); } if (userAuth == null || !userAuth.isAuthenticated()) { throw new InvalidGrantException("Could not authenticate user: " + username); } return new OAuth2Authentication(clientToken, userAuth); } } And Finally in your Spring Security OAuth configuration file <bean id="customResourceOwnerPasswordTokenGranter" class="CustomResourceOwnerPasswordTokenGranter"> <constructor-arg index="0" ref="authenticationManager"/> <constructor-arg index="1" ref="tokenServices"/> <constructor-arg index="2" ref="clientDetailsService"/> </bean> <oauth:authorization-server ...> <oauth:custom-grant token-granter-ref="customResourceOwnerPasswordTokenGranter" /> </oauth:authorization-server> Now if you have correctly Configured your AuthenticationManager to have your custom AuthenticationProvider, you will be receiving an instance of UsernamePasswordCountryAuthenticationToken to AuthenticationProvider.authenticate method(Authentication auth) where you can cast auth to UsernamePasswordCountryAuthenticationToken and make use.
You're making it hard on yourself. It'd be easier if you do basic routing in your php. Just send anything to your index.php that's not a directory, and is either not a file or is a php file: RewriteEngine on RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f [OR] RewriteCond %{REQUEST_FILENAME} (?>.*)(?<=\.php) [NC] RewriteRule ^(?!index\.php$). index.php [NS,L] At the top of index.php, do something like this: <?php $url = explode('?', $_SERVER['REQUEST_URI'], 2); $url = substr($url[0], 1); if ($url) { $url = strtolower($url) . '.php'; if (preg_match('@^[^./][^/]*(?:/[^./][^/]*)*$@', $url) && file_exists($url)) { . # does not contain dotfiles, nor `..` directory traversal, so is a php file below web root include $url; } else { # virtual URL doesn't exist, # set 404 response code header and serve a default page include '404.php'; } exit; } # no virtual URL, continue processing index.php Add a rel=canonical to each page's <head> that contains the lowercase URL (with any query string re-added) so you are not penalized for duplicate content,
I was able to get this working using this Startup.ConfigureAuth. public void ConfigureAuth(IAppBuilder app) { app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); app.UseOpenIdConnectAuthentication( new OpenIdConnectAuthenticationOptions { ClientId = clientId, MetadataAddress = metadataAddress, RedirectUri = redirectUri, //PostLogoutRedirectUri = postLogoutRedirectUri }); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); }
I have never implemented this myself, but to point you in the right direction, it may be worth having a read through this: https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#authentication-backends By the sounds of things you may be able to write an authentication backend for your front end user model, that you can run in tandem with Django's authentication system. If you could get this to work, I would imagine that you would then have to make sure that the front end user model, once authenticated, can not access the admin part of the site. For me the million dollar question here is, why do you want to keep the front end and backend users on separate models? They both have the same job, to authenticate the user? I've created several projects in the past where there are front end users and admin users. Out of the box, without any modification you set the user attribute is_staff=False for front end users and is_staff=True for the admin users; that determines whether or not a user can access the admin part of the site, and I've never had any issues with this approach. If the front end user (or backend user) desires additional functionality, the simplest solution would be to extend the user model: https://docs.djangoproject.com/en/1.10/topics/auth/customizing/#extending-the-existing-user-model Alternatively you could user your could create a custom user model and use this for both. If you're willing to provide more details, perhaps I could help further, but unless there's a strong reason for having separate user models, I'd just stick with the one and configure and extend as you need. I hope this helps.
I started a self-hosted dummy service from scratch and narrowed down the problem to my configuration. It needs to be using a webHttpBinding to function as a REST service and I guess, without explicitly specifying so, it was instead using a basicHttpBinding. I removed the standard endpoints and configured the endpoint myself to this: <system.serviceModel> <behaviors> <endpointBehaviors> <behavior name="webHttpBehavior"> <webHttp/> </behavior> </endpointBehaviors> </behaviors> <bindings> <webHttpBinding> <binding name="webHttpBinding" crossDomainScriptAccessEnabled="true" /> </webHttpBinding> </bindings> <services> <service name="LessonPlansAuthentication.MachineDataService"> <endpoint address="" binding="webHttpBinding" bindingConfiguration="webHttpBinding" behaviorConfiguration="webHttpBehavior" contract="LessonPlansAuthentication.IMachineDataService"/> </service> </services> <serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" /> </system.serviceModel> If I tried to visit the URL in the browser before making this change, it would just display a blank white page. After, it actually returns the JSON data and jQuery can successfully do a JSONP AJAX call to the URL. I'm still unclear exactly what using the webHttp binding & endpoint along with crossDomainScriptAccessEnabled=true actually changes to allow the call. Content type of the response maybe? Any comments on that would be appreciated. Now I just have to verify it works in all browsers. If anyone knows why Edge is not supporting the service with CORS enabled, please leave a comment.
in zepplin interpretors add external dependency of org.apache.bahir:spark-streaming-twitter_2.11:2.0.0 from GUI and after that run following using spark-2.0.1 import org.apache.spark._ import org.apache.spark.streaming._ import org.apache.spark.streaming.StreamingContext._ import org.apache.spark.{ SparkConf, SparkContext} import org.apache.spark.storage.StorageLevel import scala.io.Source //import org.apache.spark.Logging import java.io.File import org.apache.log4j.Logger import org.apache.log4j.Level import sys.process.stringSeqToProcess import scala.collection.mutable.HashMap /** Configures the Oauth Credentials for accessing Twitter */ def configureTwitterCredentials(apiKey: String, apiSecret: String, accessToken: String, accessTokenSecret: String) { val configs = new HashMap[String, String] ++= Seq( "apiKey" -> apiKey, "apiSecret" -> apiSecret, "accessToken" -> accessToken, "accessTokenSecret" -> accessTokenSecret) println("Configuring Twitter OAuth") configs.foreach{ case(key, value) => if (value.trim.isEmpty) { throw new Exception("Error setting authentication - value for " + key + " not set") } val fullKey = "twitter4j.oauth." + key.replace("api", "consumer") System.setProperty(fullKey, value.trim) println("\tProperty " + fullKey + " set as [" + value.trim + "]") } println() } // Configure Twitter credentials , following config values will not work,it is for show off val apiKey = "7AVLnhssAqumpgY6JtMa59w6Tr" val apiSecret = "kRLstZgz0BYazK6nqfMkPvtJas7LEqF6IlCp9YB1m3pIvvxrRZl" val accessToken = "79438845v6038203392-CH8jDX7iUSj9xmQRLpHqLzgvlLHLSdQ" val accessTokenSecret = "OXUpYu5YZrlHnjSacnGJMFkgiZgi4KwZsMzTwA0ALui365" configureTwitterCredentials(apiKey, apiSecret, accessToken, accessTokenSecret) import org.apache.spark.{ SparkConf, SparkContext} import org.apache.spark.streaming._ import org.apache.spark.streaming.twitter._ import org.apache.spark.SparkContext._ val ssc = new StreamingContext(sc, Seconds(2)) val tweets = TwitterUtils.createStream(ssc, None) val twt = tweets.window(Seconds(10)) //twt.print val sqlContext= new org.apache.spark.sql.SQLContext(sc) import sqlContext.implicits._ case class Tweet(createdAt:Long, text:String) val tweet = twt.map(status=> Tweet(status.getCreatedAt().getTime()/1000, status.getText()) ) tweet.foreachRDD(rdd=>rdd.toDF.registerTempTable("tweets")) ssc.start() //ssc.stop() After that run some queries in the table in another zappelin cell %sql select createdAt, text from tweets limit 50
In my tests intercept-url's are involved: @ContextConfiguration({ "classpath:spring/spring-app.xml", ... }) @WebAppConfiguration @RunWith(SpringJUnit4ClassRunner.class) @Transactional public class ControllerTest { private static final CharacterEncodingFilter CHARACTER_ENCODING_FILTER = new CharacterEncodingFilter(); static { CHARACTER_ENCODING_FILTER.setEncoding("UTF-8"); CHARACTER_ENCODING_FILTER.setForceEncoding(true); } protected MockMvc mockMvc; @Autowired private WebApplicationContext webApplicationContext; @PostConstruct private void postConstruct() { mockMvc = MockMvcBuilders .webAppContextSetup(webApplicationContext) .addFilter(CHARACTER_ENCODING_FILTER) .apply(springSecurity()) .build(); } @Test public void testUsers() throws Exception { mockMvc.perform(get("/users") .with(authentication(new UsernamePasswordAuthenticationToken("user", "password"))) .andDo(print()) .andExpect(status().isOk()) .andExpect(view().name("users")) .andExpect(forwardedUrl("/WEB-INF/jsp/users.jsp")); } ...
The easiest solution is to set up someting like gitlab, which provides a web interface, various sorts of access control, and all sorts of other bells and whistles. If you really want to roll your own: Start with directions in the Git book for setting up your server to permit access to a shared user over ssh. Those instructions will get you a shared git account to which everyone has access, and would let anyone push to/pull from any repository. We can implement a simple authorization layer that will restrict users to repositories in particular directories. Start with a small wrapper script: #!/bin/sh repo_prefix=$1 eval set -- $SSH_ORIGINAL_COMMAND case "$1" in (git-receive-pack|git-upload-pack|git-upload-archive) # prevent attempts at using dir/../path to escape # repository directory case "$2" in (*..*) echo "Invalid repository name." >&2 exit 1 ;; esac repo_path="$repo_prefix/$2" eval exec $1 $repo_path ;; (*) echo "Unsupported command" >&2 exit 1 ;; esac This will prepend a prefix path, provided as a command line argument, to all repository paths. Now, we need to arrange for this wrapper to intercept git operations. To use this, you will need to modify the public keys you add to the git user's authorized_keys file. If you followed the instructions in the Git book, the authorized_keys file will have one or more public keys in it, like this: ssh-rsa AAAA...== some comment For each public key, you will need to add a configuration option that will cause the wrapper script to be called in place of the original command. From the sshd man page: Each line of the file contains one key (empty lines and lines starting with a ‘#’ are ignored as comments). Protocol 1 public keys consist of the following space-separated fields: options, bits, exponent, modulus, comment. Protocol 2 public key consist of: options, keytype, base64-encoded key, comment. The options field is optional... And slightly further down: The following option specifications are supported (note that option keywords are case-insensitive): [...] command="command" Specifies that the command is executed whenever this key is used for authentication. The command supplied by the user (if any) is ignored...The command originally supplied by the client is available in the SSH_ORIGINAL_COMMAND environment variable. With that in mind, we modify our authorized_keys file to look something like this: command="/usr/bin/git-wrapper.sh username" ssh-rsa AAAA...=== This means that when someone connects with the corresponding private key, sshd will run git-wrapper.sh username, causing our git-wrapper.sh script to prepend repository paths with the string username, ensuring that git will only see repositories in the given directory. More specifically, when you run: git push origin master And assuming that origin points to project.git on the git server, thengit will attempt to run on the remote server the command: git-receive-pack project.git Our wrapper script will intercept that, and transform it into: git-receive-pack $1/project.git So for example, if our git git user home directory has no repositories: git$ ls And our authorized_keys file looks like this: git$ cat .ssh/authorized_keys command="/usr/bin/git-wrapper.sh alice" ssh-rsa ... [email protected] command="/usr/bin/git-wrapper.sh bob" ssh-rsa ... [email protected] Then if alice does this: alice$ git remote add origin git@mygitserver:project.git git push origin master She will see: fatal: 'alice/project.git' does not appear to be a git repository fatal: Could not read from remote repository. If we create the target repository: git$ mkdir alice git$ git init --bare alice/project.git Then she can push: alice$ git push origin master [...] To git@mygitserver:project.git * [new branch] master -> master But if bob were try to clone that repository: bob$ git clone git@mygitserver:project.git It would fail: fatal: 'bob/project.git' does not appear to be a git repository fatal: Could not read from remote repository. Even if he tried something sneaky: bob$ git clone git@mygitserver:../alice/project.git Invalid repository name fatal: Could not read from remote repository. And that, in a somewhat verbose nutshell, is how you can access authorization for your git repository server. Note that this was all done for demonstration purposes only; you would want a substantially more robust script in a production environment.
The prompt window which appears on windows authentication is highly likely because of 401 Access Denied While I am not sure about some mandatory questions to be able to tell the exact same reason like A- what authentication provider is being used here? B- Do you need Kerberos or not? are you using a custom identity or not? I believe using Kerberos authentication as a provider with Windows Authentication is the best option and to do it please ensure you did all the below steps carefully in a right way 1- Create a custom account on Active Directory, delegate this account from the delegate tab on AD Properties to ensure it can user Kerberos 2- use this custom identity as an app pool custom identity user, go to application pools, choose your app pool, right click, custom identity and set the user you just created. 3- go to application authentication tab, disable all authentication providers including impersonation (not only anonymous) except windows authentication 4- right click on Windows Authentication, choose providers, and choose "Negotiate/Kerberos" as primary provider below it "Negotiate" Authentication Providers 5- Set Service principle name, open CMD, set SPN to the service account such that if service account is "lab\testuser" and server domain is "server1A" and its FQDN (Fully Qualified Domain Name) is "server1A.test.com" type the below command: setspn -s server1A lab\testuser setspn -s server1.test.com testuser it is really important to clear Kerberos cache ticket as well because manytimes you will make changes and you won't see it took any effect except after clearing the cache, so you need to use [KLIST tool][3] to clear it by typing the command klist purge then you need to clear the DNS cache, restart IIS by typing the commands below on CMD "Run as admin" ipconfig/flushdns iisreset Good Luck, please let me know if you have any further questions, if you need clarification for anything
Configuration of security with Java classes start by providing your @Configuration classes subclassing org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter for the "web" part (request) and org.springframework.security.config.annotation.method.configuration.GlobalMethodSecurityConfiguration for the "global" part (service layer). In the sub-class of WebSecurityConfigurerAdapter, you have to override some "configure(...)" methods: (just examples...) public void configure(final WebSecurity web) throws Exception { // @formatter:off web.ignoring() .antMatchers("/*.html","/*.ico","/css/**","/html/**","/i18n/**","/img/**","/js/**","/lib/**"); // @formatter:on } protected void configure(final HttpSecurity http) throws Exception { http.headers() .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsMode.SAMEORIGIN)) .and() .csrf().disable() .addFilterAfter(jeePreAuthenticatedFilter(), AbstractPreAuthenticatedProcessingFilter.class) .addFilterBefore(new BasicAuthenticationFilter(authenticationManagerBean()), UsernamePasswordAuthenticationFilter.class) .addFilterBefore(switchUserProcessingFilter(), SwitchUserFilter.class) .authorizeRequests() .antMatchers("/*.html","/*.ico","/css/**","/html/**","/i18n/**","/img/**","/js/**","/lib/**").permitAll() .anyRequest().authenticated() .and() .sessionManagement() .sessionFixation().none().maximumSessions(maxSessionsPerUser) .sessionRegistry(sessionRegistry) ; } protected void configure(final AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(basicDAOAuthenticationProvider()); auth.authenticationProvider(preauthAuthProvider()); } In that @Configuration class, you should/could also have beans for the MethodSecurityMetadataSource, AccessDecisionManager, AccessDecisionVoter, ... your authentication providers, ... Same principle your @Configuration, sub-class of GlobalMethodSecurityConfiguration: protected AccessDecisionManager accessDecisionManager() { ... } protected void configure(final AuthenticationManagerBuilder auth) throws Exception { ... } protected MethodSecurityExpressionHandler createExpressionHandler() { ...; } @Bean public MethodSecurityExpressionHandler methodSecurityExpressionHandler() { ... }
More actual example you can find in GrapeOAuth2 gem. All you need is to create 3 models that will represent your clients, tokens and resource owners, mount default endpoints and protect your API. So create 3 models for used ORM and mount default OAuth2 tokens endpoint to your API: module Twitter class API < Grape::API version 'v1', using: :path format :json prefix :api helpers GrapeOAuth2::Helpers::AccessTokenHelpers # What to do if somebody will request an API with access_token # Authenticate token and raise an error in case of authentication error use Rack::OAuth2::Server::Resource::Bearer, 'OAuth API' do |request| AccessToken.authenticate(request.access_token) || request.invalid_token! end # Mount default Grape OAuth2 Token endpoint mount GrapeOAuth2::Endpoints::Token # ... end end Available routes: POST /oauth/token POST /oauth/revoke And then protect required endpoints with access_token_required! method: module Twitter module Resources class Status < Grape::API before do access_token_required! end resources :status do get do { current_user: current_resource_owner.username } end end end end end Take a look at the README for more detailed examples (simple one and customizable).
The way to work with Accu-Chek Aviva Connect is to pair it the first time by going to Settings → Wireless → Pairing → Pair Device. Then you get a screen with number code and a message: "Enter code on device". On iPhone you discover Accu-Chek device and write a value to Read Record Access Control Point characteristic. For example request a Number of records: - (void)peripheral:(CBPeripheral *)aPeripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error { if ([service.UUID isEqual:[CBUUID UUIDWithString:@"1808"]]) { for (CBCharacteristic *aChar in service.characteristics) { // Read Record Access Control Point if ([aChar.UUID isEqual:[CBUUID UUIDWithString:@"2A52"]]) { [aPeripheral readValueForCharacteristic:aChar]; [aPeripheral setNotifyValue:YES forCharacteristic:aChar]; self.readAccessControlPointCharacteristic = aChar; NSMutableData *mutableData = [NSMutableData data]; uint8_t opCode = 0x04; // Report number of stored records uint8_t operator = 0x01; // All records [mutableData appendData:[NSData dataWithBytes:(void*)&opCode length:sizeof(opCode)]]; [mutableData appendData:[NSData dataWithBytes:(void*)&operator length:sizeof(operator)]]; [aPeripheral writeValue:mutableData forCharacteristic:self.readAccessControlPointCharacteristic type:CBCharacteristicWriteWithResponse]; } } } This leads to an UIAlertView on iPhone where it asks you to enter a code which is displayed on Accu-Chek screen. When you do it, your iPhone will be successfully paired with Accu-Chek Aviva Connect. Now. When you want to read all records from Bluetooth device - you will have to go to My Data → Data Transfer → Wireless → and if your Accu-Chek device has a lot of pairings, select your iPhone name. Note: iPhone must be scaning for BT devices and connect to a discovered device automatically. Bluetooth connection will be established and you can send any requests from your iPhone to Bluetooth device without "Error: Authentication is insufficient"!
1) OAuth2 is authentication and authorization protocol which is broadly used by largest and even smaller companies. Think of Facebook API. If a user is not authentication nor authorized to make that call, you can drop the inbound request. That's one method. 2) Second method would be to add your own user agent to your HTTP header and other custom HTTP headers. If your server checks on these headers, then you can drop the inbound requests. You don't have to store the SSL certificate on the client as the client would initiate a secure connection with the server that has the SSL certificate. Anyhow, using a certificate client side could be okay to encrypt data but I don't believe Android Java has support for that. Correct me if I'm wrong. If you do happen to encrypt data with that key, you could encrypt a certain String or bytes that you can parse into one of your custom HTTP headers but if someone finds out what the encrypted String would be, he/she can still fake a connection. However I do not recommend to store your SSL certificate on the client's device. Regardless of what you might do, there's always a way to fake a HTTP/HTTPS connection like it's coming from an Android device but you can narrow down the incoming HTTPS requests using these two methods and make it much harder. An example would be Pokémon GO. There are plenty of unofficial APIs on GitHub who can fake a connection like it's coming from the official app.
You should copy paste the code from the inatallation documentation into config.yml (like me). Remove the lines with sonata_customer and sonata_order. profile: # Profile show page is a dashboard as in SonataAdminBundle dashboard: blocks: - { position: left, type: sonata.block.service.text, settings: { content: "<h2>Welcome!</h2> This is a sample user profile dashboard, feel free to override it in the configuration! Want to make this text dynamic? For instance display the user's name? Create a dedicated block and edit the configuration!"} } - { position: left, type: sonata.order.block.recent_orders, settings: { title: Recent Orders, number: 5, mode: public }} - { position: right, type: sonata.timeline.block.timeline, settings: { max_per_page: 15 }} - { position: right, type: sonata.news.block.recent_posts, settings: { title: Recent Posts, number: 5, mode: public }} - { position: right, type: sonata.news.block.recent_comments, settings: { title: Recent Comments, number: 5, mode: public }} # Customize user portal menu by setting links menu: - { route: 'sonata_user_profile_show', label: 'sonata_profile_title', domain: 'SonataUserBundle'} - { route: 'sonata_user_profile_edit', label: 'link_edit_profile', domain: 'SonataUserBundle'} - { route: 'sonata_customer_addresses', label: 'link_list_addresses', domain: 'SonataCustomerBundle'} - { route: 'sonata_user_profile_edit_authentication', label: 'link_edit_authentication', domain: 'SonataUserBundle'} - { route: 'sonata_order_index', label: 'order_list', domain: 'SonataOrderBundle'}
My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.) [Table("UserOtherEntity")] public partial class UserOtherEntity { public Guid UserOtherEntityId { get; set; } [Required] [StringLength(128)] public string UserId { get; set; } [Required] public Guid OtherEntityId { get; set; } public virtual OtherEntity OtherEntity { get; set; } } public partial class UserOtherEntity : DataManager { public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId) { return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity); } } public partial class ApplicationUser : IdentityUser { public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager) { // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie); // Add custom user claims here return userIdentity; } [NotMapped] public IEnumerable<OtherEntity> OtherEntities { get { return UserOtherEntities.GetOtherEntitiesByUserId(this.Id); } } }
import SoftLayer import json from pprint import pprint as pp productOrder = { "quantity": 1, "location": 1441195, "packageId": 251, "sshKeyIds": 248873, "hardware": [ { "hostname": "db2oncloud-tshirt-plan-customer-#-letter-datacenter", "primaryNetworkComponent": { "networkVlan": { "id": 1351859 } }, "domain": "bluemix.net", "primaryBackendNetworkComponent": { "networkVlan": { "id": 1351879 } } } ], "prices": [ { "id": 50691, "description": "Dual Intel Xeon E5-2620 v3 (12 Cores, 2.40 GHz)" }, { "id": 49437, "description": "128 GB RAM" }, { "id": 49081, "description": "Red Hat Enterprise Linux 7.x (64 bit) (per-processor licensing)" }, { "id": 35686, "description": "10 Gbps Redundant Public & Private Network Uplinks" }, { "id": 34241, "description": "Host Ping and TCP Service Monitoring" }, { "id": 34996, "description": "Automated Reboot from Monitoring" }, { "id": 50359, "description": "500 GB Bandwidth" }, { "id": 33483, "description": "Unlimited SSL VPN Users & 1 PPTP VPN User per account" }, { "id": 141833, # Disk0 "description": "1.2 TB SSD (10 DWPD)" }, { "id": 141833, # Disk1 "description": "1.2 TB SSD (10 DWPD)" }, { "id": 141833, # Disk2 "description": "1.2 TB SSD (10 DWPD)" }, { "id": 141833, # Disk3 "description": "1.2 TB SSD (10 DWPD)" }, { "id": 141833, # Disk4 "description": "1.2 TB SSD (10 DWPD)" }, { "id": 141833, # Disk5 "description": "1.2 TB SSD (10 DWPD)" }, { "id": 50143, # Disk6 "description": "800 GB SSD (10 DWPD)" }, { "id": 50143, # Disk7 "description": "800 GB SSD (10 DWPD)" }, { "id": 141965, "description": "DISK_CONTROLLER_RAID_10" }, { "id": 32500, "description": "Email and Ticket" }, { "id": 35310, "description": "Nessus Vulnerability Assessment & Reporting" }, { "id": 34807, "description": "1 IP Address" }, { "id": 25014, "description": "Reboot / KVM over IP" } ], "sshKeys": [ { "sshKeyIds":248873 } ], "storageGroups": [ { "arraySize": 100, "arrayTypeId": 5, # Raid 10 "hardDrives": [ 0, 1, 2, 3, 4, 5 ], "partitionTemplateId": 1, # Linux Basic "partitions": [ { "isGrow": True, "name": "/ssd_disk1", "size": 3501 } ] }, { "arraySize": 800, "arrayTypeId": 2, # Raid 1 "hardDrives": [ 6, 7 ], "partitions": [ { "isGrow": True, "name": "/ssd_disk2", "side": 800 } ] } ] } client = SoftLayer.Client(username=&apikey) order = client['Product_Order'].verifyOrder(productOrder) pp(order)
You have to use a web-security expression, see Spring Security Reference: 30.2 The authorize Tag This tag is used to determine whether its contents should be evaluated or not. In Spring Security 3.0, it can be used in two ways [21]. The first approach uses a web-security expression, specified in the access attribute of the tag. The expression evaluation will be delegated to the SecurityExpressionHandler<FilterInvocation> defined in the application context (you should have web expressions enabled in your <http> namespace configuration to make sure this service is available). So, for example, you might have <sec:authorize access="hasRole('supervisor')"> This content will only be visible to users who have the "supervisor" authority in their list of <tt>GrantedAuthority</tt>s. </sec:authorize> ROLE_USER is no built-in web-security expression (see Spring Security Reference), use instead hasRole('USER'), see SecurityExpressionRoot#hasRole: Determines if the SecurityExpressionOperations.getAuthentication() has a particular authority within Authentication.getAuthorities(). This is similar to SecurityExpressionOperations.hasAuthority(String) except that this method implies that the String passed in is a role. For example, if "USER" is passed in the implementation may convert it to use "ROLE_USER" instead. The way in which the role is converted may depend on the implementation settings.
using WebSecurity You are currently using a preauthorize rule on a controller action. The power of method security initially is, to use it on methods not directly related to routes, because these can be setup HttpSecurity request matchers, often by using the WebSecurityConfigurerAdapter. This - however - is not really helping you, because spring has a route to permission approach, rather than a permission to route approach. This means, if you have one global role, giving access to everything no matter of specific configuration, than you must configure it to all security definitions, if you are avoiding changing the default configuration. The only way I see to solve your need, is to hook into springs security filtering process and define an exceptional rule for admin scope. You can read here about how to implement a custom filter, which you place after your oauth2 authentication is extracted to look for admin scope (or different global rules) tree roles this is some logical solution I use for my projects, which gives a role some "parent" role, which implies roles down the current node in the tree. so the root is implicitly granting all roles / scopes you configure. For simplicity, I apply these tree logic on-write, like giving [ROOT_ROLE] results in adding all roles under (tree traverse) or revoking all roles found by depth-first search from node up towards root. The motivation is here, that access control policies are often reflecting a hierarchical structure of users, and gives more freedom to design these personal hierarchy properly using a tree. This pattern solves your problem indirectly, in a scalable way
Here is the list of ssl property ( add these to application.properties file) : server.ssl.ciphers= # Supported SSL ciphers. server.ssl.client-auth= # Whether client authentication is wanted ("want") or needed ("need"). Requires a trust store. server.ssl.enabled= # Enable SSL support. server.ssl.enabled-protocols= # Enabled SSL protocols. server.ssl.key-alias= # Alias that identifies the key in the key store. server.ssl.key-password= # Password used to access the key in the key store. server.ssl.key-store= # Path to the key store that holds the SSL certificate (typically a jks file). server.ssl.key-store-password= # Password used to access the key store. server.ssl.key-store-provider= # Provider for the key store. server.ssl.key-store-type= # Type of the key store. server.ssl.protocol=TLS # SSL protocol to use. server.ssl.trust-store= # Trust store that holds SSL certificates. server.ssl.trust-store-password= # Password used to access the trust store. server.ssl.trust-store-provider= # Provider for the trust store. server.ssl.trust-store-type= # Type of the trust store. Hope it help, reference : http://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
Here is an example showing how I make a Post call. I guess if you change to HttpMethod.GET it should work too. My example sends userName and password to a REST API and if everything is ok, it returns the Cookie from the response. You can change it to adapt to your needs. private static Cookie ConfigurarAcessoGED() { Uri uri = new Uri("URL_FROM_API"); var req = new HttpRequestMessage(HttpMethod.Post, uri); var reqBody = @"{ 'UserName':'USERNAME', 'Password':'PASSWORD' }"; req.Content = new StringContent(reqBody, Encoding.UTF8, "application/json"); CookieContainer cookies = new CookieContainer(); HttpClientHandler handler = new HttpClientHandler(); handler.CookieContainer = cookies; HttpClient client = new HttpClient(handler); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); HttpResponseMessage resp = null; try { resp = client.SendAsync(req).Result; } catch (Exception ex) { throw new Exception("Something went wrong"); } if (!resp.IsSuccessStatusCode) { string message; if (resp.StatusCode == HttpStatusCode.Unauthorized || resp.StatusCode == HttpStatusCode.Forbidden || resp.StatusCode == HttpStatusCode.Redirect) message = "Permission denied."; else message = resp.ReasonPhrase; throw new Exception(message); } IEnumerable<Cookie> responseCookies = cookies.GetCookies(uri).Cast<Cookie>(); if (responseCookies.FirstOrDefault() != null) return responseCookies.FirstOrDefault(); return null; } Here is my method from my API: [HttpPost, Route("LogIn")] public IActionResult LogIn([FromServices] UserService userService, [FromBody]LoginModel login) { using (var session = SessionFactory.OpenSession()) using (var transaction = session.BeginTransaction()) { User user = userService.Login(session, login.UserName, login.PassWord); if (user == null) return BadRequest("Invalid user"); var identity = new ClaimsIdentity("FileSystem"); identity.AddClaim(new Claim(ClaimTypes.Name, login.UserName)); foreach (Role r in user.Roles) { identity.AddClaim(new Claim(ClaimTypes.Role, r.Nome)); } var principal = new ClaimsPrincipal(identity); HttpContext.Authentication.SignInAsync("FileSystem", principal).Wait(); } return Ok(); }
Try adding this method to your Global.asax : protected void Application_BeginRequest(object sender, EventArgs e) { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS, DELETE, PUT"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Authentication"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "86400"); HttpContext.Current.Response.End(); } else { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Credentials", "true"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, OPTIONS, DELETE"); } }
Managing strings is a tricky task in C. Code with years of success can fail when an unexpected situation exist. Consider the format "%02d/%02d/%4d %02d:%02d". This would usually expect an array of size 16 + 1 (for the null character). This is the same type of coding that made for Y2K bugs as this one needs more space after the year 9999. Consider a system that allowed time_t to represent time into the far future and and tried forming a date/time string based in its max value --> buffer overflow. Instead, allow for all potential values in struct tm and provide a generous temporary buffer. Then allocate. #include <stdio.h> #include <stdlib.h> #include <time.h> // Max length needed for a `int` as decimal text #define INT_STR_LEN (sizeof(int)*CHAR_BIT/3 + 2) #define TIME2STR_FMT "%02d/%02d/%04d %02d:%02d" // Worst case size - and them some #define TIME2STR_SZ (sizeof TIME2STR_FMT + 5*INT_STR_LEN) char *time2str(time_t time) { struct tm *info = localtime(&time); if (info == NULL) return NULL; char buf[TIME2STR_SZ]; int n = snprintf(buf, sizeof buf, TIME2STR_FMT, info->tm_mon + 1, info->tm_mday, info->tm_year + 1900, info->tm_hour, info->tm_min); if (n < 0 || n >= sizeof buf) return NULL; // Allocate and copy size_t sz = strlen(buf) + 1; char *time_s = malloc(sz); if (time_s) { memcpy(time_s, buf, sz); } return time_s; } int main(void) { time_t t; puts(time2str(time(&t))); return 0; }
Finally, I found the problem. The authentication guard was just delivering the Observable from this.authService.isLoggedInObservable() method. It doesn't deliver the proper value for the routes to know whether the user is actually logged in or not. If you see in the repo, I use Observable<boolean> to tell the other components/routes whether I've logged in or not. A workaround I did was to actually store a private variable inside the guard. I did this so that the canActivate() method inside the guard only returns that private variable: true means I'm logged in, false otherwise. How to let that private variable know that I'm now logged in, and its value needs to change? Within the constructor I made sure that the guard was subscribing for the Observable with that boolean value, and update that variable accordingly. I just changed the code from AuthenticationGuard. Nothing less, nothing more. import { Injectable } from "@angular/core"; import { Router, CanActivate } from "@angular/router"; import { Observable } from "rxjs"; import { AuthenticationService } from "./authentication.service"; @Injectable() export class AuthenticationGuard implements CanActivate { private isLoggedIn: boolean; // to store the "logged in" state constructor( private router: Router, private authService: AuthenticationService) { this.authService.isLoggedInObservable().subscribe((val) => { this.isLoggedIn = val; // update as subscribed // redirect to login page if not logged in yet if (!val) this.router.navigate(["/login"]); }); } canActivate() { // only returns that private variable return this.isLoggedIn; } }
So to answer the question (just for clarity instead in the comments). Thanks to Maximilian Gerhardt who gave the answer (I will set you as best answer if you want but I can't just from the comments!). There are two ways that are good for this: Download psexec.exe onto the "victim" pc and use that with psexec.exe -s -d -i [here the session token "1" works for me] calc.exe If using a meterpreter shell you can use incognito mode (offensive-security.com/metasploit-unleashed/fun-incognito). And then use the impersonate_token method. This works great, but I cannot go back to being SYSTEM (getsystem doesn't work as there are no privilege escalation vulnerabilities present). So I have to exit and reuse the exploit. But for the workshop this works beautifully! For those interested I use SLMail 5.5 on a W7 machine to show how easy "hacking" can be and what a hacker then can do with a computer. This for an awareness workshop, which is bigger then just this "show and tell" part. steps: nmap scan on port 110 with version detection to see "hey what is this? SLMail?" google SLMail to find "Oh noes a buffer overflow, hmmmmm let's look into that!" this is metasploit a tool hackers can use to exploit know systems (I have the manually made exploit with more explanation for interested people after the workshop with buffer overflow explained) search in metasploit for SLMail, we find it and say use "it works how cool! What can we do with it?" show webcam capture! (that is scary stuff :D). Go to shell and show with whoami for the tech people that we are indeed system. then go to incognito mode and steal the token from the user that we see on the screen. open up youtube with "hackerman" video (well had to choose one :D) explain a bit that it is that easy for a script kiddy to get in if you don't update etc. etc. etc. let awareness kick in and next time they do something dumb they might think: "o wait let's not do that!" Cheers!
You need to protect the routes by yourself. Since the order in which routes are defined matters, you would do eg. // Obviously cannot be protected app.get('/login', function(req, res) { res.send(...); }); // Authentication app.post('/login', passport.authenticate('strategy', { successReturnToOrRedirect: '/', failureRedirect: '/login' })); // A random unprotected route app.get('/unprotected', function(req, res) {}); // From now on all routes require authentication app.all('/*', ensureLoggedIn('/login')); // Root of domain for authenticated users only app.get('/', function(req, res) { res.send(...); }); The connect-ensure-login module just defines a simple middleware and you could easily define your own that would do just what you need. I believe many or maybe even most use even simpler middleware to detect authenticated users like this: var isAuthenticated = function(req, res, next) { if (req.isAuthenticated()) { return next(); } else { return res.redirect('/login'); } };
Difference Between SSLCACertificateFile and SSLCertificateChainFile SSLCertificateChainFile is generally the correct option to choose, as it has the least impact; it causes the listed file to be sent along with the certificate to any clients that connect. Provide all the Root CA into the following file to resolve the issue SSLCACertificateFile (hereafter "CACert") does everything SSLCertificateChainFile does (hereafter "Chain"), and additionally permits the use of the cert in question to sign client certificates. This sort of authentication is quite rare (at least for the moment), and if you aren't using it, there's IMHO no reason to augment its functionality by using CACert instead of Chain. On the flipside, one could argue that there's no harm in the additional functionality, and CACert covers all cases. Both arguments are valid. Needless to say, if you ask the cert vendor, they'll always push for CACert over Chain, since it gives them another thing (client certs) that they can potentially sell you down the line. ;)
I have implemented dual authentication in the following way.  session_controller.rb def create  if (params[:log]=="local")              self.resource = warden.authenticate!(:database_authenticatable)               sign_in(resource_name, resource)                       yield resource if block_given?                           respond_with resource, location: after_sign_in_path_for(resource)                  else                                                           self.resource = warden.authenticate!(:ldap_authenticatable)                               sign_in(resource_name, resource)                       yield resource if block_given?                           respond_with resource, location: after_sign_in_path_for(resource)                        end   end user.rb class User < ActiveRecord::Base     devise :ldap_authenticatable, :database_authenticatable,:registerable,         :recoverable, :rememberable, :trackable, :validatable      **and view devise/sessions/new.html.erb** <%= form_for(:user, :url => session_path(:user)) do |f| %>   <div class="form-inputs">  <%= f.text_field :username ,:placeholder => "Login id"  %><br> <br>   <%= f.password_field :password,:placeholder => "Password"  %>    <label for="check_box_type">Login Server </label><%= select_tag :log, options_for_select([ [" Domain Server","domain"],["Local Server", "local"]])%>   <%= f.submit 'Sign in' %> Here according to the user input (login server :local/domain] it will login.
I cannot compile that, the compiler throws countless errors, I was looking for other solutions for fast string encryption and found out about this little toy https://www.stringencrypt.com (wasn't hard, 1st result in Google for string encryption keyword). This is how it works: You enter the label name say sString You enter the string contents You click Encrypt It takes the string and encrypts it It generates decryption source code in C++ (many other language are supported) You paste this snippet in your code Example string "StackOverflow is awesome!", the output code (every single time it generates slightly different code). It supports both ANSI (char) and UNICODE (wchar_t) type strings ANSI output: // encrypted with https://www.stringencrypt.com (v1.1.0) [C/C++] // sString = "StackOverflow is awesome!" unsigned char sString[26] = { 0xE3, 0x84, 0x2D, 0x08, 0xDF, 0x6E, 0x0B, 0x87, 0x51, 0xCF, 0xA2, 0x07, 0xDE, 0xCF, 0xBF, 0x73, 0x1C, 0xFC, 0xA7, 0x32, 0x7D, 0x64, 0xCE, 0xBD, 0x25, 0xD8 }; for (unsigned int bIFLw = 0, YivfL = 0; bIFLw < 26; bIFLw++) { YivfL = sString[bIFLw]; YivfL -= bIFLw; YivfL = ~YivfL; YivfL = (((YivfL & 0xFF) >> 7) | (YivfL << 1)) & 0xFF; YivfL ++; YivfL ^= 0x67; YivfL = (((YivfL & 0xFF) >> 6) | (YivfL << 2)) & 0xFF; YivfL += bIFLw; YivfL += 0x0F; YivfL = ((YivfL << 4) | ( (YivfL & 0xFF) >> 4)) & 0xFF; YivfL ^= 0xDA; YivfL += bIFLw; YivfL ++; sString[bIFLw] = YivfL; } printf(sString); UNICODE output: // encrypted with https://www.stringencrypt.com (v1.1.0) [C/C++] // sString = "StackOverflow is awesome!" wchar_t sString[26] = { 0x13A6, 0xA326, 0x9AA6, 0x5AA5, 0xEBA7, 0x9EA7, 0x6F27, 0x55A6, 0xEB24, 0xD624, 0x9824, 0x58A3, 0x19A5, 0xBD25, 0x62A5, 0x56A4, 0xFC2A, 0xC9AA, 0x93AA, 0x49A9, 0xDFAB, 0x9EAB, 0x9CAB, 0x45AA, 0x23CE, 0x614F }; for (unsigned int JCBjr = 0, XNEPI = 0; JCBjr < 26; JCBjr++) { XNEPI = sString[JCBjr]; XNEPI -= 0x5D75; XNEPI = (((XNEPI & 0xFFFF) >> 14) | (XNEPI << 2)) & 0xFFFF; XNEPI = ~XNEPI; XNEPI -= 0xA6E5; XNEPI ^= JCBjr; XNEPI = (((XNEPI & 0xFFFF) >> 10) | (XNEPI << 6)) & 0xFFFF; XNEPI --; XNEPI ^= 0x9536; XNEPI += JCBjr; XNEPI = ((XNEPI << 1) | ( (XNEPI & 0xFFFF) >> 15)) & 0xFFFF; sString[JCBjr] = XNEPI; } wprintf(sString); Now I know it might not be the perfect solution, but it works for me and my compiler.
I was surprised when I came in this morning and saw a notice on the screen of one that a scheduled software update as a software developer I cannot understand your surprise. It's a very well known (and often criticise feature due to slow/delayed roll out) feature of the OS I have no idea where the upgrade is coming from or how it's initiated Those come from the device manufacturer (you said Samsung, right?) and do not need a login or account of any type. It's coded somewhere deep inside the OS to check the manufacturer server for updates. Same that happens with Windows, Mac OS, Linux or iOS. There is absolutely nothing an app can do to disable the OS update from an API point of view. This would be a major security flaw. One can easily imagine a malicious app exploiting a known OS vulnerability and blocking the OS from update itself that would patch the vulnerability. possible solutions for your case Apart from creating your own custom OS to control the process the only possible way that I can think of, is to host your own VPN server that blocks the update server (or blocks the whole internet expect the resources you want to access from your app) and configure the device to this VPN under Settings -> WiFi. ps.: I saw the mentioned link and I would advise against disabling system services (or at least test A LOT after you diable it) because that could cause other issues.
For anybody else coming here looking for this info, here is sample code that demonstrates exactly what OP (and I) wanted (based on excellent info from Remus above): -- how to sign a stored procedure so it can access other Databases on same server -- adapted from this very helpful article -- http://rusanu.com/2006/03/01/signing-an-activated-procedure/ USE [master] GO CREATE DATABASE TempDB1 CREATE DATABASE OtherDB2 GO USE TempDB1 GO -- create a user for TempDB1 CREATE USER [foo] WITHOUT LOGIN GO CREATE PROCEDURE TempDB1_SP AS BEGIN CREATE TABLE OtherDB2.dbo.TestTable (ID int NULL) IF @@ERROR=0 PRINT 'Successfully created table.' END GO GRANT EXECUTE ON dbo.TempDB1_SP TO [foo] GO EXECUTE AS User='foo' PRINT 'Try to run an SP that accesses another database:' EXECUTE dbo.TempDB1_SP GO REVERT -- Output: Msg 916, Level 14, State 1, Procedure TempDB1_SP, Line 5 -- [Batch Start Line 14] -- The server principal "..." is not able to access the database -- "OtherDB2" under the current security context. PRINT '' PRINT 'Fix: Try again with signed SP...' -- Create cert with private key to sign the SP with. -- Password not important, will drop private key USE TempDB1 GO -- create a self-signed cert CREATE CERTIFICATE [DB_Cert] ENCRYPTION BY PASSWORD = 'Password1' WITH SUBJECT = 'Signing for cross-DB SPs'; -- Sign the procedure with the certificate’s private key ADD SIGNATURE TO OBJECT::[TempDB1_SP] BY CERTIFICATE [DB_Cert] WITH PASSWORD = 'Password1' -- Drop the private key. This way it cannot be used again to sign other procedures. ALTER CERTIFICATE [DB_Cert] REMOVE PRIVATE KEY -- Copy the public key part of the cert to [master] database -- backup to a file and create cert from file in [master] BACKUP CERTIFICATE [DB_Cert] TO FILE = 'C:\Users\Public\DBCert.cer' USE [OtherDB2] -- or use [master] = all DBs on server accessible GO CREATE CERTIFICATE [DB_Cert] FROM FILE = 'C:\Users\Public\DBCert.cer'; -- the 'certificate user' carries the permissions that are automatically granted -- when the signed SP accesses other Databases CREATE USER [DB_CertUser] FROM CERTIFICATE [DB_Cert] GRANT CREATE TABLE TO [DB_CertUser] -- or whatever other permissions are needed GO USE TempDB1 EXECUTE dbo.TempDB1_SP GO -- output: 'Successfully created table.' -- clean up: everything except the cert file, have to delete that yourself sorry USE [master] GO DROP DATABASE TempDB1 DROP DATABASE OtherDB2 GO
You could also use PHPMailer class at https://github.com/PHPMailer/PHPMailer . It allows you to use the mail function or use an smtp server transparently . It also handles HTML based emails and attachments so you don't have to write your own implementation. <?php require 'PHPMailerAutoload.php'; $mail = new PHPMailer; $mail->isSMTP(); // Set mailer to use SMTP $mail->Host = 'smtp1.example.com;smtp2.example.com'; // Specify main and backup SMTP servers $mail->SMTPAuth = true; // Enable SMTP authentication $mail->Username = '[email protected]'; // SMTP username $mail->Password = 'secret'; // SMTP password $mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted $mail->From = '[email protected]'; $mail->FromName = 'Mailer'; $mail->addAddress('[email protected]', 'Joe User'); // Add a recipient $mail->addAddress('[email protected]'); // Name is optional $mail->addReplyTo('[email protected]', 'Information'); $mail->addCC('[email protected]'); $mail->addBCC('[email protected]'); $mail->WordWrap = 50; // Set word wrap to 50 characters $mail->addAttachment('/var/tmp/file.tar.gz'); // Add attachments $mail->addAttachment('/tmp/image.jpg', 'new.jpg'); // Optional name $mail->isHTML(true); // Set email format to HTML $mail->Subject = 'Here is the subject'; $mail->Body = 'This is the HTML message body <b>in bold!</b>'; $mail->AltBody = 'This is the body in plain text for non-HTML mail clients'; if(!$mail->send()) { echo 'Message could not be sent.'; echo 'Mailer Error: ' . $mail->ErrorInfo; } else { echo 'Message has been sent'; }
OAuth was possibly made so popular due to its adoption by major social players like Google, Facebook and Twitter. (1) Having said that you can and it's indeed already being used across a wide range of applications that have nothing to do with social logins. (2) Before OAuth2, enterprises were mostly using SAML or WS-Federation to solve authentication and authorization related issues. The most common scenario for these protocols was to implement a SSO (Single Sign On) solution. Although they are still being actively used today, the tendency would be for you to adopt OAuth2 and/or OpenID Connect as alternatives. (3) Like you said, if you have a system that consumes tokens it will probably will not care which technology is used to generate the tokens and instead is only concerned in ensuring the token is valid. This would mean that yes, you can generate the tokens yourself as long as they meet the consumer criteria (or you adapt the consumer to meet the producer criteria). You should, however, consider a few things... It's really easy to make authentication work in the sense - yay, my user can authenticate. It's significantly complex to do it in a secure way so that you don't end up with - damn, my application just got owned. Having the possibility to do so you should delegate everything you can to a trusted third-party library or service that is focused on authentication and that will keep up the pace in the always changing security landscape. If you're looking for options I would recommend checking Auth0; of course you should know that I'm biased because I ended up working there.
A very detailed answer (and a full one) can be found here. This is the very short brief of it so you should read the full one above. First of all its much better to use ssh keys instead of username password so you will not be prompt for those again. If you still wish to use username/password pair you need to set the credential.helper flag. https://www.kernel.org/pub/software/scm/git/docs/gitcredentials.html From the git config documentation: credential.helper Specify an external helper to be called when a username or password credential is needed; the helper may consult external storage to avoid prompting the user for the credentials. Note that multiple helpers may be defined. See gitcredentials(7) for details. credential.useHttpPath When acquiring credentials, consider the "path" component of an http or https URL to be important. Defaults to false. See gitcredentials(7) for more information. credential.username If no username is set for a network authentication, use this username by default. See credential..* below, and gitcredentials(7).
Auth0 comes with a database on the free account. When you add the login registration widget to your application and a user signs up it adds them to the database in your auth0 account. You can see information about the process here What I do is authenticate users with the auth0 widget. This allows auth0 to handle encryption and security. Then when a user logs in i request a profile in the response. Typically this gives me at least basic info like an email address. I create my own database using the email address as a unique key which allows me to serve the correct data to the user when they login. Here is an example of my auth0 service using a widget and requesting the user's profile in the response then storing it to local storage. import { Injectable } from '@angular/core'; import { tokenNotExpired, JwtHelper } from 'angular2-jwt'; import { Router } from '@angular/router'; import { myConfig } from './auth.config'; declare var Auth0Lock: any; var options = { theme: { logo: '/img/logo.png', primaryColor: '#779476' }, languageDictionary: { emailInputPlaceholder: "[email protected]", title: "Login or SignUp" }, }; @Injectable() export class Auth { lock = new Auth0Lock(myConfig.clientID, myConfig.domain, options, {}); userProfile: Object; constructor(private router: Router) { this.userProfile = JSON.parse(localStorage.getItem('profile')); this.lock.on('authenticated', (authResult: any) => { localStorage.setItem('access_token', authResult.idToken); this.lock.getProfile(authResult.idToken, (error: any, profile: any) => { if (error) { console.log(error); return; } localStorage.setItem('profile', JSON.stringify(profile)); this.userProfile = profile; this.router.navigateByUrl('/overview'); }); this.lock.hide(); }); } public login() { this.lock.show(); } private get accessToken(): string { return localStorage.getItem('access_token'); } public authenticated(): boolean { try { var jwtHelper: JwtHelper = new JwtHelper(); var token = this.accessToken; if (jwtHelper.isTokenExpired(token)) return false; return true; } catch (err) { return false; } } public logout() { localStorage.removeItem('profile'); localStorage.removeItem('access_token'); this.userProfile = undefined; this.router.navigateByUrl('/home'); }; }